Compare commits

..

14 Commits

Author SHA1 Message Date
vdemydiuk be8a17c0fd Issue #88: Activate execute commands in tester mode (MT5) 2018-02-19 19:21:29 +02:00
vdemydiuk 5c6751de9b Issue #90: Added time functions: TimeCurrent, TimeTradeServer, TimeLocal, TimeGMT 2018-02-19 18:48:31 +02:00
vdemydiuk 83776f8b7a Minor refactoring to remote redundant code 2018-02-19 17:12:26 +02:00
vdemydiuk f1c1df1e00 Issue #89: Changed function OrderCheck to use json request/response 2018-02-19 17:02:19 +02:00
vdemydiuk d6640300f5 Issue #89: Changed function PositionOpen to use json request/response 2018-02-19 15:54:03 +02:00
vdemydiuk c9c188f697 Minor refactoring to remove code syle warnings 2018-02-19 13:37:43 +02:00
vdemydiuk 3a4f561836 Issue #87: Added event QuoteUpdate to MtApi5Client (MT5) for compatibility with MATLAB 2018-02-19 11:49:52 +02:00
vdemydiuk bdb30edee3 Issue #82: Responsed moved to Request folder 2018-02-19 11:27:07 +02:00
vdemydiuk 29f501b055 Issue #82: Refactored request responses (MtAp5). Added iCustom functions with string and boolean parameters. Added button iCustom in test application (MT5). 2018-02-19 11:07:37 +02:00
vdemydiuk 521d7ea2c0 Issue #82: Disabled debug mode in MtApi5.ex5. Updated test client to send order with values Expiration and Comment 2018-02-18 20:24:27 +02:00
DW 0e5bb40a6f Issue #82: Refactored MQL5 expert to use json in function OrderSend 2018-02-17 00:10:10 +02:00
vdemydiuk 14079dc3c1 Issue #82: Added stub class OrderSendRequest 2018-02-15 20:32:22 +02:00
vdemydiuk 3600a86971 MtApiService version 1.0.29. Added log wrapper class MtLog 2018-02-15 17:37:08 +02:00
vdemydiuk 83e62fbff7 Started version 1.0.16 (MT5) 2018-02-15 17:33:02 +02:00
31 changed files with 799 additions and 285 deletions
+52
View File
@@ -8,6 +8,50 @@ using log4net.Repository.Hierarchy;
namespace MTApiService
{
public class MtLog
{
#region ctor
internal MtLog(Type type)
{
_log = LogManager.GetLogger(type);
}
#endregion
#region Public
public void Debug(object message)
{
_log.Debug(message);
}
public void Error(object message)
{
_log.Error(message);
}
public void Fatal(object message)
{
_log.Fatal(message);
}
public void Info(object message)
{
_log.Info(message);
}
public void Warn(object message)
{
_log.Warn(message);
}
#endregion
#region Private
private readonly ILog _log;
#endregion
}
public class LogConfigurator
{
private const string LogFileNameExtension = "txt";
@@ -48,5 +92,13 @@ namespace MTApiService
#endif
hierarchy.Configured = true;
}
public static MtLog GetLogger(Type type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
return new MtLog(type);
}
}
}
+2 -2
View File
@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.28.0")]
[assembly: AssemblyFileVersion("1.0.28.0")]
[assembly: AssemblyVersion("1.0.29.0")]
[assembly: AssemblyFileVersion("1.0.29.0")]
+3 -1
View File
@@ -1,4 +1,6 @@
namespace MtApi
// ReSharper disable InconsistentNaming
namespace MtApi
{
public enum ENUM_TERMINAL_INFO_STRING
{
+2 -1
View File
@@ -1,4 +1,5 @@
using System;
// ReSharper disable InconsistentNaming
using System;
namespace MtApi5
{
+2 -1
View File
@@ -1,4 +1,5 @@
using System;
// ReSharper disable InconsistentNaming
using System;
namespace MtApi5
{
+16 -9
View File
@@ -1,15 +1,17 @@
namespace MtApi5
// ReSharper disable InconsistentNaming
namespace MtApi5
{
public class MqlTradeCheckResult
{
public uint Retcode { get; private set; } // Reply code
public double Balance { get; private set; } // Balance after the execution of the deal
public double Equity { get; private set; } // Equity after the execution of the deal
public double Profit { get; private set; } // Floating profit
public double Margin { get; private set; } // Margin requirements
public double Margin_free { get; private set; } // Free margin
public double Margin_level { get; private set; } // Margin level
public string Comment { get; private set; } // Comment to the reply code (description of the error)
public uint Retcode { get; } // Reply code
public double Balance { get; } // Balance after the execution of the deal
public double Equity { get; } // Equity after the execution of the deal
public double Profit { get; } // Floating profit
public double Margin { get; } // Margin requirements
public double Margin_free { get; } // Free margin
public double Margin_level { get; } // Margin level
public string Comment { get; } // Comment to the reply code (description of the error)
public MqlTradeCheckResult(uint retcode
, double balance
@@ -29,5 +31,10 @@
Margin_level = margin_level;
Comment = comment;
}
public override string ToString()
{
return $"Retcode={Retcode}; Comment={Comment}; Balance={Balance}; Equity={Equity}; Profit={Profit}; Margin={Margin}; Margin_free={Margin_free}; Margin_level={Margin_level}";
}
}
}
+9 -1
View File
@@ -1,4 +1,5 @@
using System;
// ReSharper disable InconsistentNaming
using System;
namespace MtApi5
{
@@ -21,5 +22,12 @@ namespace MtApi5
public string Comment { get; set; } // Order comment
public ulong Position { get; set; } // Position ticket
public ulong PositionBy { get; set; } // The ticket of an opposite position
public int MtExpiration => Mt5TimeConverter.ConvertToMtTime(Expiration);
public override string ToString()
{
return $"{Symbol}|{Volume}|{Price}|{Volume}|{Action}";
}
}
}
+26 -11
View File
@@ -1,4 +1,6 @@
namespace MtApi5
// ReSharper disable InconsistentNaming
namespace MtApi5
{
public class MqlTradeResult
{
@@ -15,19 +17,32 @@
Request_id = request_id;
}
public uint Retcode { get; private set; } // Operation return code
public ulong Deal { get; private set; } // Deal ticket, if it is performed
public ulong Order { get; private set; } // Order ticket, if it is placed
public double Volume { get; private set; } // Deal volume, confirmed by broker
public double Price { get; private set; } // Deal price, confirmed by broker
public double Bid { get; private set; } // Current Bid price
public double Ask { get; private set; } // Current Ask price
public string Comment { get; private set; } // Broker comment to operation (by default it is filled by the operation description)
public uint Request_id { get; private set; } // Request ID set by the terminal during the dispatch
internal MqlTradeResult(MqlTradeResult o)
{
Retcode = o.Retcode;
Deal = o.Deal;
Order = o.Order;
Volume = o.Volume;
Price = o.Price;
Bid = o.Bid;
Ask = o.Ask;
Comment = o.Comment;
Request_id = o.Request_id;
}
public uint Retcode { get; } // Operation return code
public ulong Deal { get; } // Deal ticket, if it is performed
public ulong Order { get; } // Order ticket, if it is placed
public double Volume { get; } // Deal volume, confirmed by broker
public double Price { get; } // Deal price, confirmed by broker
public double Bid { get; } // Current Bid price
public double Ask { get; } // Current Ask price
public string Comment { get; } // Broker comment to operation (by default it is filled by the operation description)
public uint Request_id { get; } // Request ID set by the terminal during the dispatch
public override string ToString()
{
return $"Retcode={Retcode}; Deal={Deal}; Order={Order}; Volume={Volume}; Price={Price}; Bid={Bid}; Ask={Ask}; Comment={Comment}; Request_id={Request_id}";
return $"Retcode={Retcode}; Comment={Comment}; Deal={Deal}; Order={Order}; Volume={Volume}; Price={Price}; Bid={Bid}; Ask={Ask}; Request_id={Request_id}";
}
}
}
+12 -5
View File
@@ -1,14 +1,15 @@
namespace MtApi5
// ReSharper disable InconsistentNaming
namespace MtApi5
{
internal enum Mt5CommandType
{
//NoCommand = 0
//trade operations
OrderSend = 1,
//OrderSend = 1,
OrderCalcMargin = 2,
OrderCalcProfit = 3,
OrderCheck = 4,
//OrderCheck = 4,
//OrderSendAsync = 5,
PositionsTotal = 6,
PositionGetSymbol = 7,
@@ -100,7 +101,7 @@
//CTrade
PositionClose = 64,
PositionOpen = 65,
PositionOpenWithResult = 1065,
//PositionOpenWithResult = 1065,
//Backtesting
BacktestingReady = 66,
@@ -170,6 +171,12 @@
iTriX = 123,
iWPR = 124,
iVIDyA = 125,
iVolumes = 126
iVolumes = 126,
//Date and Time
TimeCurrent = 127,
TimeTradeServer = 128,
TimeLocal = 129,
TimeGMT = 130
}
}
+2 -2
View File
@@ -4,8 +4,8 @@ namespace MtApi5
{
public class Mt5ConnectionEventArgs: EventArgs
{
public Mt5ConnectionState Status { get; private set; }
public string ConnectionMessage { get; private set; }
public Mt5ConnectionState Status { get; }
public string ConnectionMessage { get; }
public Mt5ConnectionEventArgs(Mt5ConnectionState status, string message)
{
+3 -1
View File
@@ -1,4 +1,6 @@
namespace MtApi5
// ReSharper disable InconsistentNaming
namespace MtApi5
{
// Chart Constants:
+4 -9
View File
@@ -1,15 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MtApi5
namespace MtApi5
{
public class Mt5Quote
{
public string Instrument { get; private set; }
public double Bid { get; private set; }
public double Ask { get; private set; }
public string Instrument { get; }
public double Bid { get; }
public double Ask { get; }
public Mt5Quote(string instrument, double bid, double ask)
{
+1 -4
View File
@@ -1,13 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MtApi5
{
public class Mt5QuoteEventArgs: EventArgs
{
public Mt5Quote Quote { get; private set; }
public Mt5Quote Quote { get; }
public Mt5QuoteEventArgs(Mt5Quote quote)
{
+7 -12
View File
@@ -1,32 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MtApi5
{
class Mt5TimeConverter
internal class Mt5TimeConverter
{
public static DateTime ConvertFromMtTime(int time)
{
DateTime tmpTime = new DateTime(1970, 1, 1);
var tmpTime = new DateTime(1970, 1, 1);
return new DateTime(tmpTime.Ticks + (time * 0x989680L));
}
public static DateTime ConvertFromMtTime(long time)
{
DateTime tmpTime = new DateTime(1970, 1, 1);
var tmpTime = new DateTime(1970, 1, 1);
return new DateTime(tmpTime.Ticks + (time * 0x989680L));
}
public static int ConvertToMtTime(DateTime time)
{
int result = 0;
if (time != DateTime.MinValue)
{
DateTime tmpTime = new DateTime(1970, 1, 1);
result = (int)((time.Ticks - tmpTime.Ticks) / 0x989680L);
}
var result = 0;
if (time == DateTime.MinValue) return result;
var tmpTime = new DateTime(1970, 1, 1);
result = (int)((time.Ticks - tmpTime.Ticks) / 0x989680L);
return result;
}
}
+7 -3
View File
@@ -68,11 +68,14 @@
<Compile Include="Mt5Quote.cs" />
<Compile Include="Requests\CopyTicksRequest.cs" />
<Compile Include="Requests\ICustomRequest.cs" />
<Compile Include="Requests\OrderCheckRequest.cs" />
<Compile Include="Requests\OrderCheckResult.cs" />
<Compile Include="Requests\OrderSendRequest.cs" />
<Compile Include="Requests\PositionOpenRequest.cs" />
<Compile Include="Requests\RequestBase.cs" />
<Compile Include="Requests\RequestType.cs" />
<Compile Include="Responses\CopyTicksResponse.cs" />
<Compile Include="Responses\ICustomResponse.cs" />
<Compile Include="Responses\ResponseBase.cs" />
<Compile Include="Requests\OrderSendResult.cs" />
<Compile Include="Requests\Response.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MTApiService\MTApiService.csproj">
@@ -83,6 +86,7 @@
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
+165 -36
View File
@@ -1,11 +1,11 @@
using System;
// ReSharper disable InconsistentNaming
using System;
using System.Collections.Generic;
using System.Linq;
using MTApiService;
using System.Collections;
using System.ServiceModel;
using MtApi5.Requests;
using MtApi5.Responses;
using Newtonsoft.Json;
using System.Threading.Tasks;
@@ -32,9 +32,11 @@ namespace MtApi5
#region Private Fields
private static readonly MtLog Log = LogConfigurator.GetLogger(typeof(MtApi5Client));
private MtClient _client;
private readonly object _locker = new object();
private volatile bool _isBacktestingMode = false;
private volatile bool _isBacktestingMode;
private Mt5ConnectionState _connectionState = Mt5ConnectionState.Disconnected;
private int _executorHandle;
#endregion
@@ -78,8 +80,8 @@ namespace MtApi5
public IEnumerable<Mt5Quote> GetQuotes()
{
var client = Client;
var quotes = client != null ? client.GetQuotes() : null;
return quotes?.Select(q => q.Parse());
var quotes = client?.GetQuotes();
return quotes?.Select(q => q.Convert());
}
///<summary>
@@ -104,17 +106,22 @@ namespace MtApi5
/// </returns>
public bool OrderSend(MqlTradeRequest request, out MqlTradeResult result)
{
Log.Debug($"OrderSend: request = {request}");
if (request == null)
{
Log.Warn("OrderSend: request is not defined!");
result = null;
return false;
}
var commandParameters = request.ToArrayList();
var response = SendRequest<OrderSendResult>(new OrderSendRequest
{
TradeRequest = request
});
var strResult = SendCommand<string>(Mt5CommandType.OrderSend, commandParameters);
return strResult.ParseResult(ParamSeparator, out result);
result = response?.TradeResult;
return response != null && response.RetVal;
}
///<summary>
@@ -180,17 +187,22 @@ namespace MtApi5
/// </returns>
public bool OrderCheck(MqlTradeRequest request, out MqlTradeCheckResult result)
{
Log.Debug($"OrderCheck: request = {request}");
if (request == null)
{
Log.Warn("OrderCheck: request is not defined!");
result = null;
return false;
}
var commandParameters = request.ToArrayList();
var response = SendRequest<OrderCheckResult>(new OrderCheckRequest
{
TradeRequest = request
});
var strResult = SendCommand<string>(Mt5CommandType.OrderSend, commandParameters);
return strResult.ParseResult(ParamSeparator, out result);
result = response?.TradeCheckResult;
return response != null && response.RetVal;
}
///<summary>
@@ -533,13 +545,25 @@ namespace MtApi5
/// <param name="sl">Stop Loss price</param>
/// <param name="tp">Take Profit price</param>
/// <param name="comment">comment</param>
/// <param name="result">output result</param>
/// <returns>true - successful check of the basic structures, otherwise - false.</returns>
public bool PositionOpen(string symbol, ENUM_ORDER_TYPE orderType, double volume, double price, double sl, double tp, string comment , out MqlTradeResult result)
{
var commandParameters = new ArrayList { symbol, (int)orderType, volume, price, sl, tp, comment };
Log.Debug($"PositionOpen: symbol = {symbol}, orderType = {orderType}, volume = {volume}, price = {price}, sl = {sl}, tp = {tp}, comment = {comment}");
var strResult = SendCommand<string>(Mt5CommandType.PositionOpenWithResult, commandParameters);
return strResult.ParseResult(ParamSeparator, out result);
var response = SendRequest<OrderSendResult>(new PositionOpenRequest
{
Symbol = symbol,
OrderType = orderType,
Volume = volume,
Price = price,
Sl = sl,
Tp = tp,
Comment = comment
});
result = response?.TradeResult;
return response != null && response.RetVal;
}
#endregion
@@ -711,7 +735,7 @@ namespace MtApi5
return ratesArray?.Length ?? 0;
}
///<summary>
///Gets history data of MqlRates structure of a specified symbol-period in specified quantity into the ratesArray array. The elements ordering of the copied data is from present to the past, i.e., starting position of 0 means the current bar.
///</summary>
@@ -1229,11 +1253,14 @@ namespace MtApi5
///<see href="https://www.mql5.com/en/docs/series/copyticks"/>
public List<MqlTick> CopyTicks(string symbolName, CopyTicksFlag flags = CopyTicksFlag.All, ulong from = 0, uint count = 0)
{
var response = SendRequest<CopyTicksResponse>(new CopyTicksRequest
var response = SendRequest<List<MqlTick>>(new CopyTicksRequest
{
SymbolName = symbolName, Flags = (int)flags, From = from, Count = count
SymbolName = symbolName,
Flags = (int)flags,
From = from,
Count = count
});
return response.Ticks;
return response;
}
#endregion
@@ -1640,8 +1667,6 @@ namespace MtApi5
#region Technical Indicators
#endregion //Technical Indicators
///<summary>
///The function creates Accelerator Oscillator in a global cache of the client terminal and returns its handle.
///</summary>
@@ -2169,7 +2194,8 @@ namespace MtApi5
///<param name="parameters">input-parameters of a custom indicator. If there is no parameters specified, then default values will be used.</param>
public int iCustom(string symbol, ENUM_TIMEFRAMES period, string name, double[] parameters)
{
var response = SendRequest<ICustomResponse>(new ICustomRequest
Log.Debug("iCustom: called.");
var response = SendRequest<int>(new ICustomRequest
{
Symbol = symbol,
Timeframe = (int)period,
@@ -2177,7 +2203,8 @@ namespace MtApi5
Params = new ArrayList(parameters),
ParamsType = ICustomRequest.ParametersType.Double
});
return response?.Value ?? 0;
Log.Debug($"iCustom: response = {response}.");
return response;
}
///<summary>
@@ -2189,7 +2216,8 @@ namespace MtApi5
///<param name="parameters">input-parameters of a custom indicator. If there is no parameters specified, then default values will be used.</param>
public int iCustom(string symbol, ENUM_TIMEFRAMES period, string name, int[] parameters)
{
var response = SendRequest<ICustomResponse>(new ICustomRequest
Log.Debug("iCustom: called.");
var response = SendRequest<int>(new ICustomRequest
{
Symbol = symbol,
Timeframe = (int)period,
@@ -2197,9 +2225,104 @@ namespace MtApi5
Params = new ArrayList(parameters),
ParamsType = ICustomRequest.ParametersType.Int
});
return response?.Value ?? 0;
Log.Debug($"iCustom: response = {response}.");
return response;
}
///<summary>
///The function returns the handle of the Volumes indicator.
///</summary>
///<param name="symbol">The symbol name of the security, the data of which should be used to calculate the indicator.</param>
///<param name="period">The value of the period can be one of the ENUM_TIMEFRAMES enumeration values, 0 means the current timeframe.</param>
///<param name="name">The name of the custom indicator, with path relative to the root directory of indicators (MQL5/Indicators/). If an indicator is located in a subdirectory, for example, in MQL5/Indicators/Examples, its name must be specified like: "Examples\\indicator_name" (it is necessary to use a double slash instead of the single slash as a separator).</param>
///<param name="parameters">input-parameters of a custom indicator. If there is no parameters specified, then default values will be used.</param>
public int iCustom(string symbol, ENUM_TIMEFRAMES period, string name, string[] parameters)
{
Log.Debug("iCustom: called.");
var response = SendRequest<int>(new ICustomRequest
{
Symbol = symbol,
Timeframe = (int)period,
Name = name,
Params = new ArrayList(parameters),
ParamsType = ICustomRequest.ParametersType.Int
});
Log.Debug($"iCustom: response = {response}.");
return response;
}
///<summary>
///The function returns the handle of the Volumes indicator.
///</summary>
///<param name="symbol">The symbol name of the security, the data of which should be used to calculate the indicator.</param>
///<param name="period">The value of the period can be one of the ENUM_TIMEFRAMES enumeration values, 0 means the current timeframe.</param>
///<param name="name">The name of the custom indicator, with path relative to the root directory of indicators (MQL5/Indicators/). If an indicator is located in a subdirectory, for example, in MQL5/Indicators/Examples, its name must be specified like: "Examples\\indicator_name" (it is necessary to use a double slash instead of the single slash as a separator).</param>
///<param name="parameters">input-parameters of a custom indicator. If there is no parameters specified, then default values will be used.</param>
public int iCustom(string symbol, ENUM_TIMEFRAMES period, string name, bool[] parameters)
{
Log.Debug("iCustom: called.");
var response = SendRequest<int>(new ICustomRequest
{
Symbol = symbol,
Timeframe = (int)period,
Name = name,
Params = new ArrayList(parameters),
ParamsType = ICustomRequest.ParametersType.Int
});
Log.Debug($"iCustom: response = {response}.");
return response;
}
#endregion //Technical Indicators
#region Date and Time
///<summary>
///Returns the last known server time, time of the last quote receipt for one of the symbols selected in the "Market Watch" window.
///</summary>
public DateTime TimeCurrent()
{
Log.Debug("TimeCurrent: called.");
var response = SendCommand<long>(Mt5CommandType.TimeCurrent, null);
Log.Debug($"TimeCurrent: response = {response}.");
return Mt5TimeConverter.ConvertFromMtTime(response);
}
///<summary>
///Returns the calculated current time of the trade server. Unlike TimeCurrent(), the calculation of the time value is performed in the client terminal and depends on the time settings on your computer.
///</summary>
public DateTime TimeTradeServer()
{
Log.Debug("TimeTradeServer: called.");
var response = SendCommand<long>(Mt5CommandType.TimeTradeServer, null);
Log.Debug($"TimeTradeServer: response = {response}.");
return Mt5TimeConverter.ConvertFromMtTime(response);
}
///<summary>
///Returns the local time of a computer, where the client terminal is running.
///</summary>
public DateTime TimeLocal()
{
Log.Debug("TimeLocal: called.");
var response = SendCommand<long>(Mt5CommandType.TimeLocal, null);
Log.Debug($"TimeLocal: response = {response}.");
return Mt5TimeConverter.ConvertFromMtTime(response);
}
///<summary>
///Returns the GMT, which is calculated taking into account the DST switch by the local time on the computer where the client terminal is running.
///</summary>
public DateTime TimeGMT()
{
Log.Debug("TimeGMT: called.");
var response = SendCommand<long>(Mt5CommandType.TimeGMT, null);
Log.Debug($"TimeGMT: response = {response}.");
return Mt5TimeConverter.ConvertFromMtTime(response);
}
#endregion //Date and Time
#endregion // Public Methods
#region Properties
@@ -2241,6 +2364,7 @@ namespace MtApi5
#region Events
public event QuoteHandler QuoteUpdated;
public event EventHandler<Mt5QuoteEventArgs> QuoteUpdate;
public event EventHandler<Mt5QuoteEventArgs> QuoteAdded;
public event EventHandler<Mt5QuoteEventArgs> QuoteRemoved;
public event EventHandler<Mt5ConnectionEventArgs> ConnectionStateChanged;
@@ -2388,10 +2512,10 @@ namespace MtApi5
}
var responseValue = response.GetValue();
return responseValue != null ? (T)responseValue : default(T);
return (T) responseValue;
}
private T SendRequest<T>(RequestBase request) where T : ResponseBase, new()
private T SendRequest<T>(RequestBase request)
{
if (request == null)
return default(T);
@@ -2410,22 +2534,21 @@ namespace MtApi5
throw new ExecutionException(ErrorCode.ErrCustom, "Response from MetaTrader is null");
}
var response = JsonConvert.DeserializeObject<T>(res);
var response = JsonConvert.DeserializeObject<Response<T>>(res);
if (response.ErrorCode != 0)
{
throw new ExecutionException((ErrorCode)response.ErrorCode, response.ErrorMessage);
}
return response;
return response.Value;
}
private void _client_QuoteUpdated(MtQuote quote)
{
if (quote != null)
{
QuoteUpdated?.Invoke(this, quote.Instrument, quote.Bid, quote.Ask);
}
if (quote == null) return;
QuoteUpdate?.Invoke(this, new Mt5QuoteEventArgs(new Mt5Quote(quote.Instrument, quote.Bid, quote.Ask)));
QuoteUpdated?.Invoke(this, quote.Instrument, quote.Bid, quote.Ask);
}
private void _client_ServerDisconnected(object sender, EventArgs e)
@@ -2440,12 +2563,18 @@ namespace MtApi5
private void _client_QuoteRemoved(MtQuote quote)
{
QuoteRemoved?.Invoke(this, new Mt5QuoteEventArgs(quote.Parse()));
if (quote != null)
{
QuoteRemoved?.Invoke(this, new Mt5QuoteEventArgs(new Mt5Quote(quote.Instrument, quote.Bid, quote.Ask)));
}
}
private void _client_QuoteAdded(MtQuote quote)
{
QuoteAdded?.Invoke(this, new Mt5QuoteEventArgs(quote.Parse()));
if (quote != null)
{
QuoteAdded?.Invoke(this, new Mt5QuoteEventArgs(new Mt5Quote(quote.Instrument, quote.Bid, quote.Ask)));
}
}
private void OnConnected()
+20 -74
View File
@@ -6,84 +6,18 @@ namespace MtApi5
{
internal static class MtConverters
{
private static readonly MtLog Log = LogConfigurator.GetLogger(typeof(MtConverters));
#region Values Converters
public static Mt5Quote Parse(this MtQuote quote)
public static Mt5Quote Convert(this MtQuote quote)
{
return (quote != null) ? new Mt5Quote(quote.Instrument, quote.Bid, quote.Ask) : null;
}
public static bool ParseResult(this string inputString, char separator, out MqlTradeResult result)
{
var retVal = false;
result = null;
if (string.IsNullOrEmpty(inputString) == false)
{
var values = inputString.Split(separator);
if (values.Length == 10)
{
try
{
retVal = int.Parse(values[0]) != 0;
var retcode = uint.Parse(values[1]);
var deal = ulong.Parse(values[2]);
var order = ulong.Parse(values[3]);
var volume = double.Parse(values[4]);
var price = double.Parse(values[5]);
var bid = double.Parse(values[6]);
var ask = double.Parse(values[7]);
var comment = values[8];
var requestId = uint.Parse(values[9]);
result = new MqlTradeResult(retcode, deal, order, volume, price, bid, ask, comment, requestId);
}
catch (Exception)
{
}
}
}
return retVal;
}
public static bool ParseResult(this string inputString, char separator, out MqlTradeCheckResult result)
{
var retVal = false;
result = null;
if (string.IsNullOrEmpty(inputString) == false)
{
var values = inputString.Split(separator);
if (values.Length == 10)
{
try
{
retVal = int.Parse(values[0]) != 0;
var retcode = uint.Parse(values[1]);
var balance = double.Parse(values[2]);
var equity = double.Parse(values[3]);
var profit = double.Parse(values[4]);
var margin = double.Parse(values[5]);
var marginFree = double.Parse(values[6]);
var marginLevel = double.Parse(values[7]);
var comment = values[8];
result = new MqlTradeCheckResult(retcode, balance, equity, profit, margin, marginFree, marginLevel, comment);
}
catch (Exception)
{
retVal = false;
}
}
}
return retVal;
return quote != null ? new Mt5Quote(quote.Instrument, quote.Bid, quote.Ask) : null;
}
public static bool ParseResult(this string inputString, char separator, out double result)
{
Log.Debug($"ParseResult: inputString = {inputString}, separator = {separator}");
var retVal = false;
result = 0;
@@ -98,18 +32,25 @@ namespace MtApi5
result = double.Parse(values[1]);
}
catch (Exception)
catch (Exception ex)
{
retVal = false;
Log.Error($"ParseResult: {ex.Message}");
}
}
}
else
{
Log.Warn("ParseResult: input srting is null or empty!");
}
return retVal;
}
public static bool ParseResult(this string inputString, char separator, out DateTime from, out DateTime to)
{
Log.Debug($"ParseResult: inputString = {inputString}, separator = {separator}");
var retVal = false;
from = new DateTime();
@@ -130,12 +71,17 @@ namespace MtApi5
var iTo= int.Parse(values[2]);
to = Mt5TimeConverter.ConvertFromMtTime(iTo);
}
catch (Exception)
catch (Exception ex)
{
retVal = false;
Log.Error($"ParseResult: {ex.Message}");
}
}
}
else
{
Log.Warn("ParseResult: input srting is null or empty!");
}
return retVal;
}
+2 -2
View File
@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.15")]
[assembly: AssemblyFileVersion("1.0.15")]
[assembly: AssemblyVersion("1.0.16")]
[assembly: AssemblyFileVersion("1.0.16")]
+10
View File
@@ -0,0 +1,10 @@
namespace MtApi5.Requests
{
internal class OrderCheckRequest: RequestBase
{
public override RequestType RequestType => RequestType.OrderCheck;
public MqlTradeRequest TradeRequest { get; set; }
}
}
+8
View File
@@ -0,0 +1,8 @@
namespace MtApi5.Requests
{
public class OrderCheckResult
{
public bool RetVal { get; set; }
public MqlTradeCheckResult TradeCheckResult { get; set; }
}
}
+9
View File
@@ -0,0 +1,9 @@
namespace MtApi5.Requests
{
internal class OrderSendRequest: RequestBase
{
public override RequestType RequestType => RequestType.OrderSend;
public MqlTradeRequest TradeRequest { get; set; }
}
}
+8
View File
@@ -0,0 +1,8 @@
namespace MtApi5.Requests
{
internal class OrderSendResult
{
public bool RetVal { get; set; }
public MqlTradeResult TradeResult { get; set; }
}
}
+15
View File
@@ -0,0 +1,15 @@
namespace MtApi5.Requests
{
internal class PositionOpenRequest: RequestBase
{
public override RequestType RequestType => RequestType.PositionOpen;
public string Symbol { get; set; }
public ENUM_ORDER_TYPE OrderType { get; set; }
public double Volume { get; set; }
public double Price { get; set; }
public double Sl { get; set; }
public double Tp { get; set; }
public string Comment { get; set; }
}
}
+7 -2
View File
@@ -1,9 +1,14 @@
namespace MtApi5.Requests
// ReSharper disable InconsistentNaming
namespace MtApi5.Requests
{
internal enum RequestType
{
Unknown = 0,
CopyTicks = 1,
iCustom = 2
iCustom = 2,
OrderSend = 3,
PositionOpen = 4,
OrderCheck = 5
}
}
+4 -2
View File
@@ -1,8 +1,10 @@
namespace MtApi5.Responses
namespace MtApi5.Requests
{
internal class ResponseBase
internal class Response<T>
{
public int ErrorCode { get; set; }
public string ErrorMessage { get; set; }
public T Value { get; set; }
}
}
-9
View File
@@ -1,9 +0,0 @@
using System.Collections.Generic;
namespace MtApi5.Responses
{
internal class CopyTicksResponse: ResponseBase
{
public List<MqlTick> Ticks { get; set; }
}
}
-7
View File
@@ -1,7 +0,0 @@
namespace MtApi5.Responses
{
internal class ICustomResponse: ResponseBase
{
public int Value { get; set; }
}
}
+51 -55
View File
@@ -4,7 +4,7 @@
xmlns:mtapi5="clr-namespace:MtApi5;assembly=MtApi5"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:mtApi5TestClient="clr-namespace:MtApi5TestClient"
Title="MainWindow" Height="700" Width="650"
Title="MainWindow" Height="700" Width="700"
Closing="Window_Closing">
<Window.Resources>
<DataTemplate x:Key="ConnectionTextBlockTemplate" DataType="{x:Type mtapi5:Mt5ConnectionState}">
@@ -100,58 +100,33 @@
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Expander ExpandDirection="Right" IsExpanded="True"
Grid.Row="0" Grid.Column="0" Margin="5">
<Expander.Header>
<TextBlock Text="Connection" RenderTransformOrigin="0.5,0.5" Margin="0,0,0,0" Width="Auto">
<TextBlock.LayoutTransform>
<TransformGroup>
<ScaleTransform ScaleX="1" ScaleY="1"/>
<SkewTransform AngleX="0" AngleY="0"/>
<RotateTransform Angle="-90"/>
<TranslateTransform X="0" Y="0"/>
</TransformGroup>
</TextBlock.LayoutTransform>
<TextBlock.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="1" ScaleY="1"/>
<SkewTransform AngleX="0" AngleY="0"/>
<RotateTransform Angle="0"/>
<TranslateTransform X="0" Y="0"/>
</TransformGroup>
</TextBlock.RenderTransform>
</TextBlock>
</Expander.Header>
<Expander.Content>
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="150"/>
</Grid.ColumnDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="150"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="Host"/>
<TextBox Grid.Row="0" Grid.Column="1"
<TextBlock Grid.Row="0" Grid.Column="0" Text="Host"/>
<TextBox Grid.Row="0" Grid.Column="1"
Margin="5,0,0,0"
Text="{Binding Host, UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Grid.Row="1" Grid.Column="0" Text="Port"/>
<TextBox Grid.Row="1" Grid.Column="1"
<TextBlock Grid.Row="1" Grid.Column="0" Text="Port"/>
<TextBox Grid.Row="1" Grid.Column="1"
Margin="5,0,0,0"
Text="{Binding Port, UpdateSourceTrigger=PropertyChanged}"/>
<StackPanel Grid.Row="2" Grid.ColumnSpan="2" Margin="5" Orientation="Horizontal">
<Button Content="Connect" Width="70" Command="{Binding ConnectCommand}" />
<Button Margin="5,0,0,0" Width="70" Content="Disconnect" Command="{Binding DisconnectCommand}" />
</StackPanel>
</Grid>
</Expander.Content>
</Expander>
<StackPanel Grid.Row="2" Grid.ColumnSpan="2" Margin="5" Orientation="Horizontal">
<Button Content="Connect" Width="70" Command="{Binding ConnectCommand}" />
<Button Margin="5,0,0,0" Width="70" Content="Disconnect" Command="{Binding DisconnectCommand}" />
</StackPanel>
</Grid>
<ListView Grid.Row="0" Grid.Column="1"
ItemsSource="{Binding Quotes}"
@@ -247,20 +222,26 @@
SelectedItem="{Binding TradeRequest.Type_time}" Margin="5,0,0,0"/>
<TextBlock Grid.Column="2" Grid.Row="6" Text="Expiration" Margin="10,0,0,0"/>
<TextBox Grid.Column="3" Grid.Row="6" Text="{Binding TradeRequest}" Margin="5,0,0,0"/>
<TextBox Grid.Column="3" Grid.Row="6" Text="{Binding TradeRequest.Expiration}" Margin="5,0,0,0"/>
<TextBlock Grid.Column="0" Grid.Row="7" Text="Comment"/>
<TextBox Grid.Column="1" Grid.Row="7" Grid.ColumnSpan="3" Text="{Binding TradeRequest}" Margin="5,0,0,0"/>
<TextBox Grid.Column="1" Grid.Row="7" Grid.ColumnSpan="3" Text="{Binding TradeRequest.Comment}" Margin="5,0,0,0"/>
</Grid>
</Expander>
<StackPanel Grid.Row="1" Orientation="Vertical">
<Button Content="OrderSend" Command="{Binding OrderSendCommand}" Width="100" Height="25" HorizontalAlignment="Left" Margin="4"/>
<Button Content="HistoryDealGetDouble" Command="{Binding HistoryDealGetDoubleCommand}" Height="25" HorizontalAlignment="Left" Margin="4"/>
<Button Content="HistoryDealGetInteger" Command="{Binding HistoryDealGetIntegerCommand}" Height="25" HorizontalAlignment="Left" Margin="4"/>
<Button Content="HistoryDealGetString" Command="{Binding HistoryDealGetStringCommand}" Height="25" HorizontalAlignment="Left" Margin="4"/>
<Button Content="HistoryOrderGetInteger" Command="{Binding HistoryOrderGetIntegerCommand}" Height="25" HorizontalAlignment="Left" Margin="4"/>
<Button Content="HistoryDealMethods" Command="{Binding HistoryDealMethodsCommand}" Height="25" HorizontalAlignment="Left" Margin="4"/>
<StackPanel Orientation="Horizontal">
<Button Content="OrderSend" Command="{Binding OrderSendCommand}" Width="100" Height="25" HorizontalAlignment="Left" Margin="4"/>
<Button Content="OrderCheck" Command="{Binding OrderCheckCommand}" Width="100" Height="25" HorizontalAlignment="Left" Margin="4"/>
</StackPanel>
<WrapPanel>
<Button Content="HistoryDealGetDouble" Command="{Binding HistoryDealGetDoubleCommand}" Height="25" HorizontalAlignment="Left" Margin="4"/>
<Button Content="HistoryDealGetInteger" Command="{Binding HistoryDealGetIntegerCommand}" Height="25" HorizontalAlignment="Left" Margin="4"/>
<Button Content="HistoryDealGetString" Command="{Binding HistoryDealGetStringCommand}" Height="25" HorizontalAlignment="Left" Margin="4"/>
<Button Content="HistoryOrderGetInteger" Command="{Binding HistoryOrderGetIntegerCommand}" Height="25" HorizontalAlignment="Left" Margin="4"/>
<Button Content="HistoryDealMethods" Command="{Binding HistoryDealMethodsCommand}" Height="25" HorizontalAlignment="Left" Margin="4"/>
</WrapPanel>
</StackPanel>
</Grid>
@@ -402,10 +383,25 @@
<Button Command="{Binding PositionOpenCommand}" Content="PositionOpen" Margin="2"/>
</WrapPanel>
</TabItem>
<TabItem Header="Indicators">
<WrapPanel VerticalAlignment="Top" Margin="5">
<Button Command="{Binding iCustomCommand}" Content="iCustom" Margin="2"/>
</WrapPanel>
</TabItem>
<TabItem Header="Time and Date">
<WrapPanel VerticalAlignment="Top" Margin="5">
<Button Command="{Binding TimeCurrentCommand}" Content="TimeCurrent" Margin="2"/>
<Button Command="{Binding TimeTradeServerCommand}" Content="TimeTradeServer" Margin="2"/>
<Button Command="{Binding TimeLocalCommand}" Content="TimeLocal" Margin="2"/>
<Button Command="{Binding TimeGMTCommand}" Content="TimeGMT" Margin="2"/>
</WrapPanel>
</TabItem>
</TabControl>
<Expander Grid.Row="2" Header="History" IsExpanded="True">
<ListBox mtApi5TestClient:ListBoxBehavior.ScrollOnNewItem="true" Height="200" ItemsSource="{Binding History}"/>
<Expander Grid.Row="2" Header="Console" IsExpanded="True">
<ListBox mtApi5TestClient:ListBoxBehavior.ScrollOnNewItem="true" Height="180" ItemsSource="{Binding History}"/>
</Expander>
<StatusBar Grid.Row="3">
+78 -25
View File
@@ -1,4 +1,5 @@
using System;
// ReSharper disable InconsistentNaming
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
@@ -16,6 +17,8 @@ namespace MtApi5TestClient
public DelegateCommand DisconnectCommand { get; private set; }
public DelegateCommand OrderSendCommand { get; private set; }
public DelegateCommand OrderCheckCommand { get; private set; }
public DelegateCommand HistoryOrderGetIntegerCommand { get; private set; }
public DelegateCommand HistoryDealGetDoubleCommand { get; private set; }
public DelegateCommand HistoryDealGetIntegerCommand { get; private set; }
@@ -55,6 +58,13 @@ namespace MtApi5TestClient
public DelegateCommand PositionOpenCommand { get; private set; }
public DelegateCommand PrintCommand { get; private set; }
public DelegateCommand iCustomCommand { get; private set; }
public DelegateCommand TimeCurrentCommand { get; private set; }
public DelegateCommand TimeTradeServerCommand { get; private set; }
public DelegateCommand TimeLocalCommand { get; private set; }
public DelegateCommand TimeGMTCommand { get; private set; }
#endregion
#region Properties
@@ -198,6 +208,8 @@ namespace MtApi5TestClient
DisconnectCommand = new DelegateCommand(ExecuteDisconnect, CanExecuteDisconnect);
OrderSendCommand = new DelegateCommand(ExecuteOrderSend);
OrderCheckCommand = new DelegateCommand(ExecuteOrderCheck);
HistoryOrderGetIntegerCommand = new DelegateCommand(ExecuteHistoryOrderGetInteger);
HistoryDealGetDoubleCommand = new DelegateCommand(ExecuteHistoryDealGetDouble);
HistoryDealGetIntegerCommand = new DelegateCommand(ExecuteHistoryDealGetInteger);
@@ -237,6 +249,13 @@ namespace MtApi5TestClient
PositionOpenCommand = new DelegateCommand(ExecutePositionOpen);
PrintCommand = new DelegateCommand(ExecutePrint);
iCustomCommand = new DelegateCommand(ExecuteICustom);
TimeCurrentCommand = new DelegateCommand(ExecuteTimeCurrent);
TimeTradeServerCommand = new DelegateCommand(ExecuteTimeTradeServer);
TimeLocalCommand = new DelegateCommand(ExecuteTimeLocal);
TimeGMTCommand = new DelegateCommand(ExecuteTimeGMT);
}
private bool CanExecuteConnect(object o)
@@ -269,15 +288,29 @@ namespace MtApi5TestClient
private async void ExecuteOrderSend(object o)
{
var request = TradeRequest.GetMqlTradeRequest();
MqlTradeResult result = null;
var retVal = await Execute(() =>
{
MqlTradeResult result;
var ok = _mtApiClient.OrderSend(request, out result);
return ok ? result : null;
return ok;
});
var message = retVal != null ? $"OrderSend successed. {MqlTradeResultToString(retVal)}" : "OrderSend failed.";
var message = retVal ? $"OrderSend: success. {result}" : $"OrderSend: fail. {result}";
AddLog(message);
}
private async void ExecuteOrderCheck(object obj)
{
var request = TradeRequest.GetMqlTradeRequest();
MqlTradeCheckResult result = null;
var retVal = await Execute(() =>
{
var ok = _mtApiClient.OrderCheck(request, out result);
return ok;
});
var message = retVal ? $"OrderCheck: success. {result}" : $"OrderCheck: fail. {result}";
AddLog(message);
}
@@ -325,15 +358,14 @@ namespace MtApi5TestClient
{
try
{
var posId = await Execute(() => _mtApiClient.PositionGetInteger(ENUM_POSITION_PROPERTY_INTEGER.POSITION_IDENTIFIER)); // posId = 7247951
var history = await Execute(() => _mtApiClient.HistorySelectByPosition(posId)); // history = true
var historyDealsTotal = await Execute(() => _mtApiClient.HistoryDealsTotal()); // historyDealsCount = 4
var histDealTicket = await Execute(() => _mtApiClient.HistoryDealGetTicket(0)); // histDealTicket = 6632442
var histDealPrice = await Execute(() => _mtApiClient.HistoryDealGetDouble(histDealTicket, ENUM_DEAL_PROPERTY_DOUBLE.DEAL_PRICE)); // Exception
var posId = await Execute(() => _mtApiClient.PositionGetInteger(ENUM_POSITION_PROPERTY_INTEGER.POSITION_IDENTIFIER));
var history = await Execute(() => _mtApiClient.HistorySelectByPosition(posId));
var historyDealsTotal = await Execute(() => _mtApiClient.HistoryDealsTotal());
var histDealTicket = await Execute(() => _mtApiClient.HistoryDealGetTicket(0));
var histDealPrice = await Execute(() => _mtApiClient.HistoryDealGetDouble(histDealTicket, ENUM_DEAL_PROPERTY_DOUBLE.DEAL_PRICE));
}
catch (Exception ex)
{
// ex.Messsage = "Service connection failed! Ошибка сериализации параметра http://tempuri.org/:command. Сообщение InnerException было \"Тип \"MtApi5.ENUM_DEAL_PROPERTY_DOUBLE\" с именем контракта данных \"ENUM_DEAL_PROPERTY_DOUBLE:http://schemas.datacontract.org/2004/07/MtApi5\" не ожидается. Попробуйте использовать DataContractResolver, если вы используете DataContractSerializer, или добавьте любые статически неизвестные типы в список известных типов - например, используя атрибут KnownTypeAttribute или путем их добавления в список известных типов, передаваемый в сериализатор.\". Подробнее см. InnerException."
AddLog(ex.Message);
return;
}
@@ -833,6 +865,41 @@ namespace MtApi5TestClient
AddLog($"Print: message print in MetaTrader - {retVal}");
}
private async void ExecuteICustom(object o)
{
const string symbol = "EURUSD";
const ENUM_TIMEFRAMES timeframe = ENUM_TIMEFRAMES.PERIOD_H1;
const string name = @"Examples\Custom Moving Average";
int[] parameters = { 0, 21, (int)ENUM_APPLIED_PRICE.PRICE_CLOSE };
var retVal = await Execute(() => _mtApiClient.iCustom(symbol, timeframe, name, parameters));
AddLog($"Custom Moving Average: result - {retVal}");
}
private async void ExecuteTimeCurrent(object o)
{
var retVal = await Execute(() => _mtApiClient.TimeCurrent());
AddLog($"TimeCurrent: {retVal}");
}
private async void ExecuteTimeTradeServer(object o)
{
var retVal = await Execute(() => _mtApiClient.TimeTradeServer());
AddLog($"TimeTradeServer: {retVal}");
}
private async void ExecuteTimeLocal(object o)
{
var retVal = await Execute(() => _mtApiClient.TimeLocal());
AddLog($"TimeLocal: {retVal}");
}
private async void ExecuteTimeGMT(object o)
{
var retVal = await Execute(() => _mtApiClient.TimeGMT());
AddLog($"TimeGMT: {retVal}");
}
private static void RunOnUiThread(Action action)
{
Application.Current?.Dispatcher.Invoke(action);
@@ -955,20 +1022,6 @@ namespace MtApi5TestClient
Quotes.Clear();
}
private static string MqlTradeResultToString(MqlTradeResult result)
{
return result != null ?
"Retcode = " + result.Retcode + ";"
+ " Comment = " + result.Comment + ";"
+ " Order = " + result.Order + ";"
+ " Volume = " + result.Volume + ";"
+ " Price = " + result.Price + ";"
+ " Deal = " + result.Deal + ";"
+ " Request_id = " + result.Request_id + ";"
+ " Bid = " + result.Bid + ";"
+ " Ask = " + result.Ask + ";" : string.Empty;
}
private void OnSelectedQuoteChanged()
{
if (SelectedQuote == null) return;
BIN
View File
Binary file not shown.
+274 -11
View File
@@ -74,6 +74,7 @@ void OnDeinit(const int reason)
void OnTick()
{
start();
if (IsTesting()) OnTimer();
}
int preinit()
@@ -94,9 +95,6 @@ bool IsDemo()
bool IsTesting()
{
bool isTesting = MQLInfoInteger(MQL_TESTER);
#ifdef __DEBUG_LOG__
PrintFormat("IsTesting: %s", isTesting ? "true" : "false");
#endif
return isTesting;
}
@@ -147,6 +145,7 @@ int init()
#ifdef __DEBUG_LOG__
PrintFormat("Expert Handle = %d", ExpertHandle);
PrintFormat("IsTesting: %s", IsTesting() ? "true" : "false");
#endif
//--- Backtesting mode
@@ -489,9 +488,9 @@ int executeCommand()
case 65: //PositionOpen
Execute_PositionOpen(false);
break;
case 1065: //PositionOpenWithResult
Execute_PositionOpen(true);
break;
// case 1065: //PositionOpenWithResult
// Execute_PositionOpen(true);
// break;
case 66: //BacktestingReady
Execute_BacktestingReady();
break;
@@ -665,6 +664,18 @@ int executeCommand()
case 126: //iVolumes
Execute_iVolumes();
break;
case 127: //TimeCurrent
Execute_TimeCurrent();
break;
case 128: //TimeTradeServer
Execute_TimeTradeServer();
break;
case 129: //TimeLocal
Execute_TimeLocal();
break;
case 130: //TimeGMT
Execute_TimeGMT();
break;
default:
Print("Unknown command type = ", commandType);
sendVoidResponse(ExpertHandle, _response_error);
@@ -3112,8 +3123,11 @@ void Execute_PositionOpen(bool isTradeResultRequired)
return;
}
PrintFormat("Execute_PositionOpen: symbol = %s, order_type = %d, volume = %f, price = %f, sl = %f, tp = %f, comment = %s",
symbol, order_type, volume, price, sl, tp, comment);
#ifdef __DEBUG_LOG__
PrintFormat("%s: symbol = %s, order_type = %d, volume = %f, price = %f, sl = %f, tp = %f, comment = %s",
__FUNCTION__, symbol, order_type, volume, price, sl, tp, comment);
#endif
CTrade trade;
bool ok = trade.PositionOpen(symbol, (ENUM_ORDER_TYPE)order_type, volume, price, sl, tp, comment);
@@ -5424,6 +5438,38 @@ void Execute_iVolumes()
PrintResponseError("iVolumes", _response_error);
}
}
void Execute_TimeCurrent()
{
if (!sendLongResponse(ExpertHandle, TimeCurrent(), _response_error))
{
PrintResponseError("TimeCurrent", _response_error);
}
}
void Execute_TimeTradeServer()
{
if (!sendLongResponse(ExpertHandle, TimeTradeServer(), _response_error))
{
PrintResponseError("TimeTradeServer", _response_error);
}
}
void Execute_TimeLocal()
{
if (!sendLongResponse(ExpertHandle, TimeLocal(), _response_error))
{
PrintResponseError("TimeLocal", _response_error);
}
}
void Execute_TimeGMT()
{
if (!sendLongResponse(ExpertHandle, TimeGMT(), _response_error))
{
PrintResponseError("TimeGMT", _response_error);
}
}
void PrintParamError(string paramName)
{
@@ -5562,7 +5608,7 @@ string OnRequest(string json)
if(jv == NULL)
{
PrintFormat("OnRequest [ERROR]: %d - %s", (string)parser.getErrorCode(), parser.getErrorMessage());
PrintFormat("%s [ERROR]: %d - %s", __FUNCTION__, (string)parser.getErrorCode(), parser.getErrorMessage());
}
else
{
@@ -5579,8 +5625,17 @@ string OnRequest(string json)
case 2: //iCustom
response = ExecuteRequest_iCustom(jo);
break;
case 3: //OrderSend
response = ExecuteRequest_OrderSend(jo);
break;
case 4: //PositionOpen
response = ExecuteRequest_PositionOpen(jo);
break;
case 5: //OrderCheck
response = ExecuteRequest_OrderCheck(jo);
break;
default:
PrintFormat("OnRequest [WARNING]: Unknown request type %d", requestType);
PrintFormat("%s [WARNING]: Unknown request type %d", __FUNCTION__, requestType);
response = CreateErrorResponse(-1, "Unknown request type");
break;
}
@@ -5664,7 +5719,7 @@ string ExecuteRequest_CopyTicks(JSONObject *jo)
jaTicks.put(i, Serialize(ticks[i]));
}
return CreateSuccessResponse("Ticks", jaTicks);;
return CreateSuccessResponse("Value", jaTicks);;
}
string ExecuteRequest_iCustom(JSONObject *jo)
@@ -5770,4 +5825,212 @@ int iCustomT(string symbol, ENUM_TIMEFRAMES timeframe, string name, T &p[], int
default:
return 0;
}
}
#define PRINT_MSG_AND_RETURN_VALUE(msg,value) PrintFormat("%s: %s",__FUNCTION__,msg);return value
#define CHECK_JSON_VALUE(jo, name_value, return_fail_result) if (jo.getValue(name_value) == NULL) { PRINT_MSG_AND_RETURN_VALUE(StringFormat("failed to get %s from JSON!", name_value), return_fail_result); }
bool JsonToMqlTradeRequest(JSONObject *jo, MqlTradeRequest& request)
{
//Action
CHECK_JSON_VALUE(jo, "Action", false);
request.action = (ENUM_TRADE_REQUEST_ACTIONS) jo.getInt("Action");
//Magic
CHECK_JSON_VALUE(jo, "Magic", false);
request.magic = jo.getLong("Magic");
//Order
CHECK_JSON_VALUE(jo, "Order", false);
request.order = jo.getLong("Magic");
//Symbol
CHECK_JSON_VALUE(jo, "Symbol", false);
StringInit(request.symbol, 100, 0);
request.symbol = jo.getString("Symbol");
//Volume
CHECK_JSON_VALUE(jo, "Volume", false);
request.volume = jo.getDouble("Volume");
//Price
CHECK_JSON_VALUE(jo, "Price", false);
request.price = jo.getDouble("Price");
//Stoplimit
CHECK_JSON_VALUE(jo, "Stoplimit", false);
request.stoplimit = jo.getDouble("Stoplimit");
//Sl
CHECK_JSON_VALUE(jo, "Sl", false);
request.sl = jo.getDouble("Sl");
//Tp
CHECK_JSON_VALUE(jo, "Tp", false);
request.tp = jo.getDouble("Tp");
//Deviation
CHECK_JSON_VALUE(jo, "Deviation", false);
request.deviation = jo.getLong("Deviation");
//Type
CHECK_JSON_VALUE(jo, "Type", false);
request.type = (ENUM_ORDER_TYPE)jo.getInt("Type");
//Type_filling
CHECK_JSON_VALUE(jo, "Type_filling", false);
request.type_filling = (ENUM_ORDER_TYPE_FILLING)jo.getInt("Type_filling");
//Type_time
CHECK_JSON_VALUE(jo, "Type_time", false);
request.type_time = (ENUM_ORDER_TYPE_TIME)jo.getInt("Type_time");
//MtExpiration
CHECK_JSON_VALUE(jo, "MtExpiration", false);
request.expiration = (datetime)jo.getInt("MtExpiration");
//Comment
if (jo.getValue("Comment") != NULL)
{
StringInit(request.comment, 1000, 0);
request.comment = jo.getString("Comment");
}
//Position
CHECK_JSON_VALUE(jo, "Position", false);
request.position = jo.getLong("Position");
//PositionBy
CHECK_JSON_VALUE(jo, "PositionBy", false);
request.position_by = jo.getLong("PositionBy");
return true;
}
JSONObject* MqlTradeResultToJson(MqlTradeResult& result)
{
JSONObject* jo = new JSONObject();
jo.put("Retcode", new JSONNumber(result.retcode));
jo.put("Deal", new JSONNumber(result.deal));
jo.put("Order", new JSONNumber(result.order));
jo.put("Volume", new JSONNumber(result.volume));
jo.put("Price", new JSONNumber(result.price));
jo.put("Bid", new JSONNumber(result.bid));
jo.put("Ask", new JSONNumber(result.ask));
jo.put("Comment", new JSONString(result.comment));
jo.put("Request_id", new JSONNumber(result.request_id));
return jo;
}
string ExecuteRequest_OrderSend(JSONObject *jo)
{
CHECK_JSON_VALUE(jo, "TradeRequest", CreateErrorResponse(-1, "Undefinded mandatory parameter TradeRequest"));
JSONObject* trade_request_jo = jo.getObject("TradeRequest");
MqlTradeRequest trade_request = {0};
JsonToMqlTradeRequest(trade_request_jo, trade_request);
MqlTradeResult trade_result = {0};
bool ok = OrderSend(trade_request, trade_result);
JSONObject* result_value_jo = new JSONObject();
result_value_jo.put("RetVal", new JSONBool(ok));
result_value_jo.put("TradeResult", MqlTradeResultToJson(trade_result));
#ifdef __DEBUG_LOG__
PrintFormat("%s: return value = %s", __FUNCTION__, ok ? "true" : "false");
#endif
return CreateSuccessResponse("Value", result_value_jo);
}
string ExecuteRequest_PositionOpen(JSONObject *jo)
{
//Symbol
CHECK_JSON_VALUE(jo, "Symbol", CreateErrorResponse(-1, "Undefinded mandatory parameter Symbol"));
string symbol = jo.getString("Symbol");
//OrderType
CHECK_JSON_VALUE(jo, "OrderType", CreateErrorResponse(-1, "Undefinded mandatory parameter OrderType"));
ENUM_ORDER_TYPE order_type = (ENUM_ORDER_TYPE) jo.getInt("OrderType");
//Volume
CHECK_JSON_VALUE(jo, "Volume", CreateErrorResponse(-1, "Undefinded mandatory parameter Volume"));
double volume = jo.getDouble("Volume");
//Price
CHECK_JSON_VALUE(jo, "Price", CreateErrorResponse(-1, "Undefinded mandatory parameter Price"));
double price = jo.getDouble("Price");
//Sl
CHECK_JSON_VALUE(jo, "Sl", CreateErrorResponse(-1, "Undefinded mandatory parameter Sl"));
double sl = jo.getDouble("Sl");
//Tp
CHECK_JSON_VALUE(jo, "Tp", CreateErrorResponse(-1, "Undefinded mandatory parameter Tp"));
double tp = jo.getDouble("Tp");
//Comment
string comment;
if (jo.getValue("Comment") != NULL)
{
comment = jo.getString("Comment");
}
#ifdef __DEBUG_LOG__
PrintFormat("%s: symbol = %s, order_type = %d, volume = %f, price = %f, sl = %f, tp = %f, comment = %s",
__FUNCTION__, symbol, order_type, volume, price, sl, tp, comment);
#endif
CTrade trade;
bool ok = trade.PositionOpen(symbol, order_type, volume, price, sl, tp, comment);
MqlTradeResult trade_result={0};
trade.Result(trade_result);
JSONObject* result_value_jo = new JSONObject();
result_value_jo.put("RetVal", new JSONBool(ok));
result_value_jo.put("TradeResult", MqlTradeResultToJson(trade_result));
return CreateSuccessResponse("Value", result_value_jo);
}
JSONObject* MqlTradeCheckResultToJson(MqlTradeCheckResult& result)
{
JSONObject* jo = new JSONObject();
jo.put("Retcode", new JSONNumber(result.retcode));
jo.put("Balance", new JSONNumber(result.balance));
jo.put("Equity", new JSONNumber(result.equity));
jo.put("Profit", new JSONNumber(result.profit));
jo.put("Margin", new JSONNumber(result.margin));
jo.put("Margin_free", new JSONNumber(result.margin_free));
jo.put("Margin_level", new JSONNumber(result.margin_level));
jo.put("Comment", new JSONString(result.comment));
return jo;
}
string ExecuteRequest_OrderCheck(JSONObject *jo)
{
CHECK_JSON_VALUE(jo, "TradeRequest", CreateErrorResponse(-1, "Undefinded mandatory parameter TradeRequest"));
JSONObject* trade_request_jo = jo.getObject("TradeRequest");
MqlTradeRequest trade_request = {0};
JsonToMqlTradeRequest(trade_request_jo, trade_request);
MqlTradeCheckResult trade_check_result = {0};
bool ok = OrderCheck(trade_request, trade_check_result);
#ifdef __DEBUG_LOG__
PrintFormat("%s: return value = %s", __FUNCTION__, ok ? "true" : "false");
#endif
JSONObject* result_value_jo = new JSONObject();
result_value_jo.put("RetVal", new JSONBool(ok));
result_value_jo.put("TradeCheckResult", MqlTradeCheckResultToJson(trade_check_result));
return CreateSuccessResponse("Value", result_value_jo);
}