β CloseOrder (GoMT4)¶
Goal: correctly close an open market order (BUY/SELL) with retry logic and proper rounding.
Real code refs:
- Account methods:
examples/mt4/MT4Account.go(OrderClose)- Example:
examples/mt4/MT4_service.go(ShowOrderCloseExample)
β 1) Preconditions¶
- You know the ticket of the order you want to close.
- The order is open (check via
ShowOpenedOrdersor similar). - MT4 terminal is running & connected.
π 2) Get order & quote¶
ord, err := account.OrderByTicket(ctx, ticket)
if err != nil { return err }
q, err := account.Quote(ctx, ord.GetSymbol())
if err != nil { return err }
βοΈ 3) Prepare close params¶
- Use Bid to close a BUY.
- Use Ask to close a SELL.
- Round price to
Digits.
info, _ := account.SymbolParams(ctx, ord.GetSymbol())
digits := int(info.GetDigits())
var closePrice float64
if ord.GetType() == pb.OrderType_OP_BUY {
closePrice = roundPrice(q.GetBid(), digits)
} else if ord.GetType() == pb.OrderType_OP_SELL {
closePrice = roundPrice(q.GetAsk(), digits)
}
slippage := int32(5)
π 4) Call OrderClose¶
resp, err := account.OrderClose(
ctx,
ticket,
ord.GetVolume(),
&closePrice,
&slippage,
)
if err != nil {
return fmt.Errorf("close failed: %w", err)
}
fmt.Printf("β
Closed ticket=%d at price=%.5f time=%s\n",
ticket, resp.GetPrice(), resp.GetCloseTime().AsTime())
β οΈ Pitfalls¶
- Invalid price β always round to
Digits. - Wrong side β BUY closes at Bid, SELL closes at Ask.
- Partial close β adjust
volumeparameter if closing partially. - Timeout β wrap in
context.WithTimeout(ctx, 5*time.Second). - Retries β transport errors autoβretried inside helper.
π Variations¶
- Partial close: send smaller volume than
ord.GetVolume(). - Loop over all open orders: call
ShowOpenedOrdersβ close each. - Close by order: see
CloseByOrders.mdrecipe.
π See also¶
ModifyOrder.mdβ adjust SL/TP instead of closing.DeletePending.mdβ remove a pending order.HistoryOrders.mdβ verify closed orders in history.