KazaTrade
دخول
القائمة

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:

FieldTypeMeaning
TicketlongPosition or order number
SymbolstringSymbol
OrderTypeOrderTypeBuy, Sell, BuyLimit, ...
DealTypeDealTypeType of the opening deal (DealBuy, DealSell, Balance, ...)
StateOrderStatePlaced, Filled, Cancelled, ...
LotsdoubleVolume in lots
OpenPrice, OpenTimedouble, DateTimeOpen price and time (server time)
ClosePrice, CloseTimedouble, DateTimeClose price and time. For an open position CloseTime is empty.
CloseLotsdoubleLots closed so far
StopLoss, TakeProfitdoubleLevels. 0 means none.
StopLimitPricedoubleLimit price of a stop-limit order
ProfitdoubleProfit in the account currency
Swap, Commission, FeedoubleCosts
Comment, CloseCommentstringComments
ExpertIdlongThe tag you set with expertID
PlacedTypePlacedTypeWho placed it
ContractSize, Digits, ProfitRateSymbol facts at the time
RequestIdintThe request number that created it, if it came from this client
ExpirationType, ExpirationTime, FillPolicySettings of a pending order
Volume, CloseVolumeulongLots and CloseLots times 100,000,000
OpenTimestampUTC, CloseTimestampUTClongOpen and close time as UTC milliseconds
DealInternalIn, DealInternalOut, OrderInternalThe raw deals and order behind it
PartialCloseDeals, PartialFillDealsDealInternal[]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.

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:

Throws:

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.

Event-style requests

These send a request and return. The answer arrives on OnOrderHistory.

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.

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).

Positions and history · MT5 library reference