Orders
Members of MT5API that place, change and close trades. Each has a blocking form that waits for the broker's answer, an async Task form, and a low-level fire-and-forget form that reports through events.
Before any trade call:
- The account must allow trading (
IsTradeAllowed, see account.md). - The symbol must exist and its group must allow the direction.
- Lots are in lots (
0.10), prices in price units.
OrderSend
Order OrderSend(string symbol, double lots, double price, OrderType type, double sl = 0.0, double tp = 0.0, ulong deviation = 0, string comment = null, long expertID = 0, FillPolicy fillPolicy = FillPolicy.Any, TradeType tradeType = TradeType.Transfer, double stoplimit = 0.0, Expiration expiration = null, long closeByTicket = 0, PlacedType placedType = PlacedType.Manually)
Opens a market position or places a pending order. Blocks until the broker accepts and fills it, or until ExecutionTimeout passes. Subscribes the symbol after a market fill.
Parameters:
symbol: the symbol, for example"EURUSD".lots: volume in lots.price: the price you expect. For market orders use the current ask (buy) or bid (sell). For pending orders it is the trigger price.type:OrderType.Buy,Sell,BuyLimit,SellLimit,BuyStop,SellStop,BuyStopLimitorSellStopLimit.sl,tp: stop loss and take profit prices.0means none.deviation: the largest price slip you accept. The broker defines the unit; it is usually points.comment: text stored with the order.expertID: your own number to tag orders (a "magic number").fillPolicy:FillOrKill,ImmediateOrCancel,FlashFillorAny.Anylets the library pick one that fits the symbol.tradeType: leave the default.stoplimit: the limit price forBuyStopLimitandSellStopLimit.expiration: for pending orders.new Expiration { Type = ExpirationType.Specified, DateTime = ... }. Null means good till cancelled.closeByTicket: used to close one position with an opposite one. Usually 0.placedType: the "placed by" tag.Manuallyusesapi.PlacedType.
Returns: the Order (see positions-and-history.md) with Ticket, OpenPrice, Lots and so on.
Throws:
InvestorModeException: the account is read-only.Exception: trading is off for the account or the symbol, or the symbol is close-only, long-only or short-only against your direction.InvalidSymbolExceptionorException("Symbol not found: ..."): the symbol does not exist.ServerException: the broker refused. ReadCode(for exampleMsg.NO_MONEY,Msg.MARKET_CLOSED,Msg.INVALID_VOLUME,Msg.INVALID_STOPS,Msg.REQUOTE). See errors.md.TimeoutException: no answer withinExecutionTimeout. The trade may still have happened: checkGetOpenedOrdersbefore you retry.
Quote q = api.GetQuote("EURUSD", 5000);
try
{
Order o = api.OrderSend("EURUSD", 0.10, q.Ask, OrderType.Buy,
sl: q.Ask - 0.0050, tp: q.Ask + 0.0100,
deviation: 20, comment: "my bot");
Console.WriteLine($"Opened #{o.Ticket} at {o.OpenPrice}");
}
catch (ServerException ex) { Console.WriteLine($"Refused: {ex.Code}"); }Pending order that expires in one day:
var exp = new Expiration { Type = ExpirationType.Specified, DateTime = api.ServerTime.AddDays(1) };
api.OrderSend("EURUSD", 0.10, 1.0500, OrderType.BuyLimit, expiration: exp);Task<Order> OrderSendAsyncTask(...)
Same parameters, return value and errors as OrderSend. Use await.
void OrderSendAsync(int requestId, string symbol, double lots, double price, OrderType type, ...)
Sends the request and returns at once. It does not wait. Get a number from GetRequestId(), pass it as requestId, and watch OnOrderProgress and OnOrderUpdate for the answer (TradeRequest.RequestId matches your number). Same parameters as OrderSend after requestId.
- Throws: the trading checks listed above (
InvestorModeException,InvalidSymbolException,Exceptionwhen trading is off). Broker refusals arrive as events.
int GetRequestId()
Returns a new request number that is unique in this process.
OrderClose
Order OrderClose(long ticket, string symbol, double price, double lots, OrderType type, ulong deviation = 0, FillPolicy fillPolicy = FillPolicy.Any, long expertId = 0, string comment = null, long closeByTicket = 0, PlacedType placedType = PlacedType.Manually)
Closes a position, fully or in part. For a pending order it deletes the order. Blocks until done.
ticket: the ticket of the position or order.symbol: its symbol.price: the current price. For a buy position use the bid. For a sell position use the ask.lots: the volume to close. Use the position'sLotsto close it all. Less closes part of it.type: the type of the position or order you are closing (Buyfor a buy position). The library sends the opposite deal.deviation,fillPolicy,expertId,comment,closeByTicket,placedType: as inOrderSend.
Returns: the Order after the close.
Throws: the same as OrderSend, plus Exception("Request Lots = 0 ") when lots is 0.
Order pos = api.GetOpenedOrder(ticket); Quote q = api.GetQuote(pos.Symbol, 5000); double price = pos.OrderType == OrderType.Buy ? q.Bid : q.Ask; api.OrderClose(pos.Ticket, pos.Symbol, price, pos.Lots, pos.OrderType, deviation: 20);
Task<Order> OrderCloseAsyncTask(...)
Async form. Same parameters and errors.
void OrderCloseAsync(int requestId, long ticket, string symbol, double price, double lots, OrderType type, ...)
Sends the close request and returns at once. Watch the events. Same checks as OrderSendAsync.
OrderModify
void OrderModify(long ticket, string symbol, double lots, double price, OrderType type, double sl, double tp, long expertID = 0, double stoplimit = 0.0, Expiration expiration = null, string comment = null)
Changes the stop loss and take profit of a position, or the price, stops and expiry of a pending order. Blocks until the broker confirms.
ticket,symbol,type: the position or order you change.typeisBuyorSellfor a position.lots: its volume.price: for a pending order the new trigger price. For a position, its open price.sl,tp: the new levels.0means no level.stoplimit,expiration,comment,expertID: as inOrderSend.
Throws: ServerException (for example Msg.INVALID_STOPS), TimeoutException.
Order pos = api.GetOpenedOrder(ticket);
api.OrderModify(pos.Ticket, pos.Symbol, pos.Lots, pos.OpenPrice, pos.OrderType,
sl: pos.OpenPrice, tp: pos.TakeProfit); // move stop to break-evenTask OrderModifyAsyncTask(...)
Async form. Same parameters and errors.
void OrderModifyAsync(int requestId, long ticket, string symbol, double lots, double price, OrderType type, double sl, double tp, ...)
Sends the change and returns at once. Watch the events.
Enums used by orders
OrderType
Buy, Sell, BuyLimit, SellLimit, BuyStop, SellStop, BuyStopLimit, SellStopLimit, CloseBy, Balance, Credit.
FillPolicy
FillOrKill, ImmediateOrCancel, FlashFill, Any.
ExpirationType
GTC (good till cancelled), Today, Specified, SpecifiedDay.
OrderState
Started, Placed, Cancelled, Partial, Filled, Rejected, Expired, RequestAdding, RequestModifying, RequestCancelling.
PlacedType
Who placed the order: Manually, Mobile, Web, ByExpert, OnSL, OnTP, OnStopOut, OnRollover, OnVmargin, OnSplit, ByDealer, Gateway, Signal, Settlement, Transfer, Sync, ExternalService, Migration, Default.
Expiration
Class with Type (ExpirationType) and DateTime.
TradeType
Low-level request kind. Leave tradeType at its default (Transfer) in normal use.