Positions and history
Members of MT5API for open trades, closed trades and history. Both open positions and pending orders are returned as Order objects.
The Order type
Order is the object OrderSend, OrderClose, GetOpenedOrders, ClosedOrders and history calls return. Public fields:
| Field | Type | Meaning |
|---|---|---|
Ticket | long | Position or order number |
Symbol | string | Symbol |
OrderType | OrderType | Buy, Sell, BuyLimit, ... |
DealType | DealType | Type of the opening deal (DealBuy, DealSell, Balance, ...) |
State | OrderState | Placed, Filled, Cancelled, ... |
Lots | double | Volume in lots |
OpenPrice, OpenTime | double, DateTime | Open price and time (server time) |
ClosePrice, CloseTime | double, DateTime | Close price and time. For an open position CloseTime is empty. |
CloseLots | double | Lots closed so far |
StopLoss, TakeProfit | double | Levels. 0 means none. |
StopLimitPrice | double | Limit price of a stop-limit order |
Profit | double | Profit in the account currency |
Swap, Commission, Fee | double | Costs |
Comment, CloseComment | string | Comments |
ExpertId | long | The tag you set with expertID |
PlacedType | PlacedType | Who placed it |
ContractSize, Digits, ProfitRate | Symbol facts at the time | |
RequestId | int | The request number that created it, if it came from this client |
ExpirationType, ExpirationTime, FillPolicy | Settings of a pending order | |
Volume, CloseVolume | ulong | Lots and CloseLots times 100,000,000 |
OpenTimestampUTC, CloseTimestampUTC | long | Open and close time as UTC milliseconds |
DealInternalIn, DealInternalOut, OrderInternal | The raw deals and order behind it | |
PartialCloseDeals, PartialFillDeals | DealInternal[] | Deals of partial closes and partial fills |
Order.Clone() returns a copy.
The raw types
DealInternal (a deal) has TicketNumber, OrderTicket, PositionTicket, Symbol, Type (DealType), Direction (In, Out, InOut, OutBy), Price, OpenPrice, StopLoss, TakeProfit, Volume, Lots, Profit, Commission, Fee, Swap, Comment, ExpertId, OpenTime (a number), OpenTimeAsDateTime.
OrderInternal (an order) has TicketNumber, Ticket, Symbol, Type (OrderType), State, Price, OpenPrice, StopLimitPrice, StopLoss, TakeProfit, Volume, Lots, RequestVolume, RequestLots, FillPolicy, ExpirationType, ExpirationTime, DealTicket, Comment, ExpertId, OpenTimeAsDateTime, ExecutionTimeAsDateTime, plus IsBuyOrder(), IsLimitOrder(), IsStopOrder(), IsStopLimitOrder(), IsTradeOrder().
Open positions
Order[] GetOpenedOrders(OrderSort sort = OrderSort.OpenTime, bool ascending = true)
Returns all open positions and pending orders the library holds. This is local data; it sends nothing to the broker.
sort:OrderSort.OpenTimeorOrderSort.CloseTime.ascending: sort direction.
foreach (Order o in api.GetOpenedOrders())
Console.WriteLine($"#{o.Ticket} {o.Symbol} {o.OrderType} {o.Lots} profit {o.Profit}");Order GetOpenedOrder(long ticket)
Returns one open position or pending order, or null if the ticket is not open.
Recently closed
Order[] ClosedOrders()
Returns the trades that closed while this client was connected. The library keeps at most the latest 100. For anything older, use DownloadOrderHistory.
History download
History dates are broker server time. Download one range, keep the result, and do not repeat the same request: each one costs the broker a request.
OrderHistoryEventArgs DownloadOrderHistory(DateTime from, DateTime to, OrderSort sort = OrderSort.OpenTime, bool ascending = true)
Downloads the closed trades between from and to and returns them when the whole range has arrived.
Returns OrderHistoryEventArgs:
Orders:List<Order>, the closed trades.InternalDeals:List<DealInternal>, every deal in the range (including balance and credit rows).InternalOrders:List<OrderInternal>, the orders behind them.Action,PartialResponse: advanced; ignore for normal use.
Throws:
DoubleRequestException: another history download is running on this client. Wait and retry.TimeoutException("DownloadOrderHistoryTimeout"): no answer withinDownloadOrderHistoryTimeout.Exception("Not connected").
var h = api.DownloadOrderHistory(DateTime.UtcNow.AddDays(-30), DateTime.UtcNow, OrderSort.CloseTime);
double total = h.Orders.Sum(o => o.Profit + o.Commission + o.Swap);
Console.WriteLine($"{h.Orders.Count} trades, net {total}");Task<OrderHistoryEventArgs> DownloadOrderHistoryAsync(DateTime from, DateTime to, OrderSort sort = OrderSort.OpenTime, bool ascending = true, DealInternal[] existDeals = null, CancellationToken cancellation = default)
Async form. If another download is running it waits and tries again instead of throwing. Pass existDeals (deals you already have) to skip them. Same other errors.
List<OrderInternal> DownloadPendingOrderHistory(DateTime from, DateTime to, bool ascending = true)
Task<List<OrderInternal>> DownloadPendingOrderHistoryAsync(DateTime from, DateTime to, bool ascending = true)
Downloads the pending orders (placed, cancelled, expired) between from and to.
- Throws:
DoubleRequestException(blocking form only).
Event-style requests
These send a request and return. The answer arrives on OnOrderHistory.
void RequestOrderHistory(DateTime from, DateTime to)void RequestOrderHistory(int year, int month, List<DealInternal> partialResponse = null): a whole calendar month.void RequestDealHistory(int year, int month, List<DealInternal> partialResponse)void RequestPendingOrderHistory(DateTime from, DateTime to)void RequestPendingOrderHistory(int year, int month, List<DealInternal> exist = null)void RequestPendingHistory(int year, int month, List<OrderInternal> exist)
Throws: Exception("Download Order History Running") if a blocking download is active, Exception("Not connected").
Equity history
List<EquityPoint> CalculateEquityHistory(DateTime from, MT5API api, EquityTimeframe timeframe, bool excludeSameBars = true)
Builds a balance and equity curve from from to now, with drawdown for each point. It downloads order history and bars for the symbols you traded, so call it sparingly and cache the result.
api: pass the same client (this/api).timeframe:EquityTimeframe.H1,H4orD1.excludeSameBars: drop points that repeat the previous one.
Returns a list of EquityPoint: Time, Balance, Equity, BalanceDrawdownRaw, BalanceDrawdownRelative, EquityDrawdownRaw, EquityDrawdownRelative, RealizedPL, UnrealizedPL. Relative values are fractions (0.05 is 5 percent).
Throws: InvalidOperationException when there are no closed trades in the range, Exception("Balance history is empty"), and the history errors above.
var points = api.CalculateEquityHistory(DateTime.UtcNow.AddDays(-30), api, EquityTimeframe.D1);
Console.WriteLine($"Max equity drawdown {points.Max(p => p.EquityDrawdownRelative):P1}");Enums
OrderSort
OpenTime, CloseTime.
DealType
DealBuy, DealSell, Balance, Credit, Charge, Correction, Bonus, Commission, DailyCommission, MonthlyCommission, DailyAgentCommission, MonthlyAgentCommission, InterestRate, CanceledBuy, CanceledSell, Dividend, FrankedDividend, Tax, AgentCommission, SoCompensation, SoCreditCompensation.
EquityTimeframe
H1 (60), H4 (240), D1 (1440).