using System.Drawing; using System.Collections; using Newtonsoft.Json; using MtApi.Events; using MtApi.MtProtocol; using MtClient; namespace MtApi { public delegate void MtApiQuoteHandler(object sender, string symbol, double bid, double ask); public sealed class MtApiClient { #region MetaTrader Constants //Special constant public const int NULL = 0; public const int EMPTY = -1; #endregion #region Private Fields private IMtLogger Log { get; } private MtRpcClient? _client; private readonly object _locker = new(); private readonly Dictionary> _mtEventHandlers = []; private HashSet _experts = []; private Dictionary _quotes = []; private MtConnectionState _connectionState = MtConnectionState.Disconnected; private int _executorHandle; #endregion #region ctor public MtApiClient(IMtLogger? log = null) { _mtEventHandlers[MtEventTypes.ChartEvent] = ReceiveOnChartEvent; _mtEventHandlers[MtEventTypes.LastTimeBar] = ReceivedOnLastTimeBarEvent; _mtEventHandlers[MtEventTypes.OnLockTicks] = ReceivedOnLockTicksEvent; _mtEventHandlers[MtEventTypes.OnTick] = ReceivedOnTickEvent; Log = log ?? new StubMtLogger(); } #endregion #region Public Methods /// ///Connect with MetaTrader API. Async method. /// ///Address of MetaTrader host (ex. 192.168.1.2) ///Port of host connection (default 8222) public void BeginConnect(string host, int port) { Log.Info($"BeginConnect: host = {host}, port = {port}"); Task.Factory.StartNew(() => Connect(host, port)); } /// ///Connect with MetaTrader API. Async method. /// ///Port of host connection (default 8222) public void BeginConnect(int port) { Log.Info($"BeginConnect: localhost, port = {port}"); Task.Factory.StartNew(() => Connect("localhost", port)); } /// ///Disconnect from MetaTrader API. Async method. /// public void BeginDisconnect() { Log.Info("BeginDisconnect called."); Task.Factory.StartNew(() => Disconnect(false)); } /// ///Load quotes connected into MetaTrader API. /// public List GetQuotes() { lock (_locker) { return _quotes.Values.ToList(); } } #endregion #region Properties /// ///Connection status of MetaTrader API. /// public MtConnectionState ConnectionState { get { lock (_locker) { return _connectionState; } } } /// ///Handle of expert used to execute commands /// public int ExecutorHandle { get { lock (_locker) { return _executorHandle; } } set { lock (_locker) { _executorHandle = value; } } } #endregion #region Deprecated Methods [Obsolete("OrderCloseByCurrentPrice is deprecated, please use OrderClose instead.")] public bool OrderCloseByCurrentPrice(int ticket, int slippage) { return OrderClose(ticket, slippage); } [Obsolete("OrderClosePrice is deprecated, please use GetOrder instead.")] public double OrderClosePrice() { return SendCommand(ExecutorHandle, MtCommandType.OrderClosePrice); } [Obsolete("OrderClosePrice is deprecated, please use GetOrder instead.")] public double OrderClosePrice(int ticket) { Dictionary cmdParams = new() { { "Ticket", ticket } }; return SendCommand(ExecutorHandle, MtCommandType.OrderClosePriceByTicket, cmdParams); } [Obsolete("OrderCloseTime is deprecated, please use GetOrder instead.")] public DateTime OrderCloseTime() { var commandResponse = SendCommand(ExecutorHandle, MtCommandType.OrderCloseTime); return MtApiTimeConverter.ConvertFromMtTime(commandResponse); } [Obsolete("OrderComment is deprecated, please use GetOrder instead.")] public string? OrderComment() { return SendCommand(ExecutorHandle, MtCommandType.OrderComment); } [Obsolete("OrderCommission is deprecated, please use GetOrder instead.")] public double OrderCommission() { return SendCommand(ExecutorHandle, MtCommandType.OrderCommission); } [Obsolete("OrderExpiration is deprecated, please use GetOrder instead.")] public DateTime OrderExpiration() { var commandResponse = SendCommand(ExecutorHandle, MtCommandType.OrderExpiration); return MtApiTimeConverter.ConvertFromMtTime(commandResponse); } [Obsolete("OrderLots is deprecated, please use GetOrder instead.")] public double OrderLots() { return SendCommand(ExecutorHandle, MtCommandType.OrderLots); } [Obsolete("OrderMagicNumber is deprecated, please use GetOrder instead.")] public int OrderMagicNumber() { return SendCommand(ExecutorHandle, MtCommandType.OrderMagicNumber); } [Obsolete("OrderOpenPrice is deprecated, please use GetOrder instead.")] public double OrderOpenPrice() { return SendCommand(ExecutorHandle, MtCommandType.OrderOpenPrice); } [Obsolete("OrderOpenPrice is deprecated, please use GetOrder instead.")] public double OrderOpenPrice(int ticket) { Dictionary cmdParams = new() { { "Ticket", ticket } }; return SendCommand(ExecutorHandle, MtCommandType.OrderOpenPriceByTicket, cmdParams); } [Obsolete("OrderOpenTime is deprecated, please use GetOrder instead.")] public DateTime OrderOpenTime() { var commandResponse = SendCommand(ExecutorHandle, MtCommandType.OrderOpenTime); return MtApiTimeConverter.ConvertFromMtTime(commandResponse); } [Obsolete("OrderProfit is deprecated, please use GetOrder instead.")] public double OrderProfit() { return SendCommand(ExecutorHandle, MtCommandType.OrderProfit); } [Obsolete("OrderStopLoss is deprecated, please use GetOrder instead.")] public double OrderStopLoss() { return SendCommand(ExecutorHandle, MtCommandType.OrderStopLoss); } [Obsolete("OrderSymbol is deprecated, please use GetOrder instead.")] public string? OrderSymbol() { return SendCommand(ExecutorHandle, MtCommandType.OrderSymbol); } [Obsolete("OrderTakeProfit is deprecated, please use GetOrder instead.")] public double OrderTakeProfit() { return SendCommand(ExecutorHandle, MtCommandType.OrderTakeProfit); } [Obsolete("OrderTicket is deprecated, please use GetOrder instead.")] public int OrderTicket() { return SendCommand(ExecutorHandle, MtCommandType.OrderTicket); } [Obsolete("OrderType is deprecated, please use GetOrder instead.")] public TradeOperation OrderType() { return (TradeOperation) SendCommand(ExecutorHandle, MtCommandType.OrderType); } [Obsolete("OrderSwap is deprecated, please use GetOrder instead.")] public double OrderSwap() { return SendCommand(ExecutorHandle, MtCommandType.OrderSwap); } #endregion #region Trading functions public int OrderSend(string symbol, TradeOperation cmd, double volume, double price, int slippage, double stoploss, double takeprofit , string comment, int magic, DateTime expiration, Color arrowColor) { Log.Debug($"OrderSend: symbol = {symbol}, cmd = {cmd}, volume = {volume}, price = {price}, slippage = {slippage}, stoploss = {stoploss}, takeprofit = {takeprofit}, comment = {comment}, magic = {magic}, expiration = {expiration}, arrowColor = {arrowColor}"); Dictionary cmdParams = new() { { "Symbol", symbol }, { "Cmd", cmd }, { "Volume", volume }, { "Price", price }, { "Slippage", slippage }, { "Stoploss", stoploss}, { "Takeprofit", takeprofit }, { "Comment", comment }, { "Magic", magic }, { "Expiration", MtApiTimeConverter.ConvertToMtTime(expiration) }, { "ArrowColor", MtApiColorConverter.ConvertToMtColor(arrowColor) } }; return SendCommand(ExecutorHandle, MtCommandType.OrderSend, cmdParams); } public int OrderSend(string symbol, TradeOperation cmd, double volume, double price, int slippage, double stoploss, double takeprofit , string comment, int magic, DateTime expiration) { Log.Debug($"OrderSend: symbol = {symbol}, cmd = {cmd}, volume = {volume}, price = {price}, slippage = {slippage}, stoploss = {stoploss}, takeprofit = {takeprofit}, comment = {comment}, magic = {magic}, expiration = {expiration}"); Dictionary cmdParams = new() { { "Symbol", symbol }, { "Cmd", cmd }, { "Volume", volume }, { "Price", price }, { "Slippage", slippage }, { "Stoploss", stoploss}, { "Takeprofit", takeprofit }, { "Comment", comment }, { "Magic", magic }, { "Expiration", MtApiTimeConverter.ConvertToMtTime(expiration) } }; return SendCommand(ExecutorHandle, MtCommandType.OrderSend, cmdParams); } public int OrderSend(string symbol, TradeOperation cmd, double volume, double price, int slippage, double stoploss, double takeprofit , string comment, int magic) { Log.Debug($"OrderSend: symbol = {symbol}, cmd = {cmd}, volume = {volume}, price = {price}, slippage = {slippage}, stoploss = {stoploss}, takeprofit = {takeprofit}, comment = {comment}, magic = {magic}"); Dictionary cmdParams = new() { { "Symbol", symbol }, { "Cmd", cmd }, { "Volume", volume }, { "Price", price }, { "Slippage", slippage }, { "Stoploss", stoploss}, { "Takeprofit", takeprofit }, { "Comment", comment }, { "Magic", magic } }; return SendCommand(ExecutorHandle, MtCommandType.OrderSend, cmdParams); } public int OrderSend(string symbol, TradeOperation cmd, double volume, double price, int slippage, double stoploss, double takeprofit , string comment) { Log.Debug($"OrderSend: symbol = {symbol}, cmd = {cmd}, volume = {volume}, price = {price}, slippage = {slippage}, stoploss = {stoploss}, takeprofit = {takeprofit}, comment = {comment}"); Dictionary cmdParams = new() { { "Symbol", symbol }, { "Cmd", cmd }, { "Volume", volume }, { "Price", price }, { "Slippage", slippage }, { "Stoploss", stoploss}, { "Takeprofit", takeprofit }, { "Comment", comment } }; return SendCommand(ExecutorHandle, MtCommandType.OrderSend, cmdParams); } public int OrderSend(string symbol, TradeOperation cmd, double volume, double price, int slippage, double stoploss, double takeprofit) { Log.Debug($"OrderSend: symbol = {symbol}, cmd = {cmd}, volume = {volume}, price = {price}, slippage = {slippage}, stoploss = {stoploss}, takeprofit = {takeprofit}"); Dictionary cmdParams = new() { { "Symbol", symbol }, { "Cmd", cmd }, { "Volume", volume }, { "Price", price }, { "Slippage", slippage }, { "Stoploss", stoploss}, { "Takeprofit", takeprofit } }; return SendCommand(ExecutorHandle, MtCommandType.OrderSend, cmdParams); } public int OrderSend(string symbol, TradeOperation cmd, double volume, string price, int slippage, double stoploss, double takeprofit) { Log.Debug($"OrderSend: symbol = {symbol}, cmd = {cmd}, volume = {volume}, price = {price}, slippage = {slippage}, stoploss = {stoploss}, takeprofit = {takeprofit}"); return double.TryParse(price, out double dPrice) ? OrderSend(symbol, cmd, volume, dPrice, slippage, stoploss, takeprofit) : 0; } public int OrderSendBuy(string symbol, double volume, int slippage) { Log.Debug($"OrderSendBuy: symbol = {symbol}, volume = {volume}, slippage = {slippage}"); return OrderSendBuy(symbol, volume, slippage, 0, 0, null, 0); } public int OrderSendSell(string symbol, double volume, int slippage) { return OrderSendSell(symbol, volume, slippage, 0, 0, null, 0); } public int OrderSendBuy(string symbol, double volume, int slippage, double stoploss, double takeprofit) { return OrderSendBuy(symbol, volume, slippage, stoploss, takeprofit, null, 0); } public int OrderSendSell(string symbol, double volume, int slippage, double stoploss, double takeprofit) { return OrderSendSell(symbol, volume, slippage, stoploss, takeprofit, null, 0); } public int OrderSendBuy(string symbol, double volume, int slippage, double stoploss, double takeprofit, string? comment, int magic) { Log.Debug($"OrderSendBuy: symbol = {symbol}, volume = {volume}, slippage = {slippage}, stoploss = {stoploss}, takeprofit = {takeprofit}, comment = {comment}, magic = {magic}"); Dictionary cmdParams = new() { { "Symbol", symbol }, { "Cmd", (int)TradeOperation.OP_BUY }, { "Volume", volume }, { "Slippage", slippage }, { "Stoploss", stoploss}, { "Takeprofit", takeprofit }, { "Magic", magic } }; if (string.IsNullOrEmpty(comment) == false) cmdParams["Comment"] = comment; return SendCommand(ExecutorHandle, MtCommandType.OrderSend, cmdParams); } public int OrderSendSell(string symbol, double volume, int slippage, double stoploss, double takeprofit, string? comment, int magic) { Log.Debug($"OrderSendSell: symbol = {symbol}, volume = {volume}, slippage = {slippage}, stoploss = {stoploss}, takeprofit = {takeprofit}, comment = {comment}, magic = {magic}"); Dictionary cmdParams = new() { { "Symbol", symbol }, { "Cmd", (int)TradeOperation.OP_SELL }, { "Volume", volume }, { "Slippage", slippage }, { "Stoploss", stoploss}, { "Takeprofit", takeprofit }, { "Magic", magic } }; if (string.IsNullOrEmpty(comment) == false) cmdParams["Comment"] = comment; return SendCommand(ExecutorHandle, MtCommandType.OrderSend, cmdParams); } public bool OrderClose(int ticket, double lots, double price, int slippage, Color color) { Log.Debug($"OrderClose: ticket = {ticket}, lots = {lots}, price = {price}, slippage = {slippage}, color = {color}"); Dictionary cmdParams = new() { { "Ticket", ticket }, { "Lots", lots }, { "Price", price }, { "Slippage", slippage }, { "ArrowColor", color} }; return SendCommand(ExecutorHandle, MtCommandType.OrderClose, cmdParams); } public bool OrderClose(int ticket, double lots, double price, int slippage) { Log.Debug($"OrderClose: ticket = {ticket}, lots = {lots}, price = {price}, slippage = {slippage}"); Dictionary cmdParams = new() { { "Ticket", ticket }, { "Lots", lots }, { "Price", price }, { "Slippage", slippage } }; return SendCommand(ExecutorHandle, MtCommandType.OrderClose, cmdParams); } public bool OrderClose(int ticket, double lots, int slippage) { Log.Debug($"OrderClose: ticket = {ticket}, lots = {lots}, slippage = {slippage}"); Dictionary cmdParams = new() { { "Ticket", ticket }, { "Lots", lots }, { "Slippage", slippage } }; return SendCommand(ExecutorHandle, MtCommandType.OrderClose, cmdParams); } public bool OrderClose(int ticket, int slippage) { Log.Debug($"OrderClose: ticket = {ticket}, slippage = {slippage}"); Dictionary cmdParams = new() { { "Ticket", ticket }, { "Slippage", slippage } }; return SendCommand(ExecutorHandle, MtCommandType.OrderClose, cmdParams); } public bool OrderCloseBy(int ticket, int opposite, Color color) { Log.Debug($"OrderCloseBy: ticket = {ticket}, opposite = {opposite}, color = {color}"); Dictionary cmdParams = new() { { "Ticket", ticket }, { "Opposite", opposite }, { "ColorValue", MtApiColorConverter.ConvertToMtColor(color) } }; return SendCommand(ExecutorHandle, MtCommandType.OrderCloseBy, cmdParams); } public bool OrderCloseBy(int ticket, int opposite) { Log.Debug($"OrderCloseBy: ticket = {ticket}, opposite = {opposite}"); Dictionary cmdParams = new() { { "Ticket", ticket }, { "Opposite", opposite } }; return SendCommand(ExecutorHandle, MtCommandType.OrderCloseBy, cmdParams); } public bool OrderDelete(int ticket, Color color) { Log.Debug($"OrderDelete: ticket = {ticket}, color = {color}"); Dictionary cmdParams = new() { { "Ticket", ticket }, { "ArrowColor", MtApiColorConverter.ConvertToMtColor(color) } }; return SendCommand(ExecutorHandle, MtCommandType.OrderDelete, cmdParams); } public bool OrderDelete(int ticket) { Log.Debug($"OrderDelete: ticket = {ticket}"); Dictionary cmdParams = new() { { "Ticket", ticket } }; return SendCommand(ExecutorHandle, MtCommandType.OrderDelete, cmdParams); } public bool OrderModify(int ticket, double price, double stoploss, double takeprofit, DateTime expiration, Color arrowColor) { Log.Debug($"OrderModify: ticket = {ticket}, price = {price}, stoploss = {stoploss}, takeprofit = {takeprofit}, expiration = {expiration}, arrowColor = {arrowColor}"); Dictionary cmdParams = new() { { "Ticket", ticket }, { "Price", price }, { "Stoploss", stoploss}, { "Takeprofit", takeprofit }, { "Expiration", MtApiTimeConverter.ConvertToMtTime(expiration) }, { "ArrowColor", MtApiColorConverter.ConvertToMtColor(arrowColor) } }; return SendCommand(ExecutorHandle, MtCommandType.OrderModify, cmdParams); } public bool OrderModify(int ticket, double price, double stoploss, double takeprofit, DateTime expiration) { Log.Debug($"OrderModify: ticket = {ticket}, price = {price}, stoploss = {stoploss}, takeprofit = {takeprofit}, expiration = {expiration}"); Dictionary cmdParams = new() { { "Ticket", ticket }, { "Price", price }, { "Stoploss", stoploss}, { "Takeprofit", takeprofit }, { "Expiration", MtApiTimeConverter.ConvertToMtTime(expiration) } }; return SendCommand(ExecutorHandle, MtCommandType.OrderModify, cmdParams); } public void OrderPrint() { SendCommand(ExecutorHandle, MtCommandType.OrderPrint); } public bool OrderSelect(int index, OrderSelectMode select, OrderSelectSource pool) { Log.Debug($"OrderSelect: index = {index}, select = {select}, pool = {pool}"); Dictionary cmdParams = new() { { "Index", index }, { "Select", (int)select }, { "Pool", (int)pool} }; return SendCommand(ExecutorHandle, MtCommandType.OrderSelect, cmdParams); } public bool OrderSelect(int index, OrderSelectMode select) { return OrderSelect(index, select, OrderSelectSource.MODE_TRADES); } public int OrdersHistoryTotal() { return SendCommand(ExecutorHandle, MtCommandType.OrdersHistoryTotal); } public int OrdersTotal() { return SendCommand(ExecutorHandle, MtCommandType.OrdersTotal); } public bool OrderCloseAll() { return SendCommand(ExecutorHandle, MtCommandType.OrderCloseAll); } public MtOrder? GetOrder(int index, OrderSelectMode select, OrderSelectSource pool) { Dictionary cmdParams = new() { { "Index", index }, { "Select", (int)select }, { "Pool", (int)pool} }; return SendCommand(ExecutorHandle, MtCommandType.GetOrder, cmdParams); } public List? GetOrders(OrderSelectSource pool) { Dictionary cmdParams = new() { { "Pool", (int)pool} }; return SendCommand>(ExecutorHandle, MtCommandType.GetOrders, cmdParams); } #endregion #region Checkup /// ///Returns the contents of the system variable _LastError. ///After the function call, the contents of _LastError are reset. /// /// ///Returns the value of the last error that occurred during the execution of an mql4 program. /// public int GetLastError() { return SendCommand(ExecutorHandle, MtCommandType.GetLastError); } /// ///Checks connection between client terminal and server. /// /// ///It returns true if connection to the server was successfully established, otherwise, it returns false. /// public bool IsConnected() { return SendCommand(ExecutorHandle, MtCommandType.IsConnected); } /// ///Checks if the Expert Advisor runs on a demo account. /// /// ///Returns true if the Expert Advisor runs on a demo account, otherwise returns false. /// public bool IsDemo() { return SendCommand(ExecutorHandle, MtCommandType.IsDemo); } /// ///Checks if the DLL function call is allowed for the Expert Advisor. /// /// ///Returns true if the DLL function call is allowed for the Expert Advisor, otherwise returns false. /// public bool IsDllsAllowed() { return SendCommand(ExecutorHandle, MtCommandType.IsDllsAllowed); } /// ///Checks if Expert Advisors are enabled for running. /// /// ///Returns true if Expert Advisors are enabled for running, otherwise returns false. /// public bool IsExpertEnabled() { return SendCommand(ExecutorHandle, MtCommandType.IsExpertEnabled); } /// ///Checks if the Expert Advisor can call library function. /// /// ///Returns true if the Expert Advisor can call library function, otherwise returns false. /// public bool IsLibrariesAllowed() { return SendCommand(ExecutorHandle, MtCommandType.IsLibrariesAllowed); } /// ///Checks if Expert Advisor runs in the Strategy Tester optimization mode. /// /// ///Returns true if Expert Advisor runs in the Strategy Tester optimization mode, otherwise returns false. /// public bool IsOptimization() { return SendCommand(ExecutorHandle, MtCommandType.IsOptimization); } /// ///Checks the forced shutdown of an mql4 program. /// /// ///Returns true, if the _StopFlag system variable contains a value other than 0. ///A nonzero value is written into _StopFlag, if a mql4 program has been commanded to complete its operation. ///In this case, you must immediately terminate the program, otherwise the program will be completed ///forcibly from the outside after 3 seconds. /// public bool IsStopped() { return SendCommand(ExecutorHandle, MtCommandType.IsStopped); } /// ///Checks if the Expert Advisor runs in the testing mode. /// /// ///Returns true if the Expert Advisor runs in the testing mode, otherwise returns false. /// public bool IsTesting() { return SendCommand(ExecutorHandle, MtCommandType.IsTesting); } /// ///Checks if the Expert Advisor is allowed to trade and trading context is not busy. /// /// ///Returns true if the Expert Advisor is allowed to trade and trading context is not busy, otherwise returns false. /// public bool IsTradeAllowed() { return SendCommand(ExecutorHandle, MtCommandType.IsTradeAllowed); } /// ///Returns the information about trade context. /// /// ///Returns true if a thread for trading is occupied by another Expert Advisor, otherwise returns false. /// public bool IsTradeContextBusy() { return SendCommand(ExecutorHandle, MtCommandType.IsTradeContextBusy); } /// ///Checks if the Expert Advisor is tested in visual mode. /// /// ///Returns true if the Expert Advisor is tested with checked "Visual Mode" button, otherwise returns false. /// public bool IsVisualMode() { return SendCommand(ExecutorHandle, MtCommandType.IsVisualMode); } /// ///Returns the code of a reason for deinitialization. /// /// ///Returns the value of _UninitReason which is formed before OnDeinit() is called. ///Value depends on the reasons that led to deinitialization. /// public int UninitializeReason() { return SendCommand(ExecutorHandle, MtCommandType.UninitializeReason); } /// ///Print the error description. /// public string? ErrorDescription(int errorCode) { Dictionary cmdParams = new() { { "ErrorCode", errorCode } }; return SendCommand(ExecutorHandle, MtCommandType.ErrorDescription, cmdParams); } /// ///Returns the value of a corresponding property of the mql4 program environment. /// ///Identifier of a property. Can be one of the values of the ENUM_TERMINAL_INFO_STRING enumeration. /// ///Value of string type. /// public string? TerminalInfoString(ENUM_TERMINAL_INFO_STRING propertyId) { Dictionary cmdParams = new() { { "PropertyId", (int)propertyId } }; return SendCommand(ExecutorHandle, MtCommandType.TerminalInfoString, cmdParams); } /// ///Returns the value of a corresponding property of the mql4 program environment. /// ///Identifier of a property. Can be one of the values of the ENUM_TERMINAL_INFO_INTEGER enumeration. /// ///Value of int type. /// public int TerminalInfoInteger(EnumTerminalInfoInteger propertyId) { Dictionary cmdParams = new() { { "PropertyId", (int)propertyId } }; return SendCommand(ExecutorHandle, MtCommandType.TerminalInfoInteger, cmdParams); } /// ///Returns the value of a corresponding property of the mql4 program environment. /// ///Identifier of a property. Can be one of the values of the ENUM_TERMINAL_INFO_DOUBLE enumeration. /// ///Value of double type. /// public double TerminalInfoDouble(EnumTerminalInfoDouble propertyId) { Dictionary cmdParams = new() { { "PropertyId", (int)propertyId } }; return SendCommand(ExecutorHandle, MtCommandType.TerminalInfoDouble, cmdParams); } /// ///Returns the name of company owning the client terminal. /// /// ///The name of company owning the client terminal. /// public string? TerminalCompany() { return SendCommand(ExecutorHandle, MtCommandType.TerminalCompany); } /// ///Returns client terminal name. /// /// ///Client terminal name. /// public string? TerminalName() { return SendCommand(ExecutorHandle, MtCommandType.TerminalName); } /// ///Returns the directory, from which the client terminal was launched. /// /// ///The directory, from which the client terminal was launched. /// public string? TerminalPath() { return SendCommand(ExecutorHandle, MtCommandType.TerminalPath); } #endregion #region Account functions public double AccountBalance() { return SendCommand(ExecutorHandle, MtCommandType.AccountBalance); } public double AccountCredit() { return SendCommand(ExecutorHandle, MtCommandType.AccountCredit); } public string? AccountCompany() { return SendCommand(ExecutorHandle, MtCommandType.AccountCompany); } public string? AccountCurrency() { return SendCommand(ExecutorHandle, MtCommandType.AccountCurrency); } public double AccountEquity() { return SendCommand(ExecutorHandle, MtCommandType.AccountEquity); } public double AccountFreeMargin() { return SendCommand(ExecutorHandle, MtCommandType.AccountFreeMargin); } public double AccountFreeMarginCheck(string symbol, TradeOperation cmd, double volume) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Cmd", cmd }, { "Volume", volume } }; return SendCommand(ExecutorHandle, MtCommandType.AccountFreeMarginCheck, cmdParams); } public double AccountFreeMarginMode() { return SendCommand(ExecutorHandle, MtCommandType.AccountFreeMarginMode); } public int AccountLeverage() { return SendCommand(ExecutorHandle, MtCommandType.AccountLeverage); } public double AccountMargin() { return SendCommand(ExecutorHandle, MtCommandType.AccountMargin); } public string? AccountName() { return SendCommand(ExecutorHandle, MtCommandType.AccountName); } public int AccountNumber() { return SendCommand(ExecutorHandle, MtCommandType.AccountNumber); } public double AccountProfit() { return SendCommand(ExecutorHandle, MtCommandType.AccountProfit); } public string? AccountServer() { return SendCommand(ExecutorHandle, MtCommandType.AccountServer); } public int AccountStopoutLevel() { return SendCommand(ExecutorHandle, MtCommandType.AccountStopoutLevel); } public int AccountStopoutMode() { return SendCommand(ExecutorHandle, MtCommandType.AccountStopoutMode); } public bool ChangeAccount(string login, string password, string host) { Dictionary cmdParams = new() { { "Login", login }, { "Password", password }, { "Host", host } }; return SendCommand(ExecutorHandle, MtCommandType.ChangeAccount, cmdParams); } #endregion #region Common Function public void Alert(string msg) { Dictionary cmdParams = new() { { "Msg", msg } }; SendCommand(ExecutorHandle, MtCommandType.Alert, cmdParams); } public void Comment(string msg) { Dictionary cmdParams = new() { { "Msg", msg } }; SendCommand(ExecutorHandle, MtCommandType.Comment, cmdParams); } public int GetTickCount() { return SendCommand(ExecutorHandle, MtCommandType.GetTickCount); } public int MessageBox(string text, string caption, int flag) { Dictionary cmdParams = new() { { "Text", text }, { "Caption", caption }, { "Flag", flag } }; return SendCommand(ExecutorHandle, MtCommandType.MessageBoxA, cmdParams); } public int MessageBox(string text, string caption) { return MessageBox(text, caption, EMPTY); } public int MessageBox(string text) { Dictionary cmdParams = new() { { "Text", text } }; return SendCommand(ExecutorHandle, MtCommandType.MessageBox, cmdParams); } public bool PlaySound(string filename) { Dictionary cmdParams = new() { { "Filename", filename } }; return SendCommand(ExecutorHandle, MtCommandType.PlaySound, cmdParams); } public void Print(string msg) { Dictionary cmdParams = new() { { "Msg", msg } }; SendCommand(ExecutorHandle, MtCommandType.Print, cmdParams); } public bool SendFTP(string filename) { Dictionary cmdParams = new() { { "Filename", filename } }; return SendCommand(ExecutorHandle, MtCommandType.SendFTP, cmdParams); } public bool SendFTP(string filename, string ftpPath) { Dictionary cmdParams = new() { { "Filename", filename }, { "FtpPath", ftpPath } }; return SendCommand(ExecutorHandle, MtCommandType.SendFTPA, cmdParams); } public bool SendMail(string subject, string someText) { Dictionary cmdParams = new() { { "Subject", subject }, { "SomeText", someText } }; return SendCommand(ExecutorHandle, MtCommandType.SendMail, cmdParams); } public void Sleep(int milliseconds) { Dictionary cmdParams = new() { { "Milliseconds", milliseconds } }; SendCommand(ExecutorHandle, MtCommandType.Sleep, cmdParams); } #endregion #region Date and Time Functions public int Day() { return SendCommand(ExecutorHandle, MtCommandType.Day); } public int DayOfWeek() { return SendCommand(ExecutorHandle, MtCommandType.DayOfWeek); } public int DayOfYear() { return SendCommand(ExecutorHandle, MtCommandType.DayOfYear); } public int Hour() { return SendCommand(ExecutorHandle, MtCommandType.Hour); } public int Minute() { return SendCommand(ExecutorHandle, MtCommandType.Minute); } public int Month() { return SendCommand(ExecutorHandle, MtCommandType.Month); } public int Seconds() { return SendCommand(ExecutorHandle, MtCommandType.Seconds); } public DateTime TimeCurrent() { var commandResponse = SendCommand(ExecutorHandle, MtCommandType.TimeCurrent); return MtApiTimeConverter.ConvertFromMtTime(commandResponse); } public DateTime TimeGMT() { var commandResponse = SendCommand(ExecutorHandle, MtCommandType.TimeGMT); return MtApiTimeConverter.ConvertFromMtTime(commandResponse); } public int TimeDay(DateTime date) { Dictionary cmdParams = new() { { "Date", MtApiTimeConverter.ConvertToMtTime(date) } }; return SendCommand(ExecutorHandle, MtCommandType.TimeDay, cmdParams); } public int TimeDayOfWeek(DateTime date) { Dictionary cmdParams = new() { { "Date", MtApiTimeConverter.ConvertToMtTime(date) } }; return SendCommand(ExecutorHandle, MtCommandType.TimeDayOfWeek, cmdParams); } public int TimeDayOfYear(DateTime date) { Dictionary cmdParams = new() { { "Date", MtApiTimeConverter.ConvertToMtTime(date) } }; return SendCommand(ExecutorHandle, MtCommandType.TimeDayOfYear, cmdParams); } public int TimeHour(DateTime time) { Dictionary cmdParams = new() { { "TIme", MtApiTimeConverter.ConvertToMtTime(time) } }; return SendCommand(ExecutorHandle, MtCommandType.TimeHour, cmdParams); } public DateTime TimeLocal() { var commandResponse = SendCommand(ExecutorHandle, MtCommandType.TimeLocal); return MtApiTimeConverter.ConvertFromMtTime(commandResponse); } public int TimeMinute(DateTime time) {; Dictionary cmdParams = new() { { "TIme", MtApiTimeConverter.ConvertToMtTime(time) } }; return SendCommand(ExecutorHandle, MtCommandType.TimeMinute, cmdParams); } public int TimeMonth(DateTime time) { Dictionary cmdParams = new() { { "TIme", MtApiTimeConverter.ConvertToMtTime(time) } }; return SendCommand(ExecutorHandle, MtCommandType.TimeMonth, cmdParams); } public int TimeSeconds(DateTime time) { Dictionary cmdParams = new() { { "TIme", MtApiTimeConverter.ConvertToMtTime(time) } }; return SendCommand(ExecutorHandle, MtCommandType.TimeSeconds, cmdParams); } public int TimeYear(DateTime time) { Dictionary cmdParams = new() { { "TIme", MtApiTimeConverter.ConvertToMtTime(time) } }; return SendCommand(ExecutorHandle, MtCommandType.TimeYear, cmdParams); } public int Year(DateTime time) { Dictionary cmdParams = new() { { "TIme", MtApiTimeConverter.ConvertToMtTime(time) } }; return SendCommand(ExecutorHandle, MtCommandType.Year, cmdParams); } #endregion #region Global Variables Functions public bool GlobalVariableCheck(string name) { Dictionary cmdParams = new() { { "Name", name } }; return SendCommand(ExecutorHandle, MtCommandType.GlobalVariableCheck, cmdParams); } public bool GlobalVariableDel(string name) { Dictionary cmdParams = new() { { "Name", name } }; return SendCommand(ExecutorHandle, MtCommandType.GlobalVariableDel, cmdParams); } public double GlobalVariableGet(string name) { Dictionary cmdParams = new() { { "Name", name } }; return SendCommand(ExecutorHandle, MtCommandType.GlobalVariableGet, cmdParams); } public string? GlobalVariableName(int index) { Dictionary cmdParams = new() { { "Index", index } }; return SendCommand(ExecutorHandle, MtCommandType.GlobalVariableName, cmdParams); } public DateTime GlobalVariableSet(string name, double value) { Dictionary cmdParams = new() { { "Name", name }, { "Value", value } }; var commandResponse = SendCommand(ExecutorHandle, MtCommandType.GlobalVariableSet, cmdParams); return MtApiTimeConverter.ConvertFromMtTime(commandResponse); } public bool GlobalVariableSetOnCondition(string name, double value, double checkValue) { Dictionary cmdParams = new() { { "Name", name }, { "Value", value }, { "CheckValue", checkValue } }; return SendCommand(ExecutorHandle, MtCommandType.GlobalVariableSetOnCondition, cmdParams); } public int GlobalVariablesDeleteAll(string prefixName) { Dictionary cmdParams = new() { { "PrefixName", prefixName } }; return SendCommand(ExecutorHandle, MtCommandType.GlobalVariableSetOnCondition, cmdParams); } public int GlobalVariablesTotal() { return SendCommand(ExecutorHandle, MtCommandType.GlobalVariablesTotal, null); } #endregion #region Technical Indicators public double iAC(string symbol, ChartPeriod timeframe, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", (int)timeframe }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iAC, cmdParams); } public double iAD(string symbol, int timeframe, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iAD, cmdParams); } public double iAlligator(string symbol, int timeframe, int jawPeriod, int jawShift, int teethPeriod, int teethShift, int lipsPeriod, int lipsShift, int maMethod, int appliedPrice, int mode, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "JawPeriod", jawPeriod }, { "JawShift", jawShift }, { "TeethPeriod", teethPeriod }, { "TeethShift", teethShift }, { "LipsPeriod", lipsPeriod }, { "LipsShift", lipsShift }, { "MaMethod", maMethod }, { "AppliedPrice", appliedPrice }, { "Mode", mode }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iAlligator, cmdParams); } public double iADX(string symbol, int timeframe, int period, int appliedPrice, int mode, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Period", period }, { "AppliedPrice", appliedPrice }, { "Mode", mode }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iADX, cmdParams); } public double iATR(string symbol, int timeframe, int period, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Period", period }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iATR, cmdParams); } public double iAO(string symbol, int timeframe, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iAO, cmdParams); } public double iBearsPower(string symbol, int timeframe, int period, int appliedPrice, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Period", period }, { "AppliedPrice", appliedPrice }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iBearsPower, cmdParams); } public double iBands(string symbol, int timeframe, int period, int deviation, int bandsShift, int appliedPrice, int mode, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Period", period }, { "Deviation", deviation }, { "BandsShift", bandsShift }, { "AppliedPrice", appliedPrice }, { "Mode", mode }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iBands, cmdParams); } public double iBandsOnArray(double[] array, int total, int period, int deviation, int bandsShift, int mode, int shift) { Dictionary cmdParams = new() { { "Total", total }, { "Period", period }, { "Deviation", deviation }, { "BandsShift", bandsShift }, { "Mode", mode }, { "Data", array ?? [] }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iBandsOnArray, cmdParams); } public double iBullsPower(string symbol, int timeframe, int period, int appliedPrice, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Period", period }, { "AppliedPrice", appliedPrice }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iBullsPower, cmdParams); } public double iCCI(string symbol, int timeframe, int period, int appliedPrice, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Period", period }, { "AppliedPrice", appliedPrice }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iCCI, cmdParams); } public double iCCIOnArray(double[] array, int total, int period, int shift) { Dictionary cmdParams = new() { { "Total", total }, { "Period", period }, { "Data", array ?? [] }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iCCIOnArray, cmdParams); } public double iCustom(string symbol, int timeframe, string name, int[] parameters, int mode, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Name", name }, { "Mode", mode }, { "Shift", shift }, { "ParamsType", (int)ParametersType.Int }, { "Params", new ArrayList(parameters) } }; return SendCommand(ExecutorHandle, MtCommandType.iCustom, cmdParams); } public double iCustom(string symbol, int timeframe, string name, double[] parameters, int mode, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Name", name }, { "Mode", mode }, { "Shift", shift }, { "ParamsType", (int)ParametersType.Double }, { "Params", new ArrayList(parameters) } }; return SendCommand(ExecutorHandle, MtCommandType.iCustom, cmdParams); } public double iCustom(string symbol, int timeframe, string name, int mode, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Name", name }, { "Mode", mode }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iCustom, cmdParams); } public double iDeMarker(string symbol, int timeframe, int period, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Period", period }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iDeMarker, cmdParams); } public double iEnvelopes(string symbol, int timeframe, int maPeriod, int maMethod, int maShift, int appliedPrice, double deviation, int mode, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "MaPeriod", maPeriod }, { "MaMethod", maMethod }, { "MaShift", maShift }, { "AppliedPrice", appliedPrice }, { "Deviation", deviation }, { "Mode", mode }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iEnvelopes, cmdParams); } public double iEnvelopesOnArray(double[] array, int total, int maPeriod, int maMethod, int maShift, double deviation, int mode, int shift) { Dictionary cmdParams = new() { { "Total", total }, { "MaPeriod", maPeriod }, { "MaMethod", maMethod }, { "MaShift", maShift }, { "Deviation", deviation }, { "Mode", mode }, { "Shift", shift }, { "Data", array ?? [] } }; return SendCommand(ExecutorHandle, MtCommandType.iEnvelopesOnArray, cmdParams); } public double iForce(string symbol, int timeframe, int period, int maMethod, int appliedPrice, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Period", period }, { "MaMethod", maMethod }, { "AppliedPrice", appliedPrice }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iForce, cmdParams); } public double iFractals(string symbol, int timeframe, int mode, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Mode", mode }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iFractals, cmdParams); } public double iGator(string symbol, int timeframe, int jawPeriod, int jawShift, int teethPeriod, int teethShift, int lipsPeriod, int lipsShift, int maMethod, int appliedPrice, int mode, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "JawPeriod", jawPeriod }, { "JawShift", jawShift }, { "TeethPeriod", teethPeriod }, { "TeethShift", teethShift }, { "LipsPeriod", lipsPeriod }, { "LipsShift", lipsShift }, { "MaMethod", maMethod }, { "AppliedPrice", appliedPrice }, { "Mode", mode }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iGator, cmdParams); } public double iIchimoku(string symbol, int timeframe, int tenkanSen, int kijunSen, int senkouSpanB, int mode, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "TenkanSen", tenkanSen }, { "KijunSen", kijunSen }, { "SenkouSpanB", senkouSpanB }, { "Mode", mode }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iIchimoku, cmdParams); } public double iBWMFI(string symbol, int timeframe, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iBWMFI, cmdParams); } public double iMomentum(string symbol, int timeframe, int period, int appliedPrice, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Period", period }, { "AppliedPrice", appliedPrice }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iMomentum, cmdParams); } public double iMomentumOnArray(double[] array, int total, int period, int shift) { Dictionary cmdParams = new() { { "Total", total }, { "Period", period }, { "Shift", shift }, { "Data", array ?? [] } }; return SendCommand(ExecutorHandle, MtCommandType.iMomentumOnArray, cmdParams); } public double iMFI(string symbol, int timeframe, int period, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Period", period }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iMFI, cmdParams); } public double iMA(string symbol, int timeframe, int period, int maShift, int maMethod, int appliedPrice, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Period", period }, { "MaShift", maShift }, { "MaMethod", maMethod }, { "AppliedPrice", appliedPrice }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iMA, cmdParams); } public double iMAOnArray(double[] array, int total, int period, int maShift, int maMethod, int shift) { Dictionary cmdParams = new() { { "Total", total }, { "Period", period }, { "MaShift", maShift }, { "MaMethod", maMethod }, { "Shift", shift }, { "Data", array ?? [] } }; return SendCommand(ExecutorHandle, MtCommandType.iMAOnArray, cmdParams); } public double iOsMA(string symbol, int timeframe, int fastEmaPeriod, int slowEmaPeriod, int signalPeriod, int appliedPrice, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "FastEmaPeriod", fastEmaPeriod }, { "SlowEmaPeriod", slowEmaPeriod }, { "SignalPeriod", signalPeriod }, { "AppliedPrice", appliedPrice }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iOsMA, cmdParams); } public double iMACD(string symbol, int timeframe, int fastEmaPeriod, int slowEmaPeriod, int signalPeriod, int appliedPrice, int mode, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "FastEmaPeriod", fastEmaPeriod }, { "SlowEmaPeriod", slowEmaPeriod }, { "SignalPeriod", signalPeriod }, { "AppliedPrice", appliedPrice }, { "Mode", mode }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iMACD, cmdParams); } public double iOBV(string symbol, int timeframe, int appliedPrice, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "AppliedPrice", appliedPrice }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iOBV, cmdParams); } public double iSAR(string symbol, int timeframe, double step, double maximum, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Step", step }, { "Maximum", maximum }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iSAR, cmdParams); } public double iRSI( string symbol, int timeframe, int period, int appliedPrice, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Period", period }, { "AppliedPrice", appliedPrice }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iRSI, cmdParams); } public double iRSIOnArray(double[] array, int total, int period, int shift) { Dictionary cmdParams = new() { { "Total", total }, { "Period", period }, { "Shift", shift }, { "Data", array ?? [] } }; return SendCommand(ExecutorHandle, MtCommandType.iMomentumOnArray, cmdParams); } public double iRVI(string symbol, int timeframe, int period, int mode, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Period", period }, { "Mode", mode }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iRVI, cmdParams); } public double iStdDev(string symbol, int timeframe, int maPeriod, int maShift, int maMethod, int appliedPrice, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "MaPeriod", maPeriod }, { "MaShift", maShift }, { "MaMethod", maMethod }, { "AppliedPrice", appliedPrice }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iStdDev, cmdParams); } public double iStdDevOnArray(double[] array, int total, int maPeriod, int maShift, int maMethod, int shift) { Dictionary cmdParams = new() { { "Total", total }, { "MaPeriod", maPeriod }, { "MaShift", maShift }, { "MaMethod", maMethod }, { "Shift", shift }, { "Data", array ?? [] } }; return SendCommand(ExecutorHandle, MtCommandType.iStdDevOnArray, cmdParams); } public double iStochastic(string symbol, int timeframe, int pKperiod, int pDperiod, int slowing, int method, int priceField, int mode, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Kperiod", pKperiod }, { "Dperiod", pDperiod }, { "Slowing", slowing }, { "Method", method }, { "PriceField", priceField }, { "Mode", mode }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iStochastic, cmdParams); } public double iWPR(string symbol, int timeframe, int period, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe }, { "Period", period }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iWPR, cmdParams); } #endregion #region Timeseries access public int iBars(string symbol, ChartPeriod timeframe) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", (int)timeframe } }; return SendCommand(ExecutorHandle, MtCommandType.iBars, cmdParams); } public int iBarShift(string symbol, ChartPeriod timeframe, DateTime time, bool exact) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", (int)timeframe }, { "Time", MtApiTimeConverter.ConvertToMtTime(time) }, { "Exact", exact } }; return SendCommand(ExecutorHandle, MtCommandType.iBarShift, cmdParams); } public double iClose(string symbol, ChartPeriod timeframe, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", (int)timeframe }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iClose, cmdParams); } public double iHigh(string symbol, ChartPeriod timeframe, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", (int)timeframe }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iHigh, cmdParams); } public int iHighest(string symbol, ChartPeriod timeframe, SeriesIdentifier type, int count, int start) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", (int)timeframe }, { "Type", (int)type }, { "Count", count }, { "StartValue", start } }; return SendCommand(ExecutorHandle, MtCommandType.iHighest, cmdParams); } public double iLow(string symbol, ChartPeriod timeframe, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", (int)timeframe }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iLow, cmdParams); } public int iLowest(string symbol, ChartPeriod timeframe, SeriesIdentifier type, int count, int start) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", (int)timeframe }, { "Type", type }, { "Count", count }, { "Start", start } }; return SendCommand(ExecutorHandle, MtCommandType.iLowest, cmdParams); } public double iOpen(string symbol, ChartPeriod timeframe, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", (int)timeframe }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iOpen, cmdParams); } public DateTime iTime(string symbol, ChartPeriod timeframe, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", (int)timeframe }, { "Shift", shift } }; var commandResponse = SendCommand(ExecutorHandle, MtCommandType.iTime, cmdParams); return MtApiTimeConverter.ConvertFromMtTime(commandResponse); } public double iVolume(string symbol, ChartPeriod timeframe, int shift) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", (int)timeframe }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.iVolume, cmdParams); } public double[]? iCloseArray(string symbol, ChartPeriod timeframe) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", (int)timeframe } }; return SendCommand(ExecutorHandle, MtCommandType.iCloseArray, cmdParams); } public double[]? iHighArray(string symbol, ChartPeriod timeframe) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", (int)timeframe } }; return SendCommand(ExecutorHandle, MtCommandType.iHighArray, cmdParams); } public double[]? iLowArray(string symbol, ChartPeriod timeframe) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", (int)timeframe } }; return SendCommand(ExecutorHandle, MtCommandType.iLowArray, cmdParams); } public double[]? iOpenArray(string symbol, ChartPeriod timeframe) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", (int)timeframe } }; return SendCommand(ExecutorHandle, MtCommandType.iOpenArray, cmdParams); } public double[]? iVolumeArray(string symbol, ChartPeriod timeframe) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", (int)timeframe } }; return SendCommand(ExecutorHandle, MtCommandType.iVolumeArray, cmdParams); } public DateTime[]? iTimeArray(string symbol, ChartPeriod timeframe) { DateTime[]? result = null; Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", (int)timeframe } }; var response = SendCommand(ExecutorHandle, MtCommandType.iTimeArray, cmdParams); if (response != null) { result = new DateTime[response.Length]; for(var i = 0; i < response.Length; i++) result[i] = MtApiTimeConverter.ConvertFromMtTime(response[i]); } return result; } public bool RefreshRates() { return SendCommand(ExecutorHandle, MtCommandType.RefreshRates, null); } public List? CopyRates(string symbolName, ENUM_TIMEFRAMES timeframe, int startPos, int count) { Dictionary cmdParams = new() { { "SymbolName", symbolName }, { "Timeframe", (int)timeframe }, { "StartPos", startPos }, { "Count", count }, { "CopyRatesType", 1 } }; return SendCommand>(ExecutorHandle, MtCommandType.CopyRates, cmdParams); } public List? CopyRates(string symbolName, ENUM_TIMEFRAMES timeframe, DateTime startTime, int count) { Dictionary cmdParams = new() { { "SymbolName", symbolName }, { "Timeframe", (int)timeframe }, { "StartTime", MtApiTimeConverter.ConvertToMtTime(startTime) },{ "Count", count }, { "CopyRatesType", 2 } }; return SendCommand>(ExecutorHandle, MtCommandType.CopyRates, cmdParams); } public List? CopyRates(string symbolName, ENUM_TIMEFRAMES timeframe, DateTime startTime, DateTime stopTime) { Dictionary cmdParams = new() { { "SymbolName", symbolName }, { "Timeframe", (int)timeframe }, { "StartTime", MtApiTimeConverter.ConvertToMtTime(startTime) }, { "StopTime", MtApiTimeConverter.ConvertToMtTime(stopTime) }, { "CopyRatesType", 3 } }; return SendCommand>(ExecutorHandle, MtCommandType.CopyRates, cmdParams); } /// ///Returns information about the state of historical data. /// ///Symbol name. ///Period. ///Identifier of the requested property, value of the ENUM_SERIES_INFO_INTEGER enumeration. /// ///Returns value of the long type. /// public long SeriesInfoInteger(string symbolName, ENUM_TIMEFRAMES timeframe, EnumSeriesInfoInteger propId) { Dictionary cmdParams = new() { { "SymbolName", symbolName }, { "Timeframe", (int)timeframe }, { "PropId", (int)propId } }; return SendCommand(ExecutorHandle, MtCommandType.SeriesInfoInteger, cmdParams); } #endregion #region Market Info /// ///Returns various data about securities listed in the "Market Watch" window. /// ///Symbol name. ///Request identifier that defines the type of information to be returned. Can be any of values of request identifiers. /// ///Returns various data about securities listed in the "Market Watch" window. /// public double MarketInfo(string symbol, MarketInfoModeType type) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Type", (int)type } }; return SendCommand(ExecutorHandle, MtCommandType.MarketInfo, cmdParams); } /// ///Returns the number of available (selected in Market Watch or all) symbols. /// ///Request mode. Can be true or false. /// ///If the 'selected' parameter is true, the function returns the number of symbols selected in MarketWatch. If the value is false, it returns the total number of all symbols. /// public int SymbolsTotal(bool selected) { Dictionary cmdParams = new() { { "Selected", selected } }; return SendCommand(ExecutorHandle, MtCommandType.SymbolsTotal, cmdParams); } /// ///Returns the name of a symbol. /// ///Order number of a symbol. ///Request mode. If the value is true, the symbol is taken from the list of symbols selected in MarketWatch. If the value is false, the symbol is taken from the general list. /// ///Value of string type with the symbol name. /// public string? SymbolName(int pos, bool selected) { Dictionary cmdParams = new() { { "Pos", pos }, { "Selected", selected } }; return SendCommand(ExecutorHandle, MtCommandType.SymbolName, cmdParams); } /// ///Selects a symbol in the Market Watch window or removes a symbol from the window. /// ///Symbol name ///Switch. If the value is false, a symbol should be removed from MarketWatch, otherwise a symbol should be selected in this window. A symbol can't be removed if the symbol chart is open, or there are open orders for this symbol. /// ///In case of failure returns false. /// public bool SymbolSelect(string name, bool select) { Dictionary cmdParams = new() { { "Name", name }, { "Select", select } }; return SendCommand(ExecutorHandle, MtCommandType.SymbolSelect, cmdParams); } /// ///Returns the corresponding property of a specified symbol. /// ///Symbol name ///Identifier of a symbol property. The value can be one of the values of the EnumSymbolInfoInteger enumeration /// ///The value of long type. /// public long SymbolInfoInteger(string name, EnumSymbolInfoInteger propId) { Dictionary cmdParams = new() { { "Name", name }, { "PropId", (int)propId } }; return SendCommand(ExecutorHandle, MtCommandType.SymbolInfoInteger, cmdParams); } /// ///Returns the corresponding property of a specified symbol. /// ///Symbol name ///Identifier of a symbol property. The value can be one of the values of the ENUM_SYMBOL_INFO_STRING enumeration. /// ///The value of string type. /// public string? SymbolInfoString(string name, ENUM_SYMBOL_INFO_STRING propId) { Dictionary cmdParams = new() { { "Name", name }, { "PropId", (int)propId } }; return SendCommand(ExecutorHandle, MtCommandType.SymbolInfoString, cmdParams); } /// ///Allows receiving time of beginning and end of the specified quoting/trading sessions for a specified symbol and day of week. /// /// ///Symbol name. ///Day of the week. ///Ordinal number of a session, whose beginning and end time we want to receive. Indexing of sessions starts with 0. ///Session type: Quote, Trade /// ///The value session. /// public MtSession? SymbolInfoSession(string symbol, DayOfWeek dayOfWeek, uint index, SessionType type) { Dictionary cmdParams = new() { { "SymbolName", symbol }, { "DayOfWeek", (int)dayOfWeek }, { "SessionIndex", (int)index }, { "SessionType", type } }; return SendCommand(ExecutorHandle, MtCommandType.Session, cmdParams); } /// ///Returns the corresponding property of a specified symbol. /// ///Symbol name. ///Identifier of a symbol property. The value can be one of the values of the ENUM_SYMBOL_INFO_DOUBLE enumeration. /// /// The value of double type. /// public double SymbolInfoDouble(string symbolName, EnumSymbolInfoDouble propId) { Dictionary cmdParams = new() { { "SymbolName", symbolName }, { "PropId", (int)propId } }; return SendCommand(ExecutorHandle, MtCommandType.SymbolInfoDouble, cmdParams); } /// ///Returns the corresponding property of a specified symbol. /// ///Symbol name. /// /// MqlTick object, to which the current prices and time of the last price update will be placed. /// public MqlTick? SymbolInfoTick(string symbol) { Dictionary cmdParams = new() { { "Symbol", symbol } }; return SendCommand(ExecutorHandle, MtCommandType.SymbolInfoTick, cmdParams); } #endregion #region Chart Operations /// ///Returns the ID of the current chart. /// /// /// Value of long type. /// public long ChartId() { return SendCommand(ExecutorHandle, MtCommandType.ChartId); } /// ///This function calls a forced redrawing of a specified chart. /// public void ChartRedraw(long chartId = 0) { Dictionary cmdParams = new() { { "ChartId", chartId } }; SendCommand(ExecutorHandle, MtCommandType.ChartRedraw, cmdParams); } /// ///Applies a specific template from a specified file to the chart. /// ///Chart ID. ///The name of the file containing the template. /// ///Returns true if the command has been added to chart queue, otherwise false. /// public bool ChartApplyTemplate(long chartId, string filename) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "Filename", filename } }; return SendCommand(ExecutorHandle, MtCommandType.ChartApplyTemplate, cmdParams); } /// ///Saves current chart settings in a template with a specified name. /// ///Chart ID. ///The filename to save the template. The ".tpl" extension will be added to the filename automatically; there is no need to specify it. The template is saved in data_folder\templates\ and can be used for manual application in the terminal. If a template with the same filename already exists, the contents of this file will be overwritten. /// ///Returns true if the command has been added to chart queue, otherwise false. /// public bool ChartSaveTemplate(long chartId, string filename) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "Filename", filename } }; return SendCommand(ExecutorHandle, MtCommandType.ChartSaveTemplate, cmdParams); } /// ///The function returns the number of a subwindow where an indicator is drawn. /// ///Chart ID. ///Short name of the indicator. /// ///Subwindow number in case of success. In case of failure the function returns -1. /// public int ChartWindowFind(long chartId, string indicatorShortname) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "IndicatorShortname", indicatorShortname } }; return SendCommand(ExecutorHandle, MtCommandType.ChartWindowFind, cmdParams); } /// ///The function returns the number of a subwindow where an indicator is drawn. /// ///Chart ID. ///The number of the chart subwindow. 0 means the main chart window. ///The time value on the chart, for which the value in pixels along the X axis will be received. ///The price value on the chart, for which the value in pixels along the Y axis will be received. ///The variable, into which the conversion of time to X will be received. The origin is in the upper left corner of the main chart window. ///The variable, into which the conversion of price to Y will be received. The origin is in the upper left corner of the main chart window. /// ///Subwindow number in case of success. In case of failure the function returns -1. /// public bool ChartTimePriceToXY(long chartId, int subWindow, DateTime? time, double price, out int x, out int y) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "SubWindow", subWindow }, { "Time", MtApiTimeConverter.ConvertToMtTime(time) }, { "Price", price } }; var response = SendCommand>>(ExecutorHandle, MtCommandType.ChartTimePriceToXY, cmdParams); if (response != null && response.Result != null && response.Result.TryGetValue("X", out x) && response.Result.TryGetValue("Y", out y)) return response.RetVal; x = 0; y = 0; return false; } /// ///The function returns the number of a subwindow where an indicator is drawn. /// ///Chart ID. ///The variable, into which the conversion of time to X will be received. The origin is in the upper left corner of the main chart window. ///The variable, into which the conversion of price to Y will be received. The origin is in the upper left corner of the main chart window. ///The number of the chart subwindow. 0 means the main chart window. ///The time value on the chart, for which the value in pixels along the X axis will be received. ///The price value on the chart, for which the value in pixels along the Y axis will be received. /// ///Subwindow number in case of success. In case of failure the function returns -1. /// public bool ChartXYToTimePrice(long chartId, int x, int y, out int subWindow, out DateTime? time, out double price) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "X", x }, { "Y", y } }; var response = SendCommand>>(ExecutorHandle, MtCommandType.ChartXYToTimePrice, cmdParams); if (response != null && response.Result != null && response.Result.TryGetValue("SubWindow", out object? mtSubWindow) && response.Result.TryGetValue("Time", out object? mtTime) && response.Result.TryGetValue("Price", out object? mtPrice)) { subWindow = Convert.ToInt32(mtSubWindow); time = MtApiTimeConverter.ConvertFromMtTime(Convert.ToInt32(mtTime)); price = Convert.ToDouble(mtPrice); return response.RetVal; } subWindow = 0; time = null; price = double.NaN; return false; } /// ///Opens a new chart with the specified symbol and period. /// ///Chart symbol. NULL means the symbol of the current chart (the Expert Advisor is attached to). /// Chart period (timeframe). Can be one of the ENUM_TIMEFRAMES values. 0 means the current chart period. /// ///If successful, it returns the opened chart ID. Otherwise returns 0. /// public long ChartOpen(string symbol, ENUM_TIMEFRAMES period) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Period", period } }; return SendCommand(ExecutorHandle, MtCommandType.ChartOpen, cmdParams); } /// ///Returns the ID of the first chart of the client terminal. /// public long ChartFirst() { return SendCommand(ExecutorHandle, MtCommandType.ChartFirst); } /// ///Returns the chart ID of the chart next to the specified one. /// ///Chart ID. 0 does not mean the current chart. 0 means "return the first chart ID". /// ///Chart ID. If this is the end of the chart list, it returns -1. /// public long ChartNext(long chartId) { Dictionary cmdParams = new() { { "ChartId", chartId } }; return SendCommand(ExecutorHandle, MtCommandType.ChartNext, cmdParams); } /// ///Closes the specified chart. /// ///Chart ID. 0 means the current chart. /// ///If successful, returns true, otherwise false. /// public bool ChartClose(long chartId) { Dictionary cmdParams = new() { { "ChartId", chartId } }; return SendCommand(ExecutorHandle, MtCommandType.ChartClose, cmdParams); } /// ///Returns the symbol name for the specified chart. /// ///Chart ID. 0 means the current chart. /// ///If chart does not exist, the result will be an empty string. /// public string? ChartSymbol(long chartId) { Dictionary cmdParams = new() { { "ChartId", chartId } }; return SendCommand(ExecutorHandle, MtCommandType.ChartSymbol, cmdParams); } /// ///Returns the timeframe period of specified chart. /// ///Chart ID. 0 means the current chart. /// ///The function returns one of the ENUM_TIMEFRAMES values. If chart does not exist, it returns 0. /// public ENUM_TIMEFRAMES ChartPeriod(long chartId) { Dictionary cmdParams = new() { { "ChartId", chartId } }; return (ENUM_TIMEFRAMES) SendCommand(ExecutorHandle, MtCommandType.ChartPeriod, cmdParams); } /// ///Sets a value for a corresponding property of the specified chart. Chart property should be of a double type. /// ///Chart ID. 0 means the current chart. ///Chart property ID. Can be one of the ENUM_CHART_PROPERTY_DOUBLE values (except the read-only properties). ///Property value. /// ///Returns true if the command has been added to chart queue, otherwise false. /// public bool ChartSetDouble(long chartId, EnumChartPropertyDouble propId, double value) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "PropId", (int)propId }, { "Value", value } }; return SendCommand(ExecutorHandle, MtCommandType.ChartSetDouble, cmdParams); } /// ///Sets a value for a corresponding property of the specified chart. Chart property must be datetime, int, color, bool or char. /// ///Chart ID. 0 means the current chart. ///Chart property ID. It can be one of the ENUM_CHART_PROPERTY_INTEGER value (except the read-only properties). ///Property value. /// ///Returns true if the command has been added to chart queue, otherwise false. /// public bool ChartSetInteger(long chartId, EnumChartPropertyInteger propId, long value) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "PropId", (int)propId }, { "Value", value } }; return SendCommand(ExecutorHandle, MtCommandType.ChartSetInteger, cmdParams); } /// ///Sets a value for a corresponding property of the specified chart. Chart property must be of the string type. /// ///Chart ID. 0 means the current chart. ///Chart property ID. Its value can be one of the ENUM_CHART_PROPERTY_STRING values (except the read-only properties). ///Property value string. String length cannot exceed 2045 characters (extra characters will be truncated). /// ///Returns true if the command has been added to chart queue, otherwise false. /// public bool ChartSetString(long chartId, EnumChartPropertyString propId, string value) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "PropId", (int)propId }, { "Value", value } }; return SendCommand(ExecutorHandle, MtCommandType.ChartSetString, cmdParams); } /// ///Sets a value for a corresponding property of the specified chart. Chart property must be of the string type. /// ///Chart ID. 0 means the current chart. ///Chart property ID. This value can be one of the ENUM_CHART_PROPERTY_DOUBLE values. ///Number of the chart subwindow. For the first case, the default value is 0 (main chart window). The most of the properties do not require a subwindow number. /// ///The value of double type. /// public double ChartGetDouble(long chartId, EnumChartPropertyDouble propId, int subWindow = 0) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "PropId", (int)propId }, { "SubWindow", subWindow } }; return SendCommand(ExecutorHandle, MtCommandType.ChartGetDouble, cmdParams); } /// ///Returns the value of a corresponding property of the specified chart. Chart property must be of datetime, int or bool type. /// ///Chart ID. 0 means the current chart. ///Chart property ID. This value can be one of the ENUM_CHART_PROPERTY_INTEGER values. ///Number of the chart subwindow. For the first case, the default value is 0 (main chart window). The most of the properties do not require a subwindow number. /// ///The value of long type. /// public long ChartGetInteger(long chartId, EnumChartPropertyInteger propId, int subWindow = 0) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "PropId", (int)propId }, { "SubWindow", subWindow } }; return SendCommand(ExecutorHandle, MtCommandType.ChartGetInteger, cmdParams); } /// ///Returns the value of a corresponding property of the specified chart. Chart property must be of string type. /// ///Chart ID. 0 means the current chart. ///Chart property ID. This value can be one of the ENUM_CHART_PROPERTY_STRING values. /// ///The value of string type. /// public string? ChartGetString(long chartId, EnumChartPropertyString propId) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "PropId", (int)propId } }; return SendCommand(ExecutorHandle, MtCommandType.ChartGetString, cmdParams); } /// ///Performs shift of the specified chart by the specified number of bars relative to the specified position in the chart. /// ///Chart ID. 0 means the current chart. ///Chart position to perform a shift. Can be one of the ENUM_CHART_POSITION values. ///Number of bars to shift the chart. Positive value means the right shift (to the end of chart), negative value means the left shift (to the beginning of chart). The zero shift can be used to navigate to the beginning or end of chart. /// ///Returns true if successful, otherwise returns false. /// public bool ChartNavigate(long chartId, int position, int shift = 0) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "Position", position }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.ChartNavigate, cmdParams); } /// ///Performs shift of the specified chart by the specified number of bars relative to the specified position in the chart. /// ///Chart ID. 0 means the current chart. ///Number of the chart subwindow. 0 denotes the main chart subwindow. ///The short name of the indicator which is set in the INDICATOR_SHORTNAME property with the IndicatorSetString() function. To get the short name of an indicator use the ChartIndicatorName() function. /// ///Returns true if the command has been added to chart queue, otherwise false. /// public bool ChartIndicatorDelete(long chartId, int subWindow, string indicatorShortname) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "SubWindow", subWindow }, { "IndicatorShortname", indicatorShortname } }; return SendCommand(ExecutorHandle, MtCommandType.ChartIndicatorDelete, cmdParams); } /// ///Returns the short name of the indicator by the number in the indicators list on the specified chart window. /// ///Chart ID. 0 means the current chart. ///Number of the chart subwindow. 0 denotes the main chart subwindow. ///the index of the indicator in the list of indicators. The numeration of indicators start with zero, i.e. the first indicator in the list has the 0 index. To obtain the number of indicators in the list use the ChartIndicatorsTotal() function. /// ///The short name of the indicator which is set in the INDICATOR_SHORTNAME property with the IndicatorSetString() function. /// public string? ChartIndicatorName(long chartId, int subWindow, int index) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "SubWindow", subWindow }, { "Index", index } }; return SendCommand(ExecutorHandle, MtCommandType.ChartIndicatorName, cmdParams); } /// ///Returns the number of all indicators applied to the specified chart window. /// ///Chart ID. 0 means the current chart. ///Number of the chart subwindow. 0 denotes the main chart subwindow. /// ///The number of indicators in the specified chart window. /// public int ChartIndicatorsTotal(long chartId, int subWindow) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "SubWindow", subWindow } }; return SendCommand(ExecutorHandle, MtCommandType.ChartIndicatorsTotal, cmdParams); } /// ///Returns the number (index) of the chart subwindow the Expert Advisor or script has been dropped to. 0 means the main chart window. /// public int ChartWindowOnDropped() { return SendCommand(ExecutorHandle, MtCommandType.ChartWindowOnDropped); } /// ///Returns the price coordinate corresponding to the chart point the Expert Advisor or script has been dropped to. /// public double ChartPriceOnDropped() { return SendCommand(ExecutorHandle, MtCommandType.ChartPriceOnDropped); } /// ///Returns the time coordinate corresponding to the chart point the Expert Advisor or script has been dropped to. /// public DateTime ChartTimeOnDropped() { var res = SendCommand(ExecutorHandle, MtCommandType.ChartTimeOnDropped); return MtApiTimeConverter.ConvertFromMtTime(res); } /// ///Returns the X coordinate of the chart point the Expert Advisor or script has been dropped to. /// public int ChartXOnDropped() { return SendCommand(ExecutorHandle, MtCommandType.ChartXOnDropped); } /// ///Returns the Y coordinateof the chart point the Expert Advisor or script has been dropped to. /// public int ChartYOnDropped() { return SendCommand(ExecutorHandle, MtCommandType.ChartYOnDropped); } /// ///Changes the symbol and period of the specified chart. The function is asynchronous, i.e. it sends the command and does not wait for its execution completion. /// ///Chart ID. 0 means the current chart. ///Chart symbol. NULL value means the current chart symbol (Expert Advisor is attached to) ///Chart period (timeframe). Can be one of the ENUM_TIMEFRAMES values. 0 means the current chart period. /// ///Returns true if the command has been added to chart queue, otherwise false. /// public bool ChartSetSymbolPeriod(long chartId, string symbol, ENUM_TIMEFRAMES period) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "Symbol", symbol }, { "Period", period } }; return SendCommand(ExecutorHandle, MtCommandType.ChartSetSymbolPeriod, cmdParams); } /// ///Saves current chart screen shot as a GIF, PNG or BMP file depending on specified extension. /// ///Chart ID. 0 means the current chart. ///Screenshot file name. Cannot exceed 63 characters. Screenshot files are placed in the \Files directory. ///Screenshot width in pixels. ///Screenshot height in pixels. ///Output mode of a narrow screenshot. /// ///Returns true if the command has been added to chart queue, otherwise false. /// public bool ChartScreenShot(long chartId, string filename, int width, int height, EnumAlignMode alignMode = EnumAlignMode.ALIGN_RIGHT) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "Filename", filename }, { "Width", width }, { "Height", height }, { "AlignMode", (int)alignMode } }; return SendCommand(ExecutorHandle, MtCommandType.ChartScreenShot, cmdParams); } /// ///Returns the amount of bars visible on the chart. /// /// ///The amount of bars visible on the chart. /// public int WindowBarsPerChart() { return SendCommand(ExecutorHandle, MtCommandType.WindowBarsPerChart); } /// ///Returns the name of the executed Expert Advisor, script, custom indicator, or library. /// /// ///The name of the executed Expert Advisor, script, custom indicator, or library, depending on the MQL4 program, from which this function has been called. /// public string? WindowExpertName() { return SendCommand(ExecutorHandle, MtCommandType.WindowExpertName); } /// ///Returns the window index containing this specified indicator. /// ///Indicator short name. /// ///If indicator with name was found, the function returns the window index containing this specified indicator, otherwise it returns -1. /// public int WindowFind(string name) { Dictionary cmdParams = new() { { "Name", name } }; return SendCommand(ExecutorHandle, MtCommandType.WindowFind, cmdParams); } /// ///Returns index of the first visible bar in the current chart window. /// /// ///Index of the first visible bar number in the current chart window. /// public int WindowFirstVisibleBar() { return SendCommand(ExecutorHandle, MtCommandType.WindowFirstVisibleBar); } /// ///Returns the system handle of the chart window. /// ///Symbol. ///Timeframe. It can be any of Timeframe enumeration values. 0 means the current chart timeframe. /// ///Returns the system handle of the chart window. If the chart of symbol and timeframe has not been opened by the moment of function calling, 0 will be returned. /// public int WindowHandle(string symbol, int timeframe) { Dictionary cmdParams = new() { { "Symbol", symbol }, { "Timeframe", timeframe } }; return SendCommand(ExecutorHandle, MtCommandType.WindowHandle, cmdParams); } /// ///Returns the visibility flag of the chart subwindow. /// ///Subwindow index. /// ///Returns true if the chart subwindow is visible, otherwise returns false. The chart subwindow can be hidden due to the visibility properties of the indicator placed in it. /// public bool WindowIsVisible(int index) { Dictionary cmdParams = new() { { "Index", index } }; return SendCommand(ExecutorHandle, MtCommandType.WindowIsVisible, cmdParams); } /// ///Returns the window index where Expert Advisor, custom indicator or script was dropped. /// /// ///The window index where Expert Advisor, custom indicator or script was dropped. This value is valid if the Expert Advisor, custom indicator or script was dropped by mouse. /// public int WindowOnDropped() { return SendCommand(ExecutorHandle, MtCommandType.WindowOnDropped); } /// ///Returns the maximal value of the vertical scale of the specified subwindow of the current chart. /// ///Chart subwindow index (0 - main chart window). /// ///The maximal value of the vertical scale of the specified subwindow of the current chart. /// public int WindowPriceMax(int index = 0) { Dictionary cmdParams = new() { { "Index", index } }; return SendCommand(ExecutorHandle, MtCommandType.WindowPriceMax, cmdParams); } /// ///Returns the minimal value of the vertical scale of the specified subwindow of the current chart. /// ///Chart subwindow index (0 - main chart window). /// ///The minimal value of the vertical scale of the specified subwindow of the current chart. /// public int WindowPriceMin(int index = 0) { Dictionary cmdParams = new() { { "Index", index } }; return SendCommand(ExecutorHandle, MtCommandType.WindowPriceMin, cmdParams); } /// ///Returns the price of the chart point where Expert Advisor or script was dropped. /// /// ///The price of the chart point where Expert Advisor or script was dropped. This value is only valid if the expert or script was dropped by mouse. /// public double WindowPriceOnDropped() { return SendCommand(ExecutorHandle, MtCommandType.WindowPriceOnDropped); } /// ///Redraws the current chart forcedly. /// /// ///Redraws the current chart forcedly. It is normally used after the objects properties have been changed. /// public void WindowRedraw() { SendCommand(ExecutorHandle, MtCommandType.WindowRedraw); } /// ///Saves current chart screen shot as a GIF file. /// ///Screen shot file name. Screenshot is saved to \Files folder. ///Screen shot width in pixels. ///Screen shot height in pixels. ///Index of the first visible bar in the screen shot. If 0 value is set, the current first visible bar will be shot. If no value or negative value has been set, the end-of-chart screen shot will be produced, indent being taken into consideration. ///Horizontal chart scale for screen shot. Can be in the range from 0 to 5. If no value or negative value has been set, the current chart scale will be used. /// Chart displaying mode. It can take the following values: CHART_BAR (0 is a sequence of bars), CHART_CANDLE (1 is a sequence of candlesticks), CHART_LINE (2 is a close prices line). If no value or negative value has been set, the chart will be shown in its current mode. /// ///Returns true if succeed, otherwise false. /// public bool WindowScreenShot(string filename, int sizeX, int sizeY, int startBar = -1, int chartScale = -1, int chartMode = -1) { Dictionary cmdParams = new() { { "Filename", filename }, { "SizeX", sizeX }, { "SizeY", sizeY }, { "StartBar", startBar }, { "ChartScale", chartScale }, { "ChartMode", chartMode } }; return SendCommand(ExecutorHandle, MtCommandType.WindowScreenShot, cmdParams); } /// ///Returns the time of the chart point where Expert Advisor or script was dropped. /// /// ///The time value of the chart point where expert or script was dropped. This value is only valid if the expert or script was dropped by mouse. /// public DateTime WindowTimeOnDropped() { var res = SendCommand(ExecutorHandle, MtCommandType.WindowTimeOnDropped); return MtApiTimeConverter.ConvertFromMtTime(res); } /// ///Returns total number of indicator windows on the chart. /// /// ///Total number of indicator windows on the chart (including main chart). /// public int WindowsTotal() { return SendCommand(ExecutorHandle, MtCommandType.WindowsTotal); } /// ///Returns the value at X axis in pixels for the chart window client area point at which the Expert Advisor or script was dropped. /// /// ///The value at X axis in pixels for the chart window client area point at which the expert or script was dropped. The value will be true only if the expert or script were moved with the mouse ("Drag'n'Drop") technique. /// public int WindowXOnDropped() { return SendCommand(ExecutorHandle, MtCommandType.WindowXOnDropped); } /// ///Returns the value at Y axis in pixels for the chart window client area point at which the Expert Advisor or script was dropped. /// /// ///Returns the value at Y axis in pixels for the chart window client area point at which the Expert Advisor or script was dropped. The value will be true only if the expert or script were moved with the mouse ("Drag'n'Drop") technique. /// public int WindowYOnDropped() { return SendCommand(ExecutorHandle, MtCommandType.WindowYOnDropped); } #endregion #region Object Functions /// ///The function creates an object with the specified name, type, and the initial coordinates in the specified chart subwindow of the specified chart. /// ///Chart identifier. 0 means the current chart. ///Name of the object. The name must be unique within a chart, including its subwindows. ///Object type. ///Number of the chart subwindow. 0 means the main chart window. ///The time coordinate of the first anchor point. ///The price coordinate of the first anchor point. ///The time coordinate of the second anchor point. ///The price coordinate of the second anchor point. ///The time coordinate of the third anchor point. ///The price coordinate of the third anchor point. /// ///Returns true or false depending on whether the object is created or not. /// public bool ObjectCreate(long chartId, string objectName, EnumObject objectType, int subWindow, DateTime? time1, double price1, DateTime? time2 = null, double? price2 = null, DateTime? time3 = null, double? price3 = null) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "ObjectName", objectName }, { "ObjectType", (int)objectType }, { "SubWindow", subWindow }, { "Time1", MtApiTimeConverter.ConvertToMtTime(time1) }, { "Price1", price1 }, { "Time2", time2 != null ? MtApiTimeConverter.ConvertToMtTime(time2.Value) : 0 }, { "Price2", price2 != null ? price2.Value : 0.0 }, { "Time3", time3 != null ? MtApiTimeConverter.ConvertToMtTime(time3.Value) : 0 }, { "Price3", price3 != null ? price3.Value : 0.0 } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectCreate, cmdParams); } /// ///The function returns the name of the corresponding object by its index in the objects list. /// ///Chart identifier. 0 means the current chart. ///Object index. This value must be greater or equal to 0 and less than ObjectsTotal(). ///Number of the chart window. Must be greater or equal to -1 (-1 mean all subwindows, 0 means the main chart window) and less than WindowsTotal(). ///Type of the object. The value can be one of the values of the EnumObject enumeration. EMPTY (-1) means all types. /// ///Name of the object is returned in case of success. /// public string? ObjectName(long chartId, int objectIndex, int subWindow = EMPTY, int objectType = EMPTY) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "ObjectIndex", objectIndex }, { "SubWindow", subWindow }, { "ObjectType", objectType } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectName, cmdParams); } /// ///The function removes the object with the specified name at the specified chart. /// ///Chart identifier. 0 means the current chart. ///Name of object to be deleted. /// ///Returns true if the removal was successful, otherwise returns false. /// public bool ObjectDelete(long chartId, string objectName) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "ObjectName", objectName } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectDelete, cmdParams); } /// ///The function removes the object with the specified name at the specified chart. /// ///Chart identifier. 0 means the current chart. ///Number of the chart window. Must be greater or equal to -1 (-1 mean all subwindows, 0 means the main chart window) and less than WindowsTotal(). ///Type of the object. The value can be one of the values of the EnumObject enumeration. EMPTY (-1) means all types. /// ///Returns true if the removal was successful, otherwise returns false. /// public int ObjectsDeleteAll(long chartId, int subWindow = EMPTY, int objectType = EMPTY) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "SubWindow", subWindow }, { "ObjectType", objectType } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectsDeleteAll, cmdParams); } /// ///The function searches for an object having the specified name. /// ///Chart identifier. 0 means the current chart. ///The name of the object to find. /// ///If successful the function returns the number of the subwindow (0 means the main window of the chart), in which the object is found. /// public int ObjectFind(long chartId, string objectName) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "ObjectName", objectName } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectFind, cmdParams); } /// ///The function returns the time value for the specified price value of the specified object. /// ///Chart identifier. 0 means the current chart. ///Name of the object. ///Price value. ///Line identifier. /// ///The time value for the specified price value of the specified object. /// public DateTime ObjectGetTimeByValue(long chartId, string objectName, double value, int lineId = 0) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "ObjectName", objectName }, { "Value", value }, { "LineId", lineId } }; var res = SendCommand(ExecutorHandle, MtCommandType.ObjectGetTimeByValue, cmdParams); return MtApiTimeConverter.ConvertFromMtTime(res); } /// ///The function returns the price value for the specified time value of the specified object. /// ///Chart identifier. 0 means the current chart. ///Name of the object. ///Time value. ///Line identifier. /// ///The price value for the specified time value of the specified object. /// public double ObjectGetValueByTime(long chartId, string objectName, DateTime? time, int lineId = 0) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "ObjectName", objectName }, { "Time", MtApiTimeConverter.ConvertToMtTime(time) }, { "LineId", lineId } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectGetValueByTime, cmdParams); } /// ///The function changes coordinates of the specified anchor point of the object at the specified chart /// ///Chart identifier. 0 means the current chart. ///Name of the object. ///Index of the anchor point. ///Time coordinate of the selected anchor point. ///Price coordinate of the selected anchor point. /// ///If successful, returns true, in case of failure returns false. /// public bool ObjectMove(long chartId, string objectName, int pointIndex, DateTime? time, double price) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "ObjectName", objectName }, { "PointIndex", pointIndex }, { "Time", MtApiTimeConverter.ConvertToMtTime(time) }, { "Price", price } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectMove, cmdParams); } /// ///The function changes coordinates of the specified anchor point of the object at the specified chart. /// ///Chart identifier. 0 means the current chart. ///Number of the chart subwindow. 0 means the main chart window, -1 means all the subwindows of the chart, including the main window. ///Type of the object. The value can be one of the values of the EnumObject enumeration. EMPTY(-1) means all types. /// ///The number of objects. /// public int ObjectsTotal(long chartId, int subWindow = EMPTY, int type = EMPTY) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "SubWindow", subWindow }, { "Type", type } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectsTotal, cmdParams); } /// ///The function returns the value of the corresponding object property. /// ///Chart identifier. 0 means the current chart. ///Name of the object. ///ID of the object property. The value can be one of the values of the EnumObjectPropertyDouble enumeration. ///Modifier of the specified property. For the first variant, the default modifier value is equal to 0. Most properties do not require a modifier. /// ///Value of the double type. /// public double ObjectGetDouble(long chartId, string objectName, EnumObjectPropertyDouble propId, int propModifier = 0) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "ObjectName", objectName }, { "PropId", (int)propId }, { "PropModifier", propModifier } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectGetDouble, cmdParams); } /// ///The function returns the value of the corresponding object property. The object property must be of the datetime, int, color, bool or char type. /// ///Chart identifier. 0 means the current chart. ///Name of the object. ///ID of the object property. The value can be one of the values of the EnumObjectPropertyDouble enumeration. ///Modifier of the specified property. For the first variant, the default modifier value is equal to 0. Most properties do not require a modifier. /// ///The long value. /// public long ObjectGetInteger(long chartId, string objectName, EnumObjectPropertyInteger propId, int propModifier = 0) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "ObjectName", objectName }, { "PropId", (int)propId }, { "PropModifier", propModifier } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectGetInteger, cmdParams); } /// ///The function returns the value of the corresponding object property. The object property must be of the string type. /// ///Chart identifier. 0 means the current chart. ///Name of the object. ///ID of the object property. The value can be one of the values of the EnumObjectPropertyString enumeration. ///Modifier of the specified property. For the first variant, the default modifier value is equal to 0. Most properties do not require a modifier. It denotes the number of the level in Fibonacci tools and in the graphical object Andrew's pitchfork. The numeration of levels starts from zero. /// ///String value. /// public string? ObjectGetString(long chartId, string objectName, EnumObjectPropertyString propId, int propModifier = 0) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "ObjectName", objectName }, { "PropId", (int)propId }, { "PropModifier", propModifier } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectGetString, cmdParams); } /// ///The function sets the value of the corresponding object property. The object property must be of the double type. /// ///Chart identifier. 0 means the current chart. ///Name of the object. ///ID of the object property. The value can be one of the values of the EnumObjectPropertyDouble enumeration. ///The value of the property. /// ///The function returns true only if the command to change properties of a graphical object has been sent to a chart successfully. /// public bool ObjectSetDouble(long chartId, string objectName, EnumObjectPropertyDouble propId, double propValue) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "ObjectName", objectName }, { "PropId", (int)propId }, { "PropValue", propValue } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectSetDouble, cmdParams); } /// ///The function sets the value of the corresponding object property. The object property must be of the double type. /// ///Chart identifier. 0 means the current chart. ///Name of the object. ///ID of the object property. The value can be one of the values of the EnumObjectPropertyDouble enumeration. ///Modifier of the specified property. It denotes the number of the level in Fibonacci tools and in the graphical object Andrew's pitchfork. The numeration of levels starts from zero. ///The value of the property. /// ///The function returns true only if the command to change properties of a graphical object has been sent to a chart successfully. /// public bool ObjectSetDouble(long chartId, string objectName, EnumObjectPropertyDouble propId, int propModifier, double propValue) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "ObjectName", objectName }, { "PropId", (int)propId }, { "PropModifier", propModifier }, { "PropValue", propValue } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectSetDouble, cmdParams); } /// ///The function sets the value of the corresponding object property. The object property must be of the int type. /// ///Chart identifier. 0 means the current chart. ///Name of the object. ///ID of the object property. The value can be one of the values of the EnumObjectPropertyInteger enumeration. ///The value of the property. /// ///The function returns true only if the command to change properties of a graphical object has been sent to a chart successfully. Otherwise it returns false. /// public bool ObjectSetInteger(long chartId, string objectName, EnumObjectPropertyInteger propId, long propValue) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "ObjectName", objectName }, { "PropId", (int)propId }, { "PropValue", propValue } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectSetInteger, cmdParams); } /// ///The function sets the value of the corresponding object property. The object property must be of the int type. /// ///Chart identifier. 0 means the current chart. ///Name of the object. ///ID of the object property. The value can be one of the values of the EnumObjectPropertyInteger enumeration. ///Modifier of the specified property. It denotes the number of the level in Fibonacci tools and in the graphical object Andrew's pitchfork. The numeration of levels starts from zero. ///The value of the property. /// ///The function returns true only if the command to change properties of a graphical object has been sent to a chart successfully. Otherwise it returns false. /// public bool ObjectSetInteger(long chartId, string objectName, EnumObjectPropertyInteger propId, int propModifier, long propValue) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "ObjectName", objectName }, { "PropId", (int)propId }, { "PropModifier", propModifier }, { "PropValue", propValue } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectSetInteger, cmdParams); } /// ///The function sets the value of the corresponding object property. The object property must be of the string type. /// ///Chart identifier. 0 means the current chart. ///Name of the object. ///ID of the object property. The value can be one of the values of the EnumObjectPropertyString enumeration. ///The value of the property. /// ///The function returns true only if the command to change properties of a graphical object has been sent to a chart successfully. Otherwise it returns false. /// public bool ObjectSetString(long chartId, string objectName, EnumObjectPropertyString propId, string propValue) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "ObjectName", objectName }, { "PropId", (int)propId }, { "PropValue", propValue } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectSetString, cmdParams); } /// ///The function sets the value of the corresponding object property. The object property must be of the string type. /// ///Chart identifier. 0 means the current chart. ///Name of the object. ///ID of the object property. The value can be one of the values of the EnumObjectPropertyString enumeration. ///Modifier of the specified property. It denotes the number of the level in Fibonacci tools and in the graphical object Andrew's pitchfork. The numeration of levels starts from zero. ///The value of the property. /// ///The function returns true only if the command to change properties of a graphical object has been sent to a chart successfully. Otherwise it returns false. /// public bool ObjectSetString(long chartId, string objectName, EnumObjectPropertyString propId, int propModifier, string propValue) { Dictionary cmdParams = new() { { "ChartId", chartId }, { "ObjectName", objectName }, { "PropId", (int)propId }, { "PropModifier", propModifier }, { "PropValue", propValue } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectSetString, cmdParams); } /// ///The function sets the font for displaying the text using drawing methods and returns the result of that operation. Arial font with the size -120 (12 pt) is used by default. /// ///Font name in the system or the name of the resource containing the font or the path to font file on the disk. ///The font size that can be set using positive and negative values. In case of positive values, the size of a displayed text does not depend on the operating system's font size settings. In case of negative values, the value is set in tenths of a point and the text size depends on the operating system settings ("standard scale" or "large scale"). See the Note below for more information about the differences between the modes. ///Combination of flags describing font style. ///Text's horizontal inclination to X axis, the unit of measurement is 0.1 degrees. It means that orientation=450 stands for inclination equal to 45 degrees. /// ///Returns true if the current font is successfully installed, otherwise false. /// public bool TextSetFont(string name, int size, FlagFontStyle flags = 0, int orientation = 0) { Dictionary cmdParams = new() { { "Name", name }, { "Size", size }, { "Flags", flags }, { "Orientation", orientation } }; return SendCommand(ExecutorHandle, MtCommandType.TextSetFont, cmdParams); } /// ///Returns the object description. /// ///Object name. /// ///Object description. For objects of OBJ_TEXT and OBJ_LABEL types, the text drawn by these objects will be returned. /// public string? ObjectDescription(string objectName) { Dictionary cmdParams = new() { { "ObjectName", objectName } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectDescription, cmdParams); } /// ///Returns the level description of a Fibonacci object. /// ///Fibonacci object name. ///Index of the Fibonacci level (0-31). /// ///The level description of a Fibonacci object. /// public string? ObjectGetFiboDescription(string objectName, int index) { Dictionary cmdParams = new() { { "ObjectName", objectName }, { "Index", index } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectGetFiboDescription, cmdParams); } /// ///The function calculates and returns bar index (shift related to the current bar) for the given price. /// ///Object name. ///Price value. /// ///The function calculates and returns bar index (shift related to the current bar) for the given price. The bar index is calculated by the first and second coordinates using a linear equation. Applied to trendlines and similar objects. /// public int ObjectGetShiftByValue(string objectName, double value) { Dictionary cmdParams = new() { { "ObjectName", objectName }, { "Value", value } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectGetShiftByValue, cmdParams); } /// ///The function calculates and returns the price value for the specified bar (shift related to the current bar). /// ///Object name. ///Bar index. /// ///The function calculates and returns the price value for the specified bar (shift related to the current bar). The price value is calculated by the first and second coordinates using a linear equation. Applied to trendlines and similar objects. /// public double ObjectGetValueByShift(string objectName, int shift) { Dictionary cmdParams = new() { { "ObjectName", objectName }, { "Shift", shift } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectGetValueByShift, cmdParams); } /// ///Changes the value of the specified object property. /// ///Object name. ///Object property index. It can be any of object properties enumeration values. ///New value of the given property. /// ///If the function succeeds, the returned value will be true, otherwise it returns false. /// public bool ObjectSet(string objectName, int index, double value) { Dictionary cmdParams = new() { { "ObjectName", objectName }, { "Index", index }, { "Value", value } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectSet, cmdParams); } /// ///The function sets a new description to a level of a Fibonacci object. /// ///Object name. ///Index of the Fibonacci level (0-31). ///New description of the level. /// ///The function returns true if successful, otherwise false. /// public bool ObjectSetFiboDescription(string objectName, int index, string text) { Dictionary cmdParams = new() { { "ObjectName", objectName }, { "Index", index }, { "Text", text } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectSetFiboDescription, cmdParams); } /// ///The function changes the object description. /// ///Object name. ///A text describing the object. ///Font size in points. ///Font name. ///Font color. /// ///Changes the object description. If the function succeeds, the returned value will be true, otherwise false. /// public bool ObjectSetText(string objectName, string text, int fontSize = 0, string? fontName = null, Color? textColor = null) { Dictionary cmdParams = new() { { "ObjectName", objectName }, { "Text", text }, { "FontSize", fontSize }, { "FontName", fontName ?? string.Empty }, { "TextColor", MtApiColorConverter.ConvertToMtColor(textColor) } }; return SendCommand(ExecutorHandle, MtCommandType.ObjectSetText, cmdParams); } /// ///The function returns the object type value. /// ///Object name. /// ///The function returns the object type value. /// public EnumObject ObjectType(string objectName) { Dictionary cmdParams = new() { { "ObjectName", objectName }, }; return (EnumObject)SendCommand(ExecutorHandle, MtCommandType.ObjectType, cmdParams); } #endregion #region Backtesting functions public void UnlockTicks() { SendCommand(ExecutorHandle, MtCommandType.UnlockTicks); } #endregion #region Private Methods private MtRpcClient? Client { get { lock(_locker) { return _client; } } } private async Task Connect(string host, int port) { lock (_locker) { if (_connectionState == MtConnectionState.Connected || _connectionState == MtConnectionState.Connecting) { return; } _connectionState = MtConnectionState.Connecting; } string message = $"Connecting to {host}:{port}"; ConnectionStateChanged?.Invoke(this, new MtConnectionEventArgs(MtConnectionState.Connecting, message)); var client = new MtRpcClient(host, port, new RpcClientLogger(Log)); client.ExpertAdded += Client_ExpertAdded; client.ExpertRemoved += Client_ExpertRemoved; client.MtEventReceived += Client_MtEventReceived; client.ConnectionFailed += Client_OnConnectionFailed; client.Disconnected += Client_Disconnected; try { await client.Connect(); Log.Info($"Connected to {host}:{port}"); var experts = client.RequestExpertsList(); if (experts == null || experts.Count == 0) { var errorMessage = "Failed to load expert list"; Log.Error(errorMessage); client.Disconnect(); ConnectionStateChanged?.Invoke(this, new MtConnectionEventArgs(MtConnectionState.Failed, errorMessage)); throw new Exception($"Connection to {host}:{port} failed. Error: {errorMessage}"); } // Load quotes Dictionary quotes = []; foreach (var handle in experts) { var quote = GetQuote(client, handle); if (quote != null) quotes[handle] = quote; } lock (_locker) { _client = client; _experts = experts; _quotes = quotes; if (_executorHandle == 0) _executorHandle = (_experts.Count > 0) ? _experts.ElementAt(0) : 0; _connectionState = MtConnectionState.Connected; } if (IsTesting()) { BacktestingReady(); } ConnectionStateChanged?.Invoke(this, new MtConnectionEventArgs(MtConnectionState.Connected, $"Connected to {host}:{port}")); QuoteList?.Invoke(this, new(quotes.Values.ToList())); } catch (Exception e) { Log.Warn($"Failed connection to {host}:{port}. {e.Message}"); lock (_locker) { _connectionState = MtConnectionState.Failed; } ConnectionStateChanged?.Invoke(this, new MtConnectionEventArgs(MtConnectionState.Failed, e.Message)); } } private void Disconnect(bool failed) { var state = failed ? MtConnectionState.Failed : MtConnectionState.Disconnected; var message = failed ? "Connection Failed" : "Disconnected"; MtRpcClient? client; lock (_locker) { if (_connectionState == MtConnectionState.Disconnected || _connectionState == MtConnectionState.Failed) return; _connectionState = state; client = _client; _client = null; _quotes.Clear(); _experts.Clear(); _executorHandle = 0; } client?.Disconnect(); Log.Info(message); ConnectionStateChanged?.Invoke(this, new MtConnectionEventArgs(state, message)); } private T? SendCommand(int expertHandle, MtCommandType commandType, object? payload = null) { return SendCommand(Client, expertHandle, commandType, payload); } private T? SendCommand(MtRpcClient? client, int expertHandle, MtCommandType commandType, object? payload = null) { if (client == null) { Log.Warn("SendCommand: No connection"); throw new Exception("No connection"); } var payloadJson = payload == null ? string.Empty : JsonConvert.SerializeObject(payload); Log.Debug($"SendCommand: sending '{payloadJson}' ..."); var responseJson = client.SendCommand(expertHandle, (int)commandType, payloadJson); Log.Debug($"SendCommand: received response JSON [{responseJson}]"); if (string.IsNullOrEmpty(responseJson)) { Log.Warn("SendCommand: Response JSON from MetaTrader is null or empty"); throw new MtExecutionException(MtErrorCode.MtApiCustomError, "Response from MetaTrader is null"); } var response = JsonConvert.DeserializeObject>(responseJson); if (response == null) { Log.Warn("SendCommand: Failed to deserialize response from JSON"); throw new MtExecutionException(MtErrorCode.MtApiCustomError, "Response from MetaTrader is null"); } if (response.ErrorCode != 0) { Log.Warn($"SendCommand: ErrorCode = {response.ErrorCode}. {response.ErrorMessage}"); throw new MtExecutionException((MtErrorCode)response.ErrorCode, response.ErrorMessage); } return (response.Value == null) ? default : response.Value; } private void Client_MtEventReceived(object? sender, MtEventArgs e) { Task.Run(() => _mtEventHandlers[(MtEventTypes)e.EventType](e.ExpertHandle, e.Payload)); } private void Client_ExpertAdded(object? sender, MtExpertEventArgs e) { Task.Run(() => ProcessExpertAdded(e.Expert)); } private void Client_ExpertRemoved(object? sender, MtExpertEventArgs e) { Task.Run(() => ProcessExpertRemoved(e.Expert)); } private void Client_OnConnectionFailed(object? sender, EventArgs e) { Log.Info("Received connection failed"); Disconnect(true); } private void Client_Disconnected(object? sender, EventArgs e) { Log.Info("Received normal disconnection"); Disconnect(false); } private void ReceivedOnTickEvent(int expertHandle, string payload) { var e = JsonConvert.DeserializeObject(payload); if (e == null || string.IsNullOrEmpty(e.Instrument) || e.Tick == null) return; QuoteUpdated?.Invoke(this, e.Instrument, e.Tick.Bid, e.Tick.Ask); MtQuote quote = new() { Instrument = e.Instrument, Bid = e.Tick.Bid, Ask = e.Tick.Ask, ExpertHandle = expertHandle }; QuoteUpdate?.Invoke(this, new MtQuoteEventArgs(quote)); } private void ReceivedOnLastTimeBarEvent(int expertHandle, string payload) { var e = JsonConvert.DeserializeObject(payload); if (e == null || string.IsNullOrEmpty(e.Symbol)) return; OnLastTimeBar?.Invoke(this, new TimeBarArgs(expertHandle, e)); } private void ReceiveOnChartEvent(int expertHandle, string payload) { var e = JsonConvert.DeserializeObject(payload); if (e == null) return; OnChartEvent?.Invoke(this, new ChartEventArgs(expertHandle, e)); } private void ReceivedOnLockTicksEvent(int expertHandle, string payload) { var e = JsonConvert.DeserializeObject(payload); if (e == null || string.IsNullOrEmpty(e.Instrument)) return; OnLockTicks?.Invoke(this, new MtLockTicksEventArgs(expertHandle, e.Instrument)); } private void ProcessExpertAdded(int handle) { Log.Debug($"ProcessExpertAdded: {handle}"); bool added; lock (_locker) { added = _experts.Add(handle); if (_executorHandle == 0) _executorHandle = (_experts.Count > 0) ? _experts.ElementAt(0) : 0; } if (added) { var quote = GetQuote(Client, handle); if (quote != null) { lock (_locker) { _quotes[handle] = quote; } QuoteAdded?.Invoke(this, new MtQuoteEventArgs(quote)); } else Log.Warn($"ProcessExpertAdded: failed to get quote for expert {handle}"); } else Log.Warn($"ProcessExpertAdded: expert handle {handle} is already exist"); } private void ProcessExpertRemoved(int handle) { Log.Debug($"ProcessExpertRemoved: {handle}"); MtQuote? quote = null; lock (_locker) { _experts.Remove(handle); if (_quotes.TryGetValue(handle, out quote)) _quotes.Remove(handle); if (_executorHandle == handle) _executorHandle = (_experts.Count > 0) ? _experts.ElementAt(0) : 0; } if (quote != null) QuoteRemoved?.Invoke(this, new MtQuoteEventArgs(quote)); } private MtQuote? GetQuote(MtRpcClient? client, int expertHandle) { Log.Debug($"GetQuote: expertHandle = {expertHandle}"); var q = SendCommand(client, expertHandle, MtCommandType.GetQuote); if (q == null || string.IsNullOrEmpty(q.Instrument) || q.Tick == null) return null; MtQuote quote = new() { Instrument = q.Instrument, Bid = q.Tick.Bid, Ask = q.Tick.Ask, ExpertHandle = expertHandle, }; return quote; } private void BacktestingReady() { SendCommand(ExecutorHandle, MtCommandType.BacktestingReady); } #endregion #region Events public event MtApiQuoteHandler? QuoteUpdated; public event EventHandler? QuoteUpdate; public event EventHandler? QuoteAdded; public event EventHandler? QuoteRemoved; public event EventHandler? ConnectionStateChanged; public event EventHandler? OnLastTimeBar; public event EventHandler? OnChartEvent; public event EventHandler? OnLockTicks; public event EventHandler? QuoteList; #endregion } internal enum ParametersType { Int = 0, Double = 1, String = 2, Boolean = 3 } internal class RpcClientLogger(IMtLogger logger) : IRpcLogger { public void Debug(string message) { logger_.Debug(message); } public void Error(string message) { logger_.Debug(message); } public void Info(string message) { logger_.Debug(message); } public void Warn(string message) { logger_.Debug(message); } private readonly IMtLogger logger_ = logger; } internal class StubMtLogger : IMtLogger { public void Debug(object message) { } public void Error(object message) { } public void Fatal(object message) { } public void Info(object message) { } public void Warn(object message) { } } }