Compare commits

...

17 Commits

Author SHA1 Message Date
Viacheslav Demydiuk 9a5acac2db Update readme: updated links 2020-10-13 15:19:26 +03:00
Viacheslav Demydiuk 7a776de8d3 Update readme: added link to telegram's chat 2020-10-13 15:18:03 +03:00
Viacheslav Demydiuk ce7953eee0 Issue #204: [MT5] Added function OrderSendAsync 2020-10-13 15:16:55 +03:00
Viacheslav Demydiuk 93aed4e44c Issue #202: [MT5] added Buy/Sell functions 2020-10-13 14:14:59 +03:00
Viacheslav Demydiuk 4c8c3b8766 MtApi [MT5] version 1.0.23 2020-09-04 12:10:26 +03:00
Viacheslav Demydiuk 73ebde8b6b Added link on Telegram's channel to readme 2020-08-30 12:28:54 +03:00
Viacheslav Demydiuk e33ba5b51f Issue #190: updated MtApi5.mq5 to version 1.7. Init string variable _erro 2020-08-28 18:54:33 +03:00
Viacheslav Demydiuk a0a4263e24 Issue #190: implemented function sendErrorResponse in Mt5Connector 2020-08-28 17:39:49 +03:00
Viacheslav Demydiuk 5d18dd4ad3 MTApiService version 1.0.32 2020-08-28 17:28:34 +03:00
Viacheslav Demydiuk 03ff1f9176 MtApi [MT5] version 1.0.22 2020-08-28 16:48:31 +03:00
Viacheslav Demydiuk f376b4e0e5 MtApi (MT4) version 1.0.41 2020-08-26 22:59:21 +03:00
Viacheslav Demydiuk fc54b5dd4a Updated test application (MT5) to perform testing functions iBullsPower, iBearsPower, BarsCalculated, CopyBuffer. 2020-08-26 21:06:26 +03:00
Viacheslav Demydiuk dd05804082 Issue #201: call iBullsPower instead iBearsPower in MQL 2020-08-26 17:53:31 +03:00
Viacheslav Demydiuk 4349eb3538 Issue #186: Implemented function PositionClosePartial 2020-08-24 22:43:20 +03:00
Vyacheslav Demidyuk e0daf9a82e Merge pull request #198 from KptKuck/dev
Add switchable Events / fix typo in AddLog()
2020-08-09 11:00:55 +03:00
Christian_X3 3997b6df74 add switchable Events
The function SendMtEvent requires a lot of computing time. To improve the speed of the tester, the events can now be switched off individually
2020-06-18 05:57:05 +02:00
Christian_X3 abfe1a281a fix typo in Addlog() 2020-06-18 05:03:21 +02:00
16 changed files with 555 additions and 63 deletions
+10
View File
@@ -208,6 +208,16 @@ _DLLAPI int _stdcall sendMqlRatesArrayResponse(int expertHandle, CMqlRates value
}, err, 0);
}
_DLLAPI bool _stdcall sendErrorResponse(int expertHandle, int code, wchar_t* message, wchar_t* err)
{
return Execute<bool>([&expertHandle, &code, message]() {
MtResponseString^ res = gcnew MtResponseString(gcnew String(message));
res->ErrorCode = code;
MtAdapter::GetInstance()->SendResponse(expertHandle, res);
return true;
}, err, false);
}
//----------- get values -------------------------------
_DLLAPI int _stdcall getCommandType(int expertHandle, int* res, wchar_t* err)
+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.31.0")]
[assembly: AssemblyFileVersion("1.0.31.0")]
[assembly: AssemblyVersion("1.0.32.0")]
[assembly: AssemblyFileVersion("1.0.32.0")]
+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.40.0")]
[assembly: AssemblyFileVersion("1.0.40.0")]
[assembly: AssemblyVersion("1.0.41.0")]
[assembly: AssemblyFileVersion("1.0.41.0")]
+2
View File
@@ -102,6 +102,8 @@ namespace MtApi5
PositionClose = 64,
PositionOpen = 65,
PositionModify = 6066,
PositionClosePartial_bySymbol = 6067,
PositionClosePartial_byTicket = 6068,
//PositionOpenWithResult = 1065,
//Backtesting
+3
View File
@@ -78,6 +78,7 @@
<Compile Include="Events\Mt5EventTypes.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Mt5Quote.cs" />
<Compile Include="Requests\BuyRequest.cs" />
<Compile Include="Requests\ChartTimePriceToXyRequest.cs" />
<Compile Include="Requests\ChartTimePriceToXyResult.cs" />
<Compile Include="Requests\ChartXyToTimePriceRequest.cs" />
@@ -88,6 +89,7 @@
<Compile Include="Requests\MarketBookGetRequest.cs" />
<Compile Include="Requests\OrderCheckRequest.cs" />
<Compile Include="Requests\OrderCheckResult.cs" />
<Compile Include="Requests\OrderSendAsyncRequest.cs" />
<Compile Include="Requests\OrderSendRequest.cs" />
<Compile Include="Requests\PositionCloseRequest.cs" />
<Compile Include="Requests\PositionCloseResult.cs" />
@@ -96,6 +98,7 @@
<Compile Include="Requests\RequestType.cs" />
<Compile Include="Requests\OrderSendResult.cs" />
<Compile Include="Requests\Response.cs" />
<Compile Include="Requests\SellRequest.cs" />
<Compile Include="Requests\SymbolInfoStringRequest.cs" />
<Compile Include="Requests\SymbolInfoStringResult.cs" />
<Compile Include="Requests\SymbolInfoTickRequest.cs" />
+118
View File
@@ -134,6 +134,38 @@ namespace MtApi5
return response != null && response.RetVal;
}
///<summary>
///Function is used for conducting asynchronous trade operations without waiting for the trade server's response to a sent request.
///</summary>
///<param name="request">Reference to a object of MqlTradeRequest type describing the trade activity of the client.</param>
///<param name="result">Reference to a object of MqlTradeResult type describing the result of trade operation in case of a successful completion (if true is returned).</param>
/// <returns>
/// Returns true if the request is sent to a trade server. In case the request is not sent, it returns false.
/// In case the request is sent, in the result variable the response code contains TRADE_RETCODE_PLACED value (code 10008) "order placed".
/// Successful execution means only the fact of sending, but does not give any guarantee that the request has reached the trade server and has been accepted for processing.
/// When processing the received request, a trade server sends a reply to a client terminal notifying of change in the current state of positions,
/// orders and deals, which leads to the generation of the Trade event.
/// </returns>
public bool OrderSendAsync(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 response = SendRequest<OrderSendResult>(new OrderSendAsyncRequest
{
TradeRequest = request
});
result = response?.TradeResult;
return response != null && response.RetVal;
}
///<summary>
///The function calculates the margin required for the specified order type, on the current account
///, in the current market environment not taking into account current pending orders and open positions
@@ -655,6 +687,92 @@ namespace MtApi5
{
return PositionOpen(symbol, orderType, volume, price, sl, tp, "", out result);
}
/// <summary>
/// Partially closes a position on a specified symbol in case of a "hedging" accounting.
/// </summary>
/// <param name="symbol">Name of a trading instrument, on which a position is closed partially.</param>
/// <param name="volume"> Volume, by which a position should be decreased. If the value exceeds the volume of a partially closed position, it is closed in full. No position in the opposite direction is opened.</param>
/// <param name="deviation">The maximum deviation from the current price (in points).</param>
/// <returns>true if the basic check of structures is successful, otherwise false.</returns>
public bool PositionClosePartial(string symbol, double volume, ulong deviation = ulong.MaxValue)
{
var commandParameters = new ArrayList { symbol, volume, deviation };
return SendCommand<bool>(Mt5CommandType.PositionClosePartial_bySymbol, commandParameters);
}
/// <summary>
/// Partially closes a position on a specified symbol in case of a "hedging" accounting.
/// </summary>
/// <param name="ticket">Closed position ticket.</param>
/// <param name="volume"> Volume, by which a position should be decreased. If the value exceeds the volume of a partially closed position, it is closed in full. No position in the opposite direction is opened.</param>
/// <param name="deviation">The maximum deviation from the current price (in points).</param>
/// <returns>true if the basic check of structures is successful, otherwise false.</returns>
public bool PositionClosePartial(ulong ticket, double volume, ulong deviation = ulong.MaxValue)
{
var commandParameters = new ArrayList { ticket, volume, deviation };
return SendCommand<bool>(Mt5CommandType.PositionClosePartial_byTicket, commandParameters);
}
/// <summary>
/// Opens a long position with specified parameters with current market Ask price
/// </summary>
/// <param name="result">output result</param>
/// <param name="volume">Requested position volume.</param>
/// <param name="symbol">Position symbol. If it is not specified, the current symbol will be used.</param>
/// <param name="price">Execution price.</param>
/// <param name="sl">Stop Loss price.</param>
/// <param name="tp">Take Profit price.</param>
/// <param name="comment">Comment.</param>
/// <returns>true - successful check of the structures, otherwise - false.</returns>
public bool Buy(out MqlTradeResult result, double volume, string symbol = null, double price = 0.0, double sl = 0.0, double tp = 0.0, string comment = null)
{
Log.Debug($"Buy: volume = {volume}, symbol = {symbol}, sl = {sl}, tp = {tp}, comment = {comment}");
var response = SendRequest<OrderSendResult>(new BuyRequest
{
Volume = volume,
Symbol = symbol,
Price = price,
Sl = sl,
Tp = tp,
Comment = comment
});
result = response?.TradeResult;
return response != null && response.RetVal;
}
/// <summary>
/// Opens a short position with specified parameters with current market Bid price
/// </summary>
/// <param name="result">output result</param>
/// <param name="volume">Requested position volume.</param>
/// <param name="symbol">Position symbol. If it is not specified, the current symbol will be used.</param>
/// <param name="price">Execution price.</param>
/// <param name="sl">Stop Loss price.</param>
/// <param name="tp">Take Profit price.</param>
/// <param name="comment">Comment.</param>
/// <returns>true - successful check of the structures, otherwise - false.</returns>
public bool Sell(out MqlTradeResult result, double volume, string symbol = null, double price = 0.0, double sl = 0.0, double tp = 0.0, string comment = null)
{
Log.Debug($"Sell: volume = {volume}, symbol = {symbol}, sl = {sl}, tp = {tp}, comment = {comment}");
var response = SendRequest<OrderSendResult>(new SellRequest
{
Volume = volume,
Symbol = symbol,
Price = price,
Sl = sl,
Tp = tp,
Comment = comment
});
result = response?.TradeResult;
return response != null && response.RetVal;
}
#endregion
#region Account Information functions
+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.21")]
[assembly: AssemblyFileVersion("1.0.21")]
[assembly: AssemblyVersion("1.0.23")]
[assembly: AssemblyFileVersion("1.0.23")]
+14
View File
@@ -0,0 +1,14 @@
namespace MtApi5.Requests
{
internal class BuyRequest : RequestBase
{
public override RequestType RequestType => RequestType.Buy;
public double Volume { get; set; }
public string Symbol { get; set; }
public double Price { get; set; }
public double Sl { get; set; }
public double Tp { get; set; }
public string Comment { get; set; }
}
}
+9
View File
@@ -0,0 +1,9 @@
namespace MtApi5.Requests
{
internal class OrderSendAsyncRequest : RequestBase
{
public override RequestType RequestType => RequestType.OrderSendAsync;
public MqlTradeRequest TradeRequest { get; set; }
}
}
+4 -1
View File
@@ -16,6 +16,9 @@ namespace MtApi5.Requests
ChartTimePriceToXY = 9,
ChartXYToTimePrice = 10,
PositionClose = 11,
SymbolInfoTick = 12
SymbolInfoTick = 12,
Buy = 13,
Sell = 14,
OrderSendAsync = 15
}
}
+14
View File
@@ -0,0 +1,14 @@
namespace MtApi5.Requests
{
internal class SellRequest : RequestBase
{
public override RequestType RequestType => RequestType.Sell;
public double Volume { get; set; }
public string Symbol { get; set; }
public double Price { get; set; }
public double Sl { get; set; }
public double Tp { get; set; }
public string Comment { get; set; }
}
}
+5 -1
View File
@@ -20,4 +20,8 @@ MQL files have been build to ex4 and stored into folders "mq4" for MetaTrader an
Changing the source code of MQL expert requires recompilation with MetaEditor. Resulting in the need to copy files "hash.mqh" and "json.mqh" to the MetaEditor include folder.
# Home Website
Please visit http://mtapi4.net
# Telegram Channel
https://t.me/mtapi4
https://t.me/joinchat/GfnfUxvelQCLvvIvLO16-w
+15 -5
View File
@@ -439,6 +439,7 @@
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<DockPanel Grid.Row="0" LastChildFill="True">
@@ -454,6 +455,15 @@
<Button Command="{Binding IndicatorReleaseCommand}" Margin="2"
Content="IndicatorRelease" HorizontalAlignment="Left" />
</StackPanel>
<WrapPanel Grid.Row="2" Margin="2">
<Button Command="{Binding iCustomCommand}" Content="iCustom" Margin="2"/>
<Button Command="{Binding iBullsPowerCommand}" Content="iBullPower" Margin="2"/>
<Button Command="{Binding iBearsPowerCommand}" Content="iBearPower" Margin="2"/>
</WrapPanel>
<WrapPanel Grid.Row="3">
<Button Command="{Binding BarsCalculatedCommand}" Content="BarsCalculated" Margin="2"/>
<Button Command="{Binding CopyBufferCommand}" Content="CopyBuffer" Margin="2"/>
</WrapPanel>
</Grid>
</Grid>
@@ -487,6 +497,7 @@
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Button Grid.Row="0" Command="{Binding PositionOpenCommand}" Content="PositionOpen" Margin="2" HorizontalAlignment="Left"/>
<StackPanel Grid.Row="1" Orientation="Horizontal" Margin="4">
@@ -495,14 +506,13 @@
<Button Command="{Binding PositionCloseCommand}" Content="PositionClose" Margin="2"/>
</StackPanel>
<Button Grid.Row="2" Command="{Binding PositionCloseAllCommand}" Content="PositionCloseAll" Margin="2" HorizontalAlignment="Left"/>
<StackPanel Grid.Row="3" Orientation="Horizontal" Margin="4">
<Button Command="{Binding BuyCommand}" Content="Buy" Width="60" Margin="2" HorizontalAlignment="Left"/>
<Button Command="{Binding SellCommand}" Content="Sell" Width="60" Margin="2" HorizontalAlignment="Left"/>
</StackPanel>
</Grid>
</TabItem>
<TabItem Header="Indicators">
<WrapPanel VerticalAlignment="Top" Margin="5">
<Button Command="{Binding iCustomCommand}" Content="iCustom" Margin="2"/>
</WrapPanel>
</TabItem>
<TabItem Header="Chart Functions">
<Grid>
<Grid.RowDefinitions>
+97 -16
View File
@@ -44,6 +44,11 @@ namespace MtApi5TestClient
public DelegateCommand CopyCloseCommand { get; private set; }
public DelegateCommand IndicatorCreateCommand { get; private set; }
public DelegateCommand IndicatorReleaseCommand { get; private set; }
public DelegateCommand iCustomCommand { get; private set; }
public DelegateCommand iBullsPowerCommand { get; private set; }
public DelegateCommand iBearsPowerCommand { get; private set; }
public DelegateCommand BarsCalculatedCommand { get; private set; }
public DelegateCommand CopyBufferCommand { get; private set; }
public DelegateCommand CopyTickVolumeCommand { get; private set; }
public DelegateCommand CopyRealVolumeCommand { get; private set; }
@@ -68,6 +73,8 @@ namespace MtApi5TestClient
public DelegateCommand PositionOpenCommand { get; private set; }
public DelegateCommand PositionCloseCommand { get; private set; }
public DelegateCommand PositionCloseAllCommand { get; private set; }
public DelegateCommand BuyCommand { get; private set; }
public DelegateCommand SellCommand { get; private set; }
public DelegateCommand GetLastErrorCommand { get; private set; }
public DelegateCommand ResetLastErrorCommand { get; private set; }
@@ -75,8 +82,6 @@ namespace MtApi5TestClient
public DelegateCommand AlertCommand { get; private set; }
public DelegateCommand TesterStopCommand { get; private set; }
public DelegateCommand iCustomCommand { get; private set; }
public DelegateCommand TimeCurrentCommand { get; private set; }
public DelegateCommand ChartOpenCommand { get; private set; }
@@ -354,6 +359,11 @@ namespace MtApi5TestClient
CopyCloseCommand = new DelegateCommand(ExecuteCopyClose);
IndicatorCreateCommand = new DelegateCommand(ExecuteIndicatorCreate);
IndicatorReleaseCommand = new DelegateCommand(ExecuteIndicatorRelease);
iCustomCommand = new DelegateCommand(ExecuteICustom);
iBullsPowerCommand = new DelegateCommand(ExecuteIBullsPowerCommand);
iBearsPowerCommand = new DelegateCommand(ExecuteIBearsPowerCommand);
BarsCalculatedCommand = new DelegateCommand(ExecuteBarsCalculatedCommand);
CopyBufferCommand = new DelegateCommand(ExecuteCopyBufferCommand);
CopyTickVolumeCommand = new DelegateCommand(ExecuteCopyTickVolume);
CopyRealVolumeCommand = new DelegateCommand(ExecuteCopyRealVolume);
@@ -378,6 +388,8 @@ namespace MtApi5TestClient
PositionOpenCommand = new DelegateCommand(ExecutePositionOpen);
PositionCloseCommand = new DelegateCommand(ExecutePositionClose);
PositionCloseAllCommand = new DelegateCommand(ExecutePositionCloseAll);
BuyCommand = new DelegateCommand(ExecuteBuy);
SellCommand = new DelegateCommand(ExecuteSell);
PrintCommand = new DelegateCommand(ExecutePrint);
AlertCommand = new DelegateCommand(ExecuteAlert);
@@ -385,8 +397,6 @@ namespace MtApi5TestClient
ResetLastErrorCommand = new DelegateCommand(ExecuteResetLastError);
TesterStopCommand = new DelegateCommand(ExecuteTesterStop);
iCustomCommand = new DelegateCommand(ExecuteICustom);
ChartOpenCommand = new DelegateCommand(ExecuteChartOpen);
ChartTimePriceToXYCommand = new DelegateCommand(ExecuteChartTimePriceToXY);
ChartXYToTimePriceCommand = new DelegateCommand(ExecuteChartXYToTimePrice);
@@ -806,6 +816,68 @@ namespace MtApi5TestClient
AddLog($"IndicatorRelease [{indicatorHandle}]: result - {retVal}");
}
private async void ExecuteICustom(object o)
{
const string name = @"Examples\Custom Moving Average";
int[] parameters = { 0, 21, (int)ENUM_APPLIED_PRICE.PRICE_CLOSE };
var retVal = await Execute(() => _mtApiClient.iCustom(TimeSeriesValues.SymbolValue, TimeSeriesValues.TimeFrame, name, parameters));
TimeSeriesValues.IndicatorHandle = retVal;
AddLog($"Custom Moving Average: result - {retVal}");
}
private async void ExecuteIBullsPowerCommand(object o)
{
const int maPeriod = 13;
var retVal = await Execute(() => _mtApiClient.iBullsPower(TimeSeriesValues.SymbolValue, TimeSeriesValues.TimeFrame, maPeriod));
TimeSeriesValues.IndicatorHandle = retVal;
AddLog($"iBullPower: result - {retVal}");
}
private async void ExecuteIBearsPowerCommand(object o)
{
const int maPeriod = 13;
var retVal = await Execute(() => _mtApiClient.iBearsPower(TimeSeriesValues.SymbolValue, TimeSeriesValues.TimeFrame, maPeriod));
TimeSeriesValues.IndicatorHandle = retVal;
AddLog($"iBearsPower: result - {retVal}");
}
private async void ExecuteBarsCalculatedCommand(object o)
{
var retVal = await Execute(() => _mtApiClient.BarsCalculated(TimeSeriesValues.IndicatorHandle));
AddLog($"BarsCalculated: result - {retVal}");
}
private async void ExecuteCopyBufferCommand(object o)
{
TimeSeriesResults.Clear();
var result = await Execute(() =>
{
var count = _mtApiClient.CopyBuffer(TimeSeriesValues.IndicatorHandle, 0, TimeSeriesValues.StartPos, TimeSeriesValues.Count, out var values);
return count > 0 ? values : null;
});
if (result == null)
{
AddLog("CopyRates: result is null");
return;
}
RunOnUiThread(() =>
{
foreach (var value in result)
{
TimeSeriesResults.Add($"{value:F6}");
}
});
AddLog("CopyRates: success");
}
private async void ExecuteCopyRates(object o)
{
if (string.IsNullOrEmpty(TimeSeriesValues?.SymbolValue)) return;
@@ -1143,6 +1215,26 @@ namespace MtApi5TestClient
AddLog($"PositionCloseAll: count = {retVal}");
}
private async void ExecuteBuy(object obj)
{
const string symbol = "EURUSD";
const double volume = 0.1;
MqlTradeResult tradeResult = null;
var retVal = await Execute(() => _mtApiClient.Buy(out tradeResult, volume, symbol));
AddLog($"Buy: symbol EURUSD retVal = {retVal}, result = {tradeResult}");
}
private async void ExecuteSell(object obj)
{
const string symbol = "EURUSD";
const double volume = 0.1;
MqlTradeResult tradeResult = null;
var retVal = await Execute(() => _mtApiClient.Sell(out tradeResult, volume, symbol));
AddLog($"Sell: symbol EURUSD retVal = {retVal}, result = {tradeResult}");
}
private async void ExecutePrint(object obj)
{
var message = MessageText;
@@ -1177,17 +1269,6 @@ namespace MtApi5TestClient
AddLog("TesterStop: executed.");
}
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());
@@ -1676,7 +1757,7 @@ namespace MtApi5TestClient
private void _mtApiClient_OnLastTimeBar(object sender, Mt5TimeBarArgs e)
{
AddLog($"OnBookEvent: ExpertHandle = {e.ExpertHandle}, Symbol = {e.Symbol}, open = {e.Rates.open}, close = {e.Rates.close}, time = {e.Rates.time}, high = {e.Rates.high}, low = {e.Rates.low}");
AddLog($"OnLastTimeBarEvent: ExpertHandle = {e.ExpertHandle}, Symbol = {e.Symbol}, open = {e.Rates.open}, close = {e.Rates.close}, time = {e.Rates.time}, high = {e.Rates.high}, low = {e.Rates.low}");
}
private void _mtApiClient_OnLockTicks(object sender, Mt5LockTicksEventArgs e)
BIN
View File
Binary file not shown.
+258 -34
View File
@@ -1,7 +1,7 @@
#property copyright "Vyacheslav Demidyuk"
#property link ""
#property version "1.6"
#property version "1.9"
#property description "MtApi (MT5) connection expert"
#include <json.mqh>
@@ -50,6 +50,12 @@ enum LockTickType
input int Port = 8228;
input LockTickType BacktestingLockTicks = NO_LOCK;
input group "Disable Events "
input bool Enable_OnBookEvent = true;
input bool Enable_OnTickEvent = true;
input bool Enable_OnTradeTransactionEvent = true;
input bool Enable_OnLastBarEvent = true;
int ExpertHandle;
@@ -89,27 +95,31 @@ void OnTick()
long lastbar_time = SeriesInfoInteger(symbol, Period(), SERIES_LASTBAR_DATE);
if (_last_bar_open_time != lastbar_time)
{
if (_last_bar_open_time != 0)
if (_last_bar_open_time != 0 )
{
MqlRates rates_array[];
CopyRates(symbol, Period(), 1, 1, rates_array);
if(Enable_OnLastBarEvent)
{
MqlRates rates_array[];
CopyRates(symbol, Period(), 1, 1, rates_array);
MtTimeBarEvent* time_bar = new MtTimeBarEvent(symbol, rates_array[0]);
SendMtEvent(ON_LAST_TIME_BAR_EVENT, time_bar);
delete time_bar;
lastbar_time_changed = true;
MtTimeBarEvent* time_bar = new MtTimeBarEvent(symbol, rates_array[0]);
SendMtEvent(ON_LAST_TIME_BAR_EVENT, time_bar);
delete time_bar;
}
lastbar_time_changed = true;
}
_last_bar_open_time = lastbar_time;
}
MqlTick last_tick;
SymbolInfoTick(Symbol(),last_tick);
if (Enable_OnTickEvent)
{
MqlTick last_tick;
SymbolInfoTick(Symbol(),last_tick);
MtOnTickEvent * tick_event = new MtOnTickEvent(symbol, last_tick);
SendMtEvent(ON_TICK_EVENT, tick_event);
delete tick_event;
MtOnTickEvent * tick_event = new MtOnTickEvent(symbol, last_tick);
SendMtEvent(ON_TICK_EVENT, tick_event);
delete tick_event;
}
if (IsTesting())
{
@@ -132,29 +142,37 @@ void OnTradeTransaction(
const MqlTradeRequest& request, // request structure
const MqlTradeResult& result // result structure
)
{
#ifdef __DEBUG_LOG__
PrintFormat("%s:", __FUNCTION__);
#endif
MtOnTradeTransactionEvent* trans_event = new MtOnTradeTransactionEvent(trans, request, result);
SendMtEvent(ON_TRADE_TRANSACTION_EVENT, trans_event);
delete trans_event;
}
{
if(!Enable_OnTradeTransactionEvent) return;
#ifdef __DEBUG_LOG__
PrintFormat("%s:", __FUNCTION__);
#endif
MtOnTradeTransactionEvent* trans_event = new MtOnTradeTransactionEvent(trans, request, result);
SendMtEvent(ON_TRADE_TRANSACTION_EVENT, trans_event);
delete trans_event;
}
void OnBookEvent(const string& symbol)
{
#ifdef __DEBUG_LOG__
PrintFormat("%s: %s", __FUNCTION__, symbol);
#endif
{
if(!Enable_OnBookEvent) return;
#ifdef __DEBUG_LOG__
PrintFormat("%s: %s", __FUNCTION__, symbol);
#endif
MtOnBookEvent * book_event = new MtOnBookEvent(symbol);
SendMtEvent(ON_BOOK_EVENT, book_event);
delete book_event;
}
MtOnBookEvent * book_event = new MtOnBookEvent(symbol);
SendMtEvent(ON_BOOK_EVENT, book_event);
delete book_event;
}
int preinit()
{
StringInit(_error,1000,0);
StringInit(_response_error,1000,0);
return (0);
@@ -555,6 +573,12 @@ int executeCommand()
case 6066: //PositionModify
Execute_PositionModify();
break;
case 6067: //PositionClosePartial_bySymbol
Execute_PositionClosePartial_bySymbol();
break;
case 6068: //Execute_PositionClosePartial_byTicket
Execute_PositionClosePartial_byTicket();
break;
case 66: //BacktestingReady
Execute_BacktestingReady();
break;
@@ -3296,6 +3320,80 @@ void Execute_PositionModify()
}
}
void Execute_PositionClosePartial_bySymbol()
{
string symbol;
double volume;
ulong deviation;
if (!getStringValue(ExpertHandle, 0, symbol, _error))
{
PrintParamError("PositionClosePartial (1)", "symbol", _error);
sendErrorResponse(ExpertHandle, -1, _error, _response_error);
return;
}
if (!getDoubleValue(ExpertHandle, 1, volume, _error))
{
PrintParamError("PositionClosePartial (1)", "volume", _error);
sendErrorResponse(ExpertHandle, -1, _error, _response_error);
return;
}
if (!getULongValue(ExpertHandle, 2, deviation, _error))
{
PrintParamError("PositionClosePartial (1)", "deviation", _error);
sendErrorResponse(ExpertHandle, -1, _error, _response_error);
return;
}
CTrade trade;
bool ok = trade.PositionClosePartial(symbol, volume, deviation);
#ifdef __DEBUG_LOG__
Print("command PositionClosePartial (1): result = ", ok);
#endif
if (!sendBooleanResponse(ExpertHandle, ok, _response_error))
{
PrintResponseError("PositionClosePartial (1)", _response_error);
}
}
void Execute_PositionClosePartial_byTicket()
{
ulong ticket;
double volume;
ulong deviation;
if (!getULongValue(ExpertHandle, 0, ticket, _error))
{
PrintParamError("PositionClosePartial (2)", "ticket", _error);
sendErrorResponse(ExpertHandle, -1, _error, _response_error);
return;
}
if (!getDoubleValue(ExpertHandle, 1, volume, _error))
{
PrintParamError("PositionClosePartial (2)", "volume", _error);
sendErrorResponse(ExpertHandle, -1, _error, _response_error);
return;
}
if (!getULongValue(ExpertHandle, 2, deviation, _error))
{
PrintParamError("PositionClosePartial (2)", "deviation", _error);
sendErrorResponse(ExpertHandle, -1, _error, _response_error);
return;
}
CTrade trade;
bool ok = trade.PositionClosePartial(ticket, volume, deviation);
#ifdef __DEBUG_LOG__
Print("command PositionClosePartial (2): result = ", ok);
#endif
if (!sendBooleanResponse(ExpertHandle, ok, _response_error))
{
PrintResponseError("PositionClosePartial (2)", _response_error);
}
}
void Execute_PositionOpen(bool isTradeResultRequired)
{
string symbol;
@@ -4457,7 +4555,7 @@ void Execute_iBullsPower()
}
if (!sendIntResponse(ExpertHandle,
iBearsPower(symbol, (ENUM_TIMEFRAMES)period, ma_period),
iBullsPower(symbol, (ENUM_TIMEFRAMES)period, ma_period),
_error))
{
PrintResponseError("iBullsPower", _response_error);
@@ -6858,6 +6956,15 @@ string OnRequest(string json)
case 12: //SymbolInfoTick
response = ExecuteRequest_SymbolInfoTick(jo);
break;
case 13: //Buy
response = ExecuteRequest_Buy(jo);
break;
case 14: //Sell
response = ExecuteRequest_Sell(jo);
break;
case 15: //OrderSendAsync
response = ExecuteRequest_OrderSendAsync(jo);
break;
default:
PrintFormat("%s [WARNING]: Unknown request type %d", __FUNCTION__, requestType);
response = CreateErrorResponse(-1, "Unknown request type");
@@ -7067,6 +7174,30 @@ string ExecuteRequest_OrderSend(JSONObject *jo)
return CreateSuccessResponse("Value", result_value_jo);
}
string ExecuteRequest_OrderSendAsync(JSONObject *jo)
{
CHECK_JSON_VALUE(jo, "TradeRequest", CreateErrorResponse(-1, "Undefinded mandatory parameter TradeRequest"));
JSONObject* trade_request_jo = jo.getObject("TradeRequest");
MqlTradeRequest trade_request = {0};
bool converted = JsonToMqlTradeRequest(trade_request_jo, trade_request);
if (converted == false)
return CreateErrorResponse(-1, "Failed to parse parameter TradeRequest");
MqlTradeResult trade_result = {0};
bool ok = OrderSendAsync(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
@@ -7389,6 +7520,98 @@ string ExecuteRequest_SymbolInfoTick(JSONObject *jo)
return CreateSuccessResponse("Value", MqlTickToJson(tick));
}
string ExecuteRequest_Buy(JSONObject *jo)
{
//Symbol
string symbol=Symbol();
if (jo.getValue("Symbol") != NULL)
symbol = jo.getString("Symbol");
//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, volume = %f, price = %f, sl = %f, tp = %f, comment = %s",
__FUNCTION__, symbol, volume, price, sl, tp, comment);
#endif
CTrade trade;
bool ok = trade.Buy(volume, symbol, 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);
}
string ExecuteRequest_Sell(JSONObject *jo)
{
//Symbol
string symbol=Symbol();
if (jo.getValue("Symbol") != NULL)
symbol = jo.getString("Symbol");
//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, volume = %f, price = %f, sl = %f, tp = %f, comment = %s",
__FUNCTION__, symbol, volume, price, sl, tp, comment);
#endif
CTrade trade;
bool ok = trade.Sell(volume, symbol, 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);
}
//------------ Events -------------------------------------------------------
enum MtEventTypes
@@ -7521,6 +7744,7 @@ void SendMtEvent(MtEventTypes eventType, MtEvent* mtEvent)
if (sendEvent(ExpertHandle, (int)eventType, json.toString(), _error))
{
#ifdef __DEBUG_LOG__
PrintFormat("%s: event = %s", __FUNCTION__, EnumToString(eventType));
PrintFormat("%s: payload = %s", __FUNCTION__, json.toString());
#endif
}