Technology

close all order mql4

close all order mql4
close all order mql4 | SiamCafe Blog
2025-06-19· อ. บอม — SiamCafe.net· 11,058 คำ

Close All MQL4

Close All Order MQL4 OrderClose Function Loop Strategy Error Handling Magic Number Filter Retry Slippage RefreshRates Expert Advisor Production Trading

FunctionParametersReturnDescription
OrderClose()ticket, lots, price, slippage, colorboolปิดออเดอร์
OrderDelete()ticket, colorboolลบ Pending Order
OrderSelect()index, select_by, poolboolเลือกออเดอร์
OrdersTotal()noneintจำนวนออเดอร์ทั้งหมด
OrderType()noneintประเภท Buy/Sell/Pending
OrderTicket()noneintหมายเลข Ticket
OrderMagicNumber()noneintMagic Number ของ EA
GetLastError()noneintรหัส Error ล่าสุด

Basic Close All

// === Close All Orders — Basic Version ===

// void CloseAllOrders()
// {
//     for(int i = OrdersTotal() - 1; i >= 0; i--)
//     {
//         if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
//             continue;
//
//         // Skip if not current symbol
//         if(OrderSymbol() != Symbol())
//             continue;
//
//         int ticket = OrderTicket();
//         double lots = OrderLots();
//         int type = OrderType();
//
//         bool result = false;
//
//         if(type == OP_BUY)
//         {
//             RefreshRates();
//             result = OrderClose(ticket, lots, Bid, 3, clrRed);
//         }
//         else if(type == OP_SELL)
//         {
//             RefreshRates();
//             result = OrderClose(ticket, lots, Ask, 3, clrBlue);
//         }
//         else // Pending orders (OP_BUYLIMIT, OP_SELLLIMIT, etc.)
//         {
//             result = OrderDelete(ticket, clrYellow);
//         }
//
//         if(!result)
//         {
//             int err = GetLastError();
//             Print("Close failed ticket:", ticket, " error:", err);
//         }
//         else
//         {
//             Print("Closed ticket:", ticket, " type:", type, " lots:", lots);
//         }
//     }
// }

from dataclasses import dataclass

@dataclass
class OrderType:
    type_id: int
    name: str
    close_price: str
    close_function: str
    description: str

order_types = [
    OrderType(0, "OP_BUY", "Bid", "OrderClose()", "Market Buy — ปิดที่ราคา Bid"),
    OrderType(1, "OP_SELL", "Ask", "OrderClose()", "Market Sell — ปิดที่ราคา Ask"),
    OrderType(2, "OP_BUYLIMIT", "N/A", "OrderDelete()", "Pending Buy Limit — ลบ"),
    OrderType(3, "OP_SELLLIMIT", "N/A", "OrderDelete()", "Pending Sell Limit — ลบ"),
    OrderType(4, "OP_BUYSTOP", "N/A", "OrderDelete()", "Pending Buy Stop — ลบ"),
    OrderType(5, "OP_SELLSTOP", "N/A", "OrderDelete()", "Pending Sell Stop — ลบ"),
]

print("=== Order Types ===")
for o in order_types:
    print(f"  [{o.type_id}] {o.name} | Price: {o.close_price}")
    print(f"    Function: {o.close_function} | {o.description}")

Advanced Close with Filter

// === Close All Orders — Advanced with Magic Number ===

// input int MagicNumber = 12345;
// input int Slippage = 5;
// input int MaxRetries = 3;
//
// bool CloseOrder(int ticket, int type, double lots)
// {
//     for(int retry = 0; retry < MaxRetries; retry++)
//     {
//         RefreshRates();
//         double price = (type == OP_BUY) ? Bid : Ask;
//         bool result = OrderClose(ticket, lots, price, Slippage);
//
//         if(result)
//         {
//             Print("OK: Closed #", ticket, " at ", price);
//             return true;
//         }
//
//         int err = GetLastError();
//         Print("Retry ", retry+1, "/", MaxRetries, " ticket:", ticket, " err:", err);
//
//         if(err == 4108) return true; // Already closed
//         if(err == 129 || err == 138) { Sleep(200); continue; }
//         if(err == 146) { Sleep(500); continue; } // Trade context busy
//
//         Sleep(100);
//     }
//     return false;
// }
//
// void CloseAllFiltered()
// {
//     int closed = 0, failed = 0, pending = 0;
//
//     for(int i = OrdersTotal() - 1; i >= 0; i--)
//     {
//         if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
//         if(OrderSymbol() != Symbol()) continue;
//         if(OrderMagicNumber() != MagicNumber) continue;
//
//         int type = OrderType();
//
//         if(type <= OP_SELL) // Market orders
//         {
//             if(CloseOrder(OrderTicket(), type, OrderLots()))
//                 closed++;
//             else
//                 failed++;
//         }
//         else // Pending orders
//         {
//             if(OrderDelete(OrderTicket()))
//                 pending++;
//             else
//                 failed++;
//         }
//     }
//
//     Print("Summary: Closed=", closed, " Pending=", pending, " Failed=", failed);
// }

@dataclass
class ErrorCode:
    code: int
    name: str
    cause: str
    fix: str

errors = [
    ErrorCode(129, "ERR_INVALID_PRICE", "ราคาไม่ถูกต้อง", "RefreshRates() ก่อน Close"),
    ErrorCode(130, "ERR_INVALID_STOPS", "SL/TP ไม่ถูกต้อง", "ตรวจ Stop Level"),
    ErrorCode(138, "ERR_REQUOTE", "ราคาเปลี่ยนระหว่าง Close", "เพิ่ม Slippage หรือ Retry"),
    ErrorCode(146, "ERR_TRADE_CONTEXT_BUSY", "Trade Context ถูกใช้งาน", "Sleep แล้ว Retry"),
    ErrorCode(4108, "ERR_INVALID_TICKET", "Ticket ไม่ถูกต้อง", "ออเดอร์ถูกปิดแล้ว ข้ามได้"),
    ErrorCode(4051, "ERR_INVALID_FUNCTION_PARAM", "Parameter ไม่ถูกต้อง", "ตรวจ Lots Price"),
]

print("\n=== Common Errors ===")
for e in errors:
    print(f"  [{e.code}] {e.name}")
    print(f"    Cause: {e.cause}")
    print(f"    Fix: {e.fix}")

Production EA Integration

// === Production EA — Close Buttons ===

// // Close All Buy Orders
// void CloseAllBuy()
// {
//     for(int i = OrdersTotal()-1; i >= 0; i--)
//     {
//         if(!OrderSelect(i, SELECT_BY_POS)) continue;
//         if(OrderSymbol() != Symbol()) continue;
//         if(OrderMagicNumber() != MagicNumber) continue;
//         if(OrderType() == OP_BUY)
//         {
//             RefreshRates();
//             OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, clrRed);
//         }
//     }
// }
//
// // Close All Sell Orders
// void CloseAllSell()
// {
//     for(int i = OrdersTotal()-1; i >= 0; i--)
//     {
//         if(!OrderSelect(i, SELECT_BY_POS)) continue;
//         if(OrderSymbol() != Symbol()) continue;
//         if(OrderMagicNumber() != MagicNumber) continue;
//         if(OrderType() == OP_SELL)
//         {
//             RefreshRates();
//             OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, clrBlue);
//         }
//     }
// }
//
// // Close Profitable Orders Only
// void CloseProfitable()
// {
//     for(int i = OrdersTotal()-1; i >= 0; i--)
//     {
//         if(!OrderSelect(i, SELECT_BY_POS)) continue;
//         if(OrderSymbol() != Symbol()) continue;
//         if(OrderProfit() > 0)
//         {
//             int type = OrderType();
//             double price = (type == OP_BUY) ? Bid : Ask;
//             OrderClose(OrderTicket(), OrderLots(), price, Slippage);
//         }
//     }
// }

@dataclass
class CloseStrategy:
    name: str
    condition: str
    use_case: str
    risk: str

strategies = [
    CloseStrategy("Close All", "ปิดทุกออเดอร์", "Emergency exit ปิดทุกอย่างทันที", "High — ปิดทั้งกำไรและขาดทุน"),
    CloseStrategy("Close Buy Only", "OrderType() == OP_BUY", "ปิดเฉพาะ Buy เมื่อตลาดกลับตัว", "Medium — เก็บ Sell ไว้"),
    CloseStrategy("Close Sell Only", "OrderType() == OP_SELL", "ปิดเฉพาะ Sell เมื่อตลาดขึ้น", "Medium — เก็บ Buy ไว้"),
    CloseStrategy("Close Profitable", "OrderProfit() > 0", "เก็บกำไรที่มี ถือขาดทุนต่อ", "Medium — ยังมี Losing"),
    CloseStrategy("Close Losing", "OrderProfit() < 0", "ตัดขาดทุน ถือกำไรต่อ", "Low — เก็บ Profit"),
    CloseStrategy("Close by Magic", "OrderMagicNumber() == X", "ปิดเฉพาะ EA ตัวนี้", "Low — ไม่กระทบ EA อื่น"),
    CloseStrategy("Close by Symbol", "OrderSymbol() == X", "ปิดเฉพาะ Pair นี้", "Low — ไม่กระทบ Pair อื่น"),
]

print("Close Strategies:")
for s in strategies:
    print(f"  [{s.name}] Condition: {s.condition}")
    print(f"    Use: {s.use_case}")
    print(f"    Risk: {s.risk}")

เคล็ดลับ

การนำความรู้ไปประยุกต์ใช้งานจริง

แหล่งเรียนรู้ที่แนะนำ ได้แก่ Official Documentation ที่อัพเดทล่าสุดเสมอ Online Course จาก Coursera Udemy edX ช่อง YouTube คุณภาพทั้งไทยและอังกฤษ และ Community อย่าง Discord Reddit Stack Overflow ที่ช่วยแลกเปลี่ยนประสบการณ์กับนักพัฒนาทั่วโลก

ปิดออเดอร์ทั้งหมดด้วย MQL4 อย่างไร

OrderClose() Loop OrdersTotal()-1 ลงมา 0 OrderSelect() OrderType() Buy Bid Sell Ask RefreshRates() GetLastError() Retry

ทำไมต้อง Loop จากหลังไปหน้า

ปิดออเดอร์ OrdersTotal() ลดลง Index เปลี่ยน Loop หน้าไปหลังข้าม Index Loop หลังไปหน้าปลอดภัย ออเดอร์ที่ยังไม่ปิดไม่เปลี่ยน Index

กรองออเดอร์ด้วย Magic Number อย่างไร

OrderMagicNumber() เปรียบเทียบ Magic Number EA ตรงจึงปิด ป้องกันปิดออเดอร์ EA อื่น Manual Trade Input Parameter OrderSymbol()

จัดการ Error อย่างไร

GetLastError() 129 Invalid Price RefreshRates 138 Requote Retry 4108 Invalid Ticket ปิดแล้ว 146 Trade Context Busy Sleep Retry 3-5 ครั้ง Log

สรุป

Close All Order MQL4 OrderClose Loop Strategy Magic Number Filter Error Handling Retry RefreshRates Slippage Expert Advisor Production Trading

📖 บทความที่เกี่ยวข้อง

close all order mt4อ่านบทความ → close all order mt4 มือถือ iosอ่านบทความ → mql4 close all ordersอ่านบทความ → mql4 close orderอ่านบทความ → close all mt5อ่านบทความ →

📚 ดูบทความทั้งหมด →