Skip to content

Commit

Permalink
Issue #122: Implemented UnlockTicks function in MtApi (MT5)
Browse files Browse the repository at this point in the history
  • Loading branch information
vdemydiuk committed Jun 5, 2018
1 parent 0f717f1 commit 1a5882b
Show file tree
Hide file tree
Showing 14 changed files with 251 additions and 29 deletions.
51 changes: 40 additions & 11 deletions MTApiService/Mt5Expert.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,51 @@ namespace MTApiService
{
public class Mt5Expert : MtExpert
{
private static readonly ILog Log = LogManager.GetLogger(typeof(MtExpert));
private static readonly ILog Log = LogManager.GetLogger(typeof(Mt5Expert));
private const int StopExpertInterval = 2000; // 2 sec for testing mode
private readonly System.Timers.Timer _stopTimer = new System.Timers.Timer();
private System.Timers.Timer _stopTimer;


public Mt5Expert(int handle, string symbol, double bid, double ask, IMetaTraderHandler mtHandler, bool isTestMode) :
base(handle, symbol, bid, ask, mtHandler)
{
IsTestMode = isTestMode;
_stopTimer.Interval = StopExpertInterval;
_stopTimer.Elapsed += _stopTimer_Elapsed;
}

public bool IsTestMode { get; }

public override void UpdateQuote(MtQuote quote)
public override int GetCommandType()
{
Log.Debug("UpdateQuote: begin.");
Log.Debug("GetCommandType: called.");

base.UpdateQuote(quote);
if (IsTestMode)
{
ResetTestModeTimer();
}

return base.GetCommandType();
}

public override void SendEvent(MtEvent mtEvent)
{
Log.DebugFormat("SendEvent: begin. event = {0}", mtEvent);

if (IsTestMode)
{
//reset timer
_stopTimer.Stop();
_stopTimer.Start();
if (_stopTimer == null)
{
_stopTimer = new System.Timers.Timer
{
Interval = StopExpertInterval,
AutoReset = false
};
_stopTimer.Elapsed += _stopTimer_Elapsed;
}
}

Log.Debug("UpdateQuote: end.");
base.SendEvent(mtEvent);

Log.Debug("SendEvent: end.");
}

private void _stopTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
Expand All @@ -42,7 +58,20 @@ private void _stopTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
Log.Warn("Mt5Expert has received new tick during 2 sec in testing mode. The possible cause: user has stopped the tester manually in MetaTrader 5.");
Deinit();

_stopTimer.Elapsed -= _stopTimer_Elapsed;
_stopTimer = null;

Log.Debug("_stopTimer_Elapsed: end.");
}

private void ResetTestModeTimer()
{
if (_stopTimer == null)
return;

//reset timer
_stopTimer.Stop();
_stopTimer.Start();
}
}
}
27 changes: 26 additions & 1 deletion MTApiService/MtAdapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ public void AddExpert(int port, MtExpert expert)
}

server.AddExpert(expert);
expert.Deinited += ExpertOnDeinited;

Log.Info("AddExpert: end");
}
Expand All @@ -81,7 +82,6 @@ public void RemoveExpert(int expertHandle)
if (_experts.ContainsKey(expertHandle))
{
expert = _experts[expertHandle];
_experts.Remove(expertHandle);
}
}

Expand Down Expand Up @@ -270,6 +270,31 @@ private void server_Stopped(object sender, EventArgs e)
}
}
}


private void ExpertOnDeinited(object sender, EventArgs eventArgs)
{
Log.Debug("ExpertOnDeinited: begin.");

var expert = sender as MtExpert;
if (expert == null)
{
Log.Warn("expert_Deinited: end. Expert is not defined.");
return;
}

lock (_experts)
{
if (_experts.ContainsKey(expert.Handle))
{
_experts.Remove(expert.Handle);
}
}

Log.DebugFormat("ExpertOnDeinited: removed expert {0}", expert.Handle);

Log.Debug("ExpertOnDeinited: end.");
}
#endregion
}
}
6 changes: 3 additions & 3 deletions MTApiService/MtExpert.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public void SendResponse(MtResponse response)
Log.Debug("SendResponse: end.");
}

public int GetCommandType()
public virtual int GetCommandType()
{
Log.Debug("GetCommandType: called.");

Expand Down Expand Up @@ -110,7 +110,7 @@ public bool ContainsNamedParameter(string name)
return command.NamedParams.ContainsKey(name);
}

public void SendEvent(MtEvent mtEvent)
public virtual void SendEvent(MtEvent mtEvent)
{
Log.DebugFormat("SendEvent: begin. event = {0}", mtEvent);

Expand All @@ -119,7 +119,7 @@ public void SendEvent(MtEvent mtEvent)
Log.Debug("SendEvent: end.");
}

public virtual void UpdateQuote(MtQuote quote)
public void UpdateQuote(MtQuote quote)
{
Log.DebugFormat("UpdateQuote: begin. quote = {0}", quote);

Expand Down
3 changes: 2 additions & 1 deletion MtApi5/Events/Mt5EventTypes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ internal enum Mt5EventTypes
{
OnTradeTransaction = 1,
OnBookEvent = 2,
OnTick = 3
OnTick = 3,
OnLastTimeBar = 4
}
}
9 changes: 9 additions & 0 deletions MtApi5/Events/OnLastTimeBarEvent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace MtApi5.Events
{
public class OnLastTimeBarEvent
{
public MqlRates Rates { get; set; }
public string Instrument { get; set; }
public int ExpertHandle { get; set; }
}
}
4 changes: 1 addition & 3 deletions MtApi5/MqlRates.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ public class MqlRates
{
public MqlRates(DateTime time, double open, double high, double low, double close, long tick_volume, int spread, long real_volume)
{
this.time = time;
mt_time = Mt5TimeConverter.ConvertToMtTime(time);
this.open = open;
this.high = high;
Expand All @@ -20,7 +19,6 @@ public MqlRates(DateTime time, double open, double high, double low, double clos

internal MqlRates(long time, double open, double high, double low, double close, long tick_volume, int spread, long real_volume)
{
this.time = Mt5TimeConverter.ConvertFromMtTime(time);
mt_time = time;
this.open = open;
this.high = high;
Expand All @@ -35,7 +33,7 @@ public MqlRates()
{
}

public DateTime time { get; set; } // Period start time
public DateTime time => Mt5TimeConverter.ConvertFromMtTime(mt_time); // Period start time
public long mt_time { get; set; } // Period start time (original MT time)
public double open { get; set; } // Open price
public double high { get; set; } // The highest price of the period
Expand Down
4 changes: 3 additions & 1 deletion MtApi5/Mt5CommandType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,8 @@ internal enum Mt5CommandType
GlobalVariableTemp = 154,
GlobalVariableSetOnCondition = 156,
GlobalVariablesDeleteAll = 157,
GlobalVariablesTotal = 158
GlobalVariablesTotal = 158,

UnlockTicks = 159
}
}
18 changes: 18 additions & 0 deletions MtApi5/Mt5TimeBarArgs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System;

namespace MtApi5
{
public class Mt5TimeBarArgs: EventArgs
{
internal Mt5TimeBarArgs(int expertHandle, string symbol, MqlRates rates)
{
ExpertHandle = expertHandle;
Rates = rates;
Symbol = symbol;
}

public int ExpertHandle { get; }
public string Symbol { get; }
public MqlRates Rates { get; }
}
}
2 changes: 2 additions & 0 deletions MtApi5/MtApi5.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,10 @@
<ItemGroup>
<Compile Include="CopyTicksFlag.cs" />
<Compile Include="Events\OnBookEvent.cs" />
<Compile Include="Events\OnLastTimeBarEvent.cs" />
<Compile Include="Events\OnTickEvent.cs" />
<Compile Include="Events\OnTradeTransactionEvent.cs" />
<Compile Include="Mt5TimeBarArgs.cs" />
<Compile Include="MqlBookInfo.cs" />
<Compile Include="MqlParam.cs" />
<Compile Include="MqlRates.cs" />
Expand Down
20 changes: 20 additions & 0 deletions MtApi5/MtApi5Client.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ public MtApi5Client()
_mtEventHandlers[Mt5EventTypes.OnBookEvent] = ReceivedOnBookEvent;
_mtEventHandlers[Mt5EventTypes.OnTick] = ReceivedOnTickEvent;
_mtEventHandlers[Mt5EventTypes.OnTradeTransaction] = ReceivedOnTradeTransaction;
_mtEventHandlers[Mt5EventTypes.OnLastTimeBar] = ReceivedOnLastTimeBar;
}

///<summary>
Expand Down Expand Up @@ -3057,6 +3058,18 @@ public int GlobalVariablesTotal()
}
#endregion

#region Backtesting functions

///<summary>
///The function unlock ticks in backtesting mode.
///</summary>
public void UnlockTicks()
{
SendCommand<object>(Mt5CommandType.UnlockTicks, null);
}

#endregion

#endregion // Public Methods

#region Properties
Expand Down Expand Up @@ -3104,6 +3117,7 @@ public int ExecutorHandle
public event EventHandler<Mt5ConnectionEventArgs> ConnectionStateChanged;
public event EventHandler<Mt5TradeTransactionEventArgs> OnTradeTransaction;
public event EventHandler<Mt5BookEventArgs> OnBookEvent;
public event EventHandler<Mt5TimeBarArgs> OnLastTimeBar;
#endregion

#region Private Methods
Expand Down Expand Up @@ -3216,6 +3230,12 @@ private void ReceivedOnTickEvent(int expertHandler, string payload)
QuoteUpdate?.Invoke(this, new Mt5QuoteEventArgs(quote));
}

private void ReceivedOnLastTimeBar(int expertHandler, string payload)
{
var e = JsonConvert.DeserializeObject<OnLastTimeBarEvent>(payload);
OnLastTimeBar?.Invoke(this, new Mt5TimeBarArgs(expertHandler, e.Instrument, e.Rates));
}

private void Connect(string host, int port)
{
var client = new MtClient(host, port);
Expand Down
5 changes: 4 additions & 1 deletion TestClients/MtApi5TestClient/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -574,14 +574,17 @@
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>

<WrapPanel VerticalAlignment="Top" Margin="5">
<Button Command="{Binding GetLastErrorCommand}" Content="GetLastError" Margin="2"/>
<Button Command="{Binding ResetLastErrorCommand}" Content="ResetLastError" Margin="2"/>
</WrapPanel>

<Grid Margin="10" Grid.Row="1">
<Button Grid.Row="1" Content="UnlockTicks" HorizontalAlignment="Left" Margin="5" Command="{Binding UnlockTicksCommand}"/>

<Grid Margin="10" Grid.Row="2">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
Expand Down
15 changes: 15 additions & 0 deletions TestClients/MtApi5TestClient/ViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ public class ViewModel : INotifyPropertyChanged
public DelegateCommand GlobalVariableSetOnConditionCommand { get; private set; }
public DelegateCommand GlobalVariablesDeleteAllCommand { get; private set; }
public DelegateCommand GlobalVariablesTotalCommand { get; private set; }

public DelegateCommand UnlockTicksCommand { get; private set; }
#endregion

#region Properties
Expand Down Expand Up @@ -289,6 +291,7 @@ public ViewModel()
_mtApiClient.QuoteUpdate += mMtApiClient_QuoteUpdate;
_mtApiClient.OnTradeTransaction += mMtApiClient_OnTradeTransaction;
_mtApiClient.OnBookEvent += _mtApiClient_OnBookEvent;
_mtApiClient.OnLastTimeBar += _mtApiClient_OnOnLastTimeBar;

ConnectionState = _mtApiClient.ConnectionState;
ConnectionMessage = "Disconnected";
Expand Down Expand Up @@ -424,6 +427,8 @@ private void InitCommands()
GlobalVariableSetOnConditionCommand = new DelegateCommand(ExecuteGlobalVariableSetOnCondition);
GlobalVariablesDeleteAllCommand = new DelegateCommand(ExecuteGlobalVariablesDeleteAll);
GlobalVariablesTotalCommand = new DelegateCommand(ExecuteGlobalVariablesTotal);

UnlockTicksCommand = new DelegateCommand(ExecuteUnlockTicks);
}

private bool CanExecuteConnect(object o)
Expand Down Expand Up @@ -1564,6 +1569,11 @@ private async void ExecuteChartScreenShot(object obj)
}
#endregion

private void ExecuteUnlockTicks(object o)
{
_mtApiClient.UnlockTicks();
}

private static void RunOnUiThread(Action action)
{
Application.Current?.Dispatcher.Invoke(action);
Expand Down Expand Up @@ -1640,6 +1650,11 @@ private void _mtApiClient_OnBookEvent(object sender, Mt5BookEventArgs e)
AddLog($"OnBookEvent: ExpertHandle = {e.ExpertHandle}, Symbol = {e.Symbol}");
}

private void _mtApiClient_OnOnLastTimeBar(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}");
}

private void AddQuote(Mt5Quote quote)
{
if (_quotesMap.ContainsKey(quote.ExpertHandle))
Expand Down
Binary file modified mq5/MtApi5.ex5
Binary file not shown.
Loading

0 comments on commit 1a5882b

Please sign in to comment.