Table of Contents

Class ViiSyncAccountApi

Namespace
ViiSync.AccountApi
Assembly
ViiSync.AccountApi.dll

The ViiSync trading-account API, shaped like mtapi.io's MT5API so MT5 integrations port with minimal change: the same constructor (login, password, host, port), Connect, OrderSend/OrderClose/OrderModify with MT5's parameter lists and enums, Symbols.Infos, GetQuote, OnQuote, OnOrderUpdate, the Account* figures and the history downloads. Every blocking call has an …Async twin.

Differences a porting developer should know: times are UTC (ViiSync's server clock is UTC, MT5 servers are usually UTC+2/+3); tickets are 64-bit ids issued by ViiSync; failures throw ServerException with MT5 return codes (Msg). State (positions, pending orders, account figures, symbols) is kept current from the engine's pushes, so reading GetOpenedOrders(OrderSort, bool) or AccountEquity costs no round trip.

public sealed class ViiSyncAccountApi : IDisposable, IAsyncDisposable
Inheritance
ViiSyncAccountApi
Implements
Inherited Members

Constructors

ViiSyncAccountApi()

Create an API without connection details; set User, Password, Host (and Port) before Connect().

ViiSyncAccountApi(ulong, string, string, int)

MT5-style: login, password, host and port. Port 443 connects over TLS (wss://host/ws); any other port connects to ws://host:port/ws. Pass a full ws:///wss:// URL as host to set the endpoint exactly.

ViiSyncAccountApi(ulong, string, Uri)

Connect to an explicit WebSocket endpoint, e.g. wss://server.example.com/ws.

Properties

Account

The account record (MT5 Account).

AccountBalance

Balance, deposit currency (MT5 AccountBalance).

AccountCompanyName

Account holder company (MT5 AccountCompanyName).

AccountCredit

Credit, deposit currency (MT5 AccountCredit).

AccountCurrency

Deposit currency (MT5 AccountCurrency).

AccountEquity

Balance + credit + floating P/L (MT5 AccountEquity).

AccountFreeMargin

Equity − margin (MT5 AccountFreeMargin).

AccountLeverage

Leverage denominator, e.g. 100 for 1:100 (the value the engine margins with).

AccountMargin

Used margin, netted per symbol by the engine's risk model (MT5 AccountMargin).

AccountMethod

Hedging or netting (MT5 AccountMethod).

AccountProfit

Floating P/L of the open positions, as last marked by the engine, plus their accrued swap when the engine charges swaps (MT5 AccountProfit includes POSITION_SWAP; a display-only estimate is never counted).

AutoReconnect

Reconnect automatically after a dropped connection or an expired session (MT5 reconnects on Connect only).

ClusterSummary

Server identity: name = endpoint host, time zone, engine version.

ConfigureWebSocket

Optional low-level hook for the WebSocket options (headers, TLS callbacks, keep-alive).

ConnectTime

When the current session logged in (UTC).

ConnectTimeout

Connect + login + initial state load budget, ms (MT5 ConnectTimeout).

Connected

True while connected and logged in.

DeviceId

Device fingerprint reported at login (empty = derived from the machine).

DownloadOrderHistoryTimeout

History download budget per request, ms (MT5 DownloadOrderHistoryTimeout).

Endpoint

The WebSocket endpoint. Derived from Host/Port unless set explicitly.

ExecutionTimeout

How long a trade call waits for the server's answer, ms (MT5 ExecutionTimeout).

GetQuoteTimeoutMs

Default GetQuote(string, int, int) wait, ms (MT5 GetQuoteTimeoutMs).

Host

Server host name, or a full ws:///wss:// URL.

Id

Caller-owned tag (MT5 Id).

IsInvestor

True when this session logged in with the account's INVESTOR password (MT5 IsInvestor): read-only — quotes, account, positions, orders and history work; every trade/password call throws InvestorModeException here, and the engine refuses them server-side with TRADE_DISABLED regardless of the client.

IsNotConfirmedAccount

True until the account's KYC is approved (MT5 IsNotConfirmedAccount).

IsTradeAllowed

False while disconnected and on an investor (read-only) session (MT5 IsTradeAllowed).

IsTradeDisableOnServer

True when the server refuses trading for this session (MT5 IsTradeDisableOnServer).

LastQuoteTime

When the last quote arrived (UTC).

LastServerMessageTime

When the last frame (any, including heartbeats) arrived from the server (UTC).

Mails

Messages received in the account's mailbox (MT5 Mails).

MarginLevel

Equity / margin × 100, 0 with no margin in use (MT5 MarginLevel).

NoServerMessagesTimeout

Treat the connection as dead when nothing (not even the engine's 50 ms heartbeat) arrived for this long, ms (MT5 NoServerMessagesTimeout). 0 disables the watchdog.

Password

Account password (master for trading, investor for a read-only session).

PendingOrders

ViiSync extra: working pending orders only.

PlacedType

Default ORDER_REASON for orders this API places (MT5 PlacedType).

Port

Server port. 443 connects over TLS (wss://host/ws); any other port uses ws://host:port/ws.

Positions

ViiSync extra: open positions only.

ProcessEventTimeoutMs

Event-handler watchdog, ms (MT5 ProcessEventTimeoutMs). Events are raised on the API's receive loop, so a slow handler delays every later push (quotes, trade updates). A handler that runs longer than this is reported on OnLog (name + elapsed ms) and counted in SlowEventHandlers. 0 disables the check.

Proxy

Optional HTTP(S) proxy for the WebSocket connection (replaces MT5's Proxy* fields).

ReconnectDelayMs

Delay between reconnect attempts, ms (doubles up to 30 s).

Server

The endpoint in use (MT5 Server).

ServerTime

The server's current time (server zone), corrected for the measured clock offset (MT5 ServerTime).

ServerTimeUtc

ViiSync extra: server time in UTC.

ServerTimeZoneInMinutes

Server time zone in minutes from UTC (ViiSync: 0 — the server clock is UTC).

ServerVersion

Engine release from the login reply, e.g. 1.0.0+abc1234 (MT5 ServerBuild).

SlowEventHandlers

ViiSync extra: how many event-handler invocations exceeded ProcessEventTimeoutMs.

SupportsTypedTradeResults

True when the engine answers trade commands with typed results (engines with opcodes 85-88). Older engines are driven through the legacy commands; the API behaves the same, but trade calls are serialized.

Symbols

The account's symbol catalog, kept current from the engine (MT5 Symbols).

User

Trading account login (ViiSync account id).

Methods

CalculateBalanceHistory(DateTime)

ViiSync extra: the balance curve (one point per balance-changing deal) from from.

CalculateBalanceHistoryAsync(DateTime, CancellationToken)

Async CalculateBalanceHistory(DateTime).

CalculateEquityHistory(DateTime, EquityTimeframe, bool)

Equity curve sampled every timeframe from from to now (MT5 CalculateEquityHistory): balance from the deal ledger plus the floating P/L of the positions open at each sample, priced at that sample's M1 close. A symbol whose profit currency is not the deposit currency is converted at the HISTORICAL rate of that sample — the M1 close of the conversion pair (direct, inverse, or through USD), as the terminal does; only when the server holds no bar of the pair before a sample does it fall back to the live rate.

CalculateEquityHistoryAsync(DateTime, EquityTimeframe, bool, CancellationToken)

Async CalculateEquityHistory(DateTime, EquityTimeframe, bool).

CalculateOrderProfit(string, double, double, double, bool)

Profit of a hypothetical trade in the deposit currency (MT5 CalculateOrderProfit) — the engine's ViiPnl.Profit: (close − open)·dir·contract·lots, converted at the live profit-currency rate.

ChangePassword(string, bool)

Change the master (or investor) password (MT5 ChangePassword). Throws ServerException (INVALID_PASSWORD) when the server refuses it.

ChangePasswordAsync(string, bool, CancellationToken)

Async ChangePassword(string, bool).

ClosedOrders()

Closed trades known to this session (from the seed window plus everything closed since connecting) — MT5 ClosedOrders. Use DownloadOrderHistory(DateTime, DateTime, OrderSort, bool) for an arbitrary window.

Connect()

Connect, log in and load the account state (symbols, positions, orders, account figures). Throws ConnectException (Code INVALID_ACCOUNT when the credentials are refused).

ConnectAsync(int)

Connect with an overall timeout in ms.

ConnectAsync(CancellationToken)

Connect, log in and load the account state.

ConvertToTimeframe(List<Bar>, int)

Aggregate bars into a larger timeframe (MT5 ConvertToTimeframe).

Disconnect()

Close the connection. No automatic reconnect follows.

DisconnectAsync()

Close the connection. No automatic reconnect follows.

Dispose()

Disconnect (same as Disconnect()).

DisposeAsync()

Disconnect (same as DisconnectAsync()).

DownloadDealHistory(DateTime?, DateTime)

ViiSync extra: every deal in a window (null from = from the beginning), oldest first.

DownloadOrderHistory(DateTime, DateTime, OrderSort, bool)

Closed trades, deals and orders of a time window (MT5 DownloadOrderHistory). Orders holds one Order per position CLOSED in the window (built from its deals, the way the MT5 terminal's history does: open from the IN deal — fetched even when it predates the window — close from the OUT deals, profit/commission/swap summed) plus balance/credit operations; InternalDeals every deal of the window; InternalOrders every order placed in the window.

DownloadOrderHistoryAsync(DateTime, DateTime, OrderSort, bool, CancellationToken)

Async DownloadOrderHistory(DateTime, DateTime, OrderSort, bool).

DownloadPendingOrderHistory(DateTime, DateTime, bool)

Pending orders that finished (filled, cancelled, expired, rejected) in a window, placed-time order (MT5 DownloadPendingOrderHistory).

DownloadPendingOrderHistoryAsync(DateTime, DateTime, bool, CancellationToken)

Async DownloadPendingOrderHistory(DateTime, DateTime, bool).

DownloadQuoteHistory(string, DateTime, DateTime, int)

OHLC bars in [from, to] for any MT5 timeframe in minutes (1, 5, 15, 30, 60, 240, 1440, 10080, 43200 or any other) — MT5 DownloadQuoteHistory. The engine stores M1; larger frames are aggregated here by the MT5 terminal's rules. Uses the compact VC1 transfer when the engine supports it.

DownloadQuoteHistoryAsync(string, DateTime, DateTime, int, CancellationToken)

Async DownloadQuoteHistory(string, DateTime, DateTime, int).

DownloadQuoteHistoryMonth(string, int, int, int, int, int)

Bars from the start of a month (or of day when > 0) up to now (MT5 DownloadQuoteHistoryMonth).

DownloadQuoteHistoryMonthAsync(string, int, int, int, int, int)

Async DownloadQuoteHistoryMonth(string, int, int, int, int, int).

DownloadQuoteHistoryToday(string, int, int)

Today's bars (MT5 DownloadQuoteHistoryToday).

DownloadQuoteHistoryTodayAsync(string, int, int)

Async DownloadQuoteHistoryToday(string, int, int).

DownloadTickHistory(string, DateTime, DateTime)

ViiSync extra: raw ticks in [from, to] (ascending). Pages back through the engine's tick store with the compact VC1 transfer.

DownloadTickHistoryAsync(string, DateTime, DateTime, CancellationToken, Action<TickBar[]>?)

Async DownloadTickHistory(string, DateTime, DateTime). onPage, when given, receives each page as it arrives.

GetAskTickValue(Quote)

Tick value at the ask (profit of a short) — MT5 GetAskTickValue.

GetBidTickValue(Quote)

Tick value at the bid (profit of a long) — MT5 GetBidTickValue.

GetContractSize(string)

Contract size of a symbol (MT5 GetContractSize).

GetMarketWatch(string)

Today's high/low/open, the previous close, change and spread (MT5 GetMarketWatch).

GetMarketWatchAsync(string, CancellationToken)

Async GetMarketWatch(string).

GetOpenedOrder(long)

One open position or working order by ticket, or null (MT5 GetOpenedOrder).

GetOpenedOrders(OrderSort, bool)

Open positions and working pending orders (MT5 GetOpenedOrders). No round trip — kept current from the engine's pushes.

GetOrderBook(string)

ViiSync extra: the last order book received for a symbol, or null.

GetQuote(string, int, int)

The latest quote (MT5 GetQuote). Returns the streamed quote when it is at most msNotOlder ms old (0 = any age); otherwise asks the engine and waits up to msTimeout ms (0 = GetQuoteTimeoutMs). Null when the symbol has no price.

GetQuoteAsync(string, int, int, CancellationToken)

Async GetQuote(string, int, int) (MT5 GetQuoteTask).

GetTickSize(string)

Minimal price change (MT5 GetTickSize).

GetTickValue(string, int)

Value of one tick for one lot in the deposit currency (MT5 GetTickValue).

IsQuoteSession(string)

Is the symbol quoting now (weekly quote session and not a holiday)? (MT5 IsQuoteSession)

IsSubscribed(string)

True when quotes of the symbol are being streamed.

IsTradeSession(string)

Is the symbol tradable now (trade session, not a holiday, inside office hours)? (MT5 IsTradeSession)

MailBodyRequest(long)

Mail bodies arrive with the message in ViiSync; this re-raises OnMail for it and marks it read (MT5 MailBodyRequest).

OrderClose(long, string, double, double, OrderType, ulong, FillPolicy, long, string?, long, PlacedType)

Close a position (fully, or partially when lots is below its volume), delete a pending order, or close a position by an opposite one (closeByTicket) — MT5 OrderClose. price is ignored (ViiSync closes at the live quote). Returns the closed trade.

OrderCloseAsync(long, string, double, double, OrderType, ulong, FillPolicy, long, string?, long, PlacedType, CancellationToken)

Async OrderClose(long, string, double, double, OrderType, ulong, FillPolicy, long, string?, long, PlacedType) (MT5 OrderCloseAsyncTask).

OrderCloseBy(long, long)

MT5 close-by: close ticket by the opposite position closeByTicket of the same symbol (hedging accounts). min(volume) of both closes at the open price of closeByTicket, so the pair pays no spread. Returns the first position's closed trade.

OrderCloseByAsync(long, long, CancellationToken)

Async OrderCloseBy(long, long).

OrderDelete(long, OrderType, string, double, double)

Delete (cancel) a working pending order (MT5 OrderClientSafe.OrderDelete).

OrderDeleteAsync(long, OrderType, string?, double, double, CancellationToken)

Async OrderDelete(long, OrderType, string, double, double).

OrderModify(long, string, double, double, OrderType, double, double, long, double, Expiration?, string?)

Modify a position's SL/TP, or a pending order's price/SL/TP/volume/expiration (MT5 OrderModify). SL/TP are absolute prices; 0 removes the level.

OrderModifyAsync(long, string, double, double, OrderType, double, double, long, double, Expiration?, string?, CancellationToken)

Async OrderModify(long, string, double, double, OrderType, double, double, long, double, Expiration?, string?) (MT5 OrderModifyAsyncTask).

OrderSend(string, double, double, OrderType, double, double, ulong, string?, long, FillPolicy, TradeType, double, Expiration?, long, PlacedType)

Open a market position or place a pending order (MT5 OrderSend, same parameters).

Returns the opened position (market) or the working order (pending). Throws ServerException with an MT5 return code (NO_MONEY, INVALID_VOLUME, MARKET_CLOSED, NO_PRICES, …) when refused.

OrderSendAsync(string, double, double, OrderType, double, double, ulong, string?, long, FillPolicy, TradeType, double, Expiration?, long, PlacedType, CancellationToken)

Async OrderSend(string, double, double, OrderType, double, double, ulong, string?, long, FillPolicy, TradeType, double, Expiration?, long, PlacedType) (MT5 OrderSendAsyncTask).

PingHost(string, int)

TCP connect time to a host in ms, −1 when unreachable (MT5 PingHost).

RequestDealHistory(int, int)

Fire-and-forget deals of a month on OnOrderHistory (MT5 RequestDealHistory).

RequestOrderHistory(DateTime, DateTime)

Fire-and-forget: the window's history on OnOrderHistory (MT5 RequestOrderHistory).

RequestOrderHistory(int, int)

Fire-and-forget by month (MT5 RequestOrderHistory(year, month)).

RequestPendingOrderHistory(DateTime, DateTime)

Fire-and-forget: finished pending orders of a window on OnOrderHistory (as InternalOrders).

RequestPendingOrderHistory(int, int)

Month variant of RequestPendingOrderHistory(DateTime, DateTime).

RequestQuoteHistoryMonth(string, int, int, int)

Fire-and-forget variant: bars from a month/day to now, delivered on OnQuoteHistory (M1).

RequestQuoteHistoryToday(string)

Fire-and-forget: today's M1 bars on OnQuoteHistory.

RequiredMargin(string, double, DealType, double)

Margin the engine would charge to open lots alone (MT5 RequiredMargin), in the deposit currency: the engine's MarginOf formula for the symbol's calculation mode, at the account leverage. price 0 = the current ask (buy) / bid (sell). Hedged offsets against existing positions are not applied here — the engine nets them when it admits the order.

Subscribe(string)

Stream quotes for a symbol (MT5 Subscribe); they arrive on OnQuote.

Subscribe(string[])

Stream quotes for several symbols (added to the current set).

SubscribeAsync(IEnumerable<string>, bool, CancellationToken)

Async Subscribe(string[]). Unknown symbols throw InvalidSymbolException unless force.

SubscribeForce(string[])

Subscribe even to names that are not (yet) in the account's catalog (MT5 SubscribeForce).

SubscribeOrderBook(string)

Stream the order book of a symbol (MT5 SubscribeOrderBook); books arrive on OnOrderBook.

SubscribeOrderBookAsync(string, CancellationToken)

Async SubscribeOrderBook(string).

Subscriptions()

The symbols currently streamed (MT5 Subscriptions).

TickHistoryRequest(string, int, int, int)

Stream ticks from a start date up to now on OnTickHistory, newest page first (MT5 TickHistoryRequest). Stop with TickHistoryStop(string).

TickHistoryStop(string)

Stop a running TickHistoryRequest(string, int, int, int) (MT5 TickHistoryStop).

Unsubscribe(string)

Stop streaming a symbol (MT5 Unsubscribe).

Unsubscribe(string[])

Stop streaming several symbols.

UnsubscribeAsync(IEnumerable<string>, CancellationToken)

Async Unsubscribe(string[]).

UnsubscribeOrderBook(string)

Stop streaming a symbol's order book (MT5 UnsubscribeOrderBook).

UnsubscribeOrderBookAsync(string, CancellationToken)

Async UnsubscribeOrderBook(string).

UpdateAccountProfit()

Refresh the account figures from the engine (MT5 UpdateAccountProfit).

UpdateAccountProfit(List<Order>)

Sum of the given orders' profit (MT5 UpdateAccountProfit(List<Order>)).

UpdateAccountProfitAsync(CancellationToken)

Async UpdateAccountProfit(): re-request positions and account figures and wait for both.

UpdateProfits(Quote?)

Refresh positions (with the engine's current marks) and the account figures (MT5 UpdateProfits). The optional quote is accepted for source compatibility; ViiSync marks with its own live quotes.

Events

OnAccountUpdate

ViiSync extra: account figures changed (balance, equity, margin).

OnConnectProgress

Raised at each connection stage (MT5 OnConnectProgress).

OnLog

ViiSync extra: diagnostic log lines (connection, server errors).

OnMail

Raised when a mailbox message arrives (MT5 OnMail).

OnOrderBook

Raised with each order-book update of a symbol subscribed with SubscribeOrderBook(string) (MT5 OnOrderBook).

OnOrderHistory

Raised with the result of RequestOrderHistory(DateTime, DateTime) and the other fire-and-forget history requests (MT5 OnOrderHistory).

OnOrderProgress

Raised at each stage of a trade request: InProcess when it leaves, then Opened / Accepted / Closed / Modified / PendingDeleted / ClosedBy, or Rejected / Timeout / Exception (MT5 OnOrderProgress).

OnOrderUpdate

Raised when a position, pending order or deal of the account changes (MT5 OnOrderUpdate).

OnQuote

Raised for every quote of a subscribed symbol (MT5 OnQuote).

OnQuoteHistory

Raised with the bars of RequestQuoteHistoryMonth(string, int, int, int) / RequestQuoteHistoryToday(string) (MT5 OnQuoteHistory).

OnSymbolUpdate

Raised once per symbol that was added, changed or removed after the initial catalog load (MT5 OnSymbolUpdate).

OnSymbolsUpdate

Raised once after a catalog change, after the per-symbol OnSymbolUpdate events (MT5 OnSymbolsUpdate).

OnTickHistory

Raised once per page of a TickHistoryRequest(string, int, int, int) stream (MT5 OnTickHistory).