-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathStrategyRunner.cs
229 lines (188 loc) · 11.1 KB
/
StrategyRunner.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
using DevelopmentInProgress.TradeServer.StrategyExecution.WebHost.Cache.Subscriptions;
using DevelopmentInProgress.TradeServer.StrategyExecution.WebHost.Cache.TradeStrategy;
using DevelopmentInProgress.TradeServer.StrategyExecution.WebHost.Notification;
using DevelopmentInProgress.TradeServer.StrategyExecution.WebHost.Utilities;
using DevelopmentInProgress.TradeView.Core.Extensions;
using DevelopmentInProgress.TradeView.Core.TradeStrategy;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace DevelopmentInProgress.TradeServer.StrategyExecution.WebHost
{
public class StrategyRunner : IStrategyRunner
{
private readonly IBatchNotification<StrategyNotification> strategyLogger;
private readonly IBatchNotification<StrategyNotification> strategyAccountInfoPublisher;
private readonly IBatchNotification<StrategyNotification> strategyCustomNotificationPublisher;
private readonly IBatchNotification<StrategyNotification> strategyNotificationPublisher;
private readonly IBatchNotification<StrategyNotification> strategyOrderBookPublisher;
private readonly IBatchNotification<StrategyNotification> strategyTradePublisher;
private readonly IBatchNotification<StrategyNotification> strategyStatisticsPublisher;
private readonly IBatchNotification<StrategyNotification> strategyCandlesticksPublisher;
private readonly IBatchNotification<StrategyNotification> strategyParameterUpdatePublisher;
private readonly ISubscriptionsCacheManager subscriptionsCacheManager;
private readonly ITradeStrategyCacheManager tradeStrategyCacheManager;
private CancellationToken cancellationToken;
public StrategyRunner(
IBatchNotificationFactory<StrategyNotification> batchNotificationFactory,
ISubscriptionsCacheManager subscriptionsCacheManager,
ITradeStrategyCacheManager tradeStrategyCacheManager)
{
if (batchNotificationFactory == null)
{
throw new ArgumentNullException(nameof(batchNotificationFactory));
}
this.subscriptionsCacheManager = subscriptionsCacheManager ?? throw new ArgumentNullException(nameof(subscriptionsCacheManager));
this.tradeStrategyCacheManager = tradeStrategyCacheManager ?? throw new ArgumentNullException(nameof(tradeStrategyCacheManager));
strategyLogger = batchNotificationFactory.GetBatchNotifier(BatchNotificationType.StrategyLogger);
strategyAccountInfoPublisher = batchNotificationFactory.GetBatchNotifier(BatchNotificationType.StrategyAccountInfoPublisher);
strategyCustomNotificationPublisher = batchNotificationFactory.GetBatchNotifier(BatchNotificationType.StrategyCustomNotificationPublisher);
strategyNotificationPublisher = batchNotificationFactory.GetBatchNotifier(BatchNotificationType.StrategyNotificationPublisher);
strategyOrderBookPublisher = batchNotificationFactory.GetBatchNotifier(BatchNotificationType.StrategyOrderBookPublisher);
strategyTradePublisher = batchNotificationFactory.GetBatchNotifier(BatchNotificationType.StrategyTradePublisher);
strategyStatisticsPublisher = batchNotificationFactory.GetBatchNotifier(BatchNotificationType.StrategyStatisticsPublisher);
strategyCandlesticksPublisher = batchNotificationFactory.GetBatchNotifier(BatchNotificationType.StrategyCandlesticksPublisher);
strategyParameterUpdatePublisher = batchNotificationFactory.GetBatchNotifier(BatchNotificationType.StrategyParameterUpdatePublisher);
}
public async Task<Strategy> RunAsync(Strategy strategy, string localPath, CancellationToken cancellationToken)
{
if (strategy == null)
{
throw new ArgumentNullException(nameof(strategy));
}
this.cancellationToken = cancellationToken;
try
{
strategy.Status = StrategyStatus.Initialising;
Notify(NotificationLevel.Information, NotificationEventId.RunAsync, strategy, "Initialising strategy");
if (string.IsNullOrWhiteSpace(strategy.TargetAssembly))
{
Notify(NotificationLevel.Error, NotificationEventId.RunAsync, strategy, "No TargetAssembly");
return strategy;
}
if (string.IsNullOrWhiteSpace(strategy.TargetType))
{
Notify(NotificationLevel.Error, NotificationEventId.RunAsync, strategy, "No TargetType");
return strategy;
}
return await RunStrategyAsync(strategy, localPath).ConfigureAwait(false);
}
catch (Exception ex)
{
Notify(NotificationLevel.Error, NotificationEventId.RunAsync, strategy, ex.ToString());
throw;
}
}
internal async Task<Strategy> RunStrategyAsync(Strategy strategy, string localPath)
{
ITradeStrategy tradeStrategy = null;
try
{
Notify(NotificationLevel.Information, NotificationEventId.RunStrategyAsync, strategy, $"Loading {strategy.Name}");
var dependencies = GetAssemblies(localPath);
var assemblyLoader = new AssemblyLoader(localPath, dependencies);
var assembly = assemblyLoader.LoadFromMemoryStream(Path.Combine(localPath, strategy.TargetAssembly));
var type = assembly.GetType(strategy.TargetType);
dynamic obj = Activator.CreateInstance(type);
tradeStrategy = (ITradeStrategy)obj;
tradeStrategy.StrategyNotificationEvent += StrategyNotificationEvent;
tradeStrategy.StrategyAccountInfoEvent += StrategyAccountInfoEvent;
tradeStrategy.StrategyOrderBookEvent += StrategyOrderBookEvent;
tradeStrategy.StrategyTradeEvent += StrategyTradeEvent;
tradeStrategy.StrategyStatisticsEvent += StrategyStatisticsEvent;
tradeStrategy.StrategyCandlesticksEvent += StrategyCandlesticksEvent;
tradeStrategy.StrategyParameterUpdateEvent += StrategyParameterUpdateEvent;
tradeStrategy.StrategyCustomNotificationEvent += StrategyCustomNotificationEvent;
tradeStrategy.SetStrategy(strategy);
strategy.Status = StrategyStatus.Running;
if(tradeStrategyCacheManager.TryAddTradeStrategy(strategy.Name, tradeStrategy))
{
Notify(NotificationLevel.Information, NotificationEventId.RunStrategyAsync, strategy, $"Subscribing {strategy.Name}");
await subscriptionsCacheManager.Subscribe(strategy, tradeStrategy).ConfigureAwait(false);
Notify(NotificationLevel.Information, NotificationEventId.RunStrategyAsync, strategy, $"Running {strategy.Name}");
var result = await tradeStrategy.RunAsync(cancellationToken).ConfigureAwait(false);
if(!tradeStrategyCacheManager.TryRemoveTradeStrategy(strategy.Name, out ITradeStrategy ts))
{
Notify(NotificationLevel.Error, NotificationEventId.RunStrategyAsync, strategy, $"Failed to remove {strategy.Name} from the cache manager.");
}
}
else
{
Notify(NotificationLevel.Error, NotificationEventId.RunStrategyAsync, strategy, $"Failed to add {strategy.Name} to the cache manager.");
}
}
finally
{
if(tradeStrategy != null)
{
subscriptionsCacheManager.Unsubscribe(strategy, tradeStrategy);
tradeStrategy.StrategyNotificationEvent -= StrategyNotificationEvent;
tradeStrategy.StrategyAccountInfoEvent -= StrategyAccountInfoEvent;
tradeStrategy.StrategyOrderBookEvent -= StrategyOrderBookEvent;
tradeStrategy.StrategyTradeEvent -= StrategyTradeEvent;
tradeStrategy.StrategyParameterUpdateEvent -= StrategyParameterUpdateEvent;
tradeStrategy.StrategyCustomNotificationEvent -= StrategyCustomNotificationEvent;
}
// TODO: Unload target assembly and it's dependencies from memory and delete them.
}
return strategy;
}
private void StrategyNotificationEvent(object sender, StrategyNotificationEventArgs e)
{
strategyNotificationPublisher.AddNotification(e.StrategyNotification);
}
private void StrategyParameterUpdateEvent(object sender, StrategyNotificationEventArgs e)
{
strategyParameterUpdatePublisher.AddNotification(e.StrategyNotification);
}
private void StrategyAccountInfoEvent(object sender, StrategyNotificationEventArgs e)
{
strategyAccountInfoPublisher.AddNotification(e.StrategyNotification);
}
private void StrategyOrderBookEvent(object sender, StrategyNotificationEventArgs e)
{
strategyOrderBookPublisher.AddNotification(e.StrategyNotification);
}
private void StrategyTradeEvent(object sender, StrategyNotificationEventArgs e)
{
strategyTradePublisher.AddNotification(e.StrategyNotification);
}
private void StrategyStatisticsEvent(object sender, StrategyNotificationEventArgs e)
{
strategyStatisticsPublisher.AddNotification(e.StrategyNotification);
}
private void StrategyCandlesticksEvent(object sender, StrategyNotificationEventArgs e)
{
strategyCandlesticksPublisher.AddNotification(e.StrategyNotification);
}
private void StrategyCustomNotificationEvent(object sender, StrategyNotificationEventArgs e)
{
strategyCustomNotificationPublisher.AddNotification(e.StrategyNotification);
}
private void Notify(NotificationLevel notificationLevel, int notificationEvent, Strategy strategy, string message = "")
{
var strategyNotification = strategy.GetNotification(notificationLevel, notificationEvent, message);
strategyNotificationPublisher.AddNotification(strategyNotification);
strategyLogger.AddNotification(strategyNotification);
}
private static IList<string> GetAssemblies(string localPath)
{
var dependencies = new List<string>();
var files = Directory.GetFiles(localPath);
foreach (string filePath in files)
{
if(filePath.EndsWith(".pdb", StringComparison.OrdinalIgnoreCase))
{
continue;
}
var filePathSplit = filePath.Split('\\');
var fileName = filePathSplit[^1];
var name = fileName.Substring(0, fileName.LastIndexOf('.'));
dependencies.Add(name);
}
return dependencies;
}
}
}