Repository navigation
Expand file tree
/
Copy pathTemplateStudyPlugin.cs
More file actions
313 lines (261 loc) · 11.4 KB
/
Copy pathTemplateStudyPlugin.cs
File metadata and controls
313 lines (261 loc) · 11.4 KB
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using VisualHFT.Commons.PluginManager;
using VisualHFT.Commons.Helpers;
using VisualHFT.Enums;
using VisualHFT.Helpers;
using VisualHFT.Model;
using VisualHFT.PluginManager;
using VisualHFT.Studies.Template.Model;
using VisualHFT.Studies.Template.UserControls;
using VisualHFT.Studies.Template.ViewModel;
using VisualHFT.UserSettings;
using VisualHFT.Commons.Model;
namespace VisualHFT.Studies.Template
{
/// <summary>
/// Template for a study plugin. Implement IPlugin and derive from BasePluginStudy
/// to perform calculations on market data and push results into the VisualHFT framework.
/// </summary>
public class TemplateStudyPlugin : BasePluginStudy
{
#region Private Fields
private new bool _disposed = false; // to track whether the object has been disposed
private PlugInSettings _settings = new PlugInSettings();
// Study-specific data
private double _calculatedValue = 0;
private readonly object _lockObject = new object();
// Queue for non-blocking order book processing
private HelperCustomQueue<OrderBookSnapshot> _QUEUE;
#endregion
public TemplateStudyPlugin()
{
_QUEUE = new HelperCustomQueue<OrderBookSnapshot>($"<OrderBookSnapshot>_{this.Name}", QUEUE_onRead, QUEUE_onError);
}
~TemplateStudyPlugin()
{
Dispose(false);
}
#region IPlugin Implementation
public override async Task StartAsync()
{
await base.StartAsync(); // Call the base first
try
{
_QUEUE.Clear();
HelperOrderBook.Instance.Subscribe(OnOrderBookDataReceived);
log.Info($"{this.Name} Plugin has successfully started.");
Status = ePluginStatus.STARTED;
}
catch (Exception ex)
{
log.Error($"Error starting {Name} study plugin", ex);
Status = ePluginStatus.STOPPED_FAILED;
throw;
}
}
public override async Task StopAsync()
{
Status = ePluginStatus.STOPPING;
log.Info($"{this.Name} is stopping.");
try
{
HelperOrderBook.Instance.Unsubscribe(OnOrderBookDataReceived);
await base.StopAsync();
Status = ePluginStatus.STOPPED;
log.Info($"{this.Name} study plugin stopped successfully");
}
catch (Exception ex)
{
log.Error($"Error stopping {Name} study plugin", ex);
Status = ePluginStatus.STOPPED_FAILED;
}
}
#endregion
#region BasePluginStudy Implementation
public override string Name { get; set; } = "TemplateStudy";
public override string Version { get; set; } = "1.0.0";
public override string Description { get; set; } = "Template study plugin for custom calculations on market data.";
public override string Author { get; set; } = "Developer Name";
public override ISetting Settings { get => _settings; set => _settings = (PlugInSettings)value; }
public override string TileTitle { get; set; } = "Template Study";
public override string TileToolTip { get; set; } = "The <b>Template Study</b> performs custom calculations on market data.<br/><br/>" +
"This template demonstrates how to create study plugins that analyze market conditions.<br/>" +
"Override the calculation methods to implement your specific analysis logic.";
public override Action CloseSettingWindow { get; set; } = () => { };
public override event EventHandler<decimal>? OnAlertTriggered;
protected override void LoadSettings()
{
var loaded = LoadFromUserSettings<PlugInSettings>();
if (loaded == null)
{
InitializeDefaultSettings();
}
else
{
_settings = loaded;
}
if (_settings.Provider == null) //To prevent back compability with older setting formats
{
_settings.Provider = new Provider();
}
}
protected override void SaveSettings()
{
SaveToUserSettings(_settings);
}
protected override void InitializeDefaultSettings()
{
_settings = new PlugInSettings
{
Symbol = "BTC/USD",
Provider = new Provider { ProviderID = 1, ProviderName = "Default" },
AggregationLevel = AggregationLevel.None
};
}
private void OnOrderBookDataReceived(OrderBook orderBook)
{
/*
* ***************************************************************************************************
* TRANSFORM the incoming object (decouple it)
* DO NOT hold this call back, since other components depends on the speed of this specific call back.
* DO NOT BLOCK
* IDEALLY, USE QUEUES TO DECOUPLE
* ***************************************************************************************************
*/
if (orderBook == null)
return;
if (_settings.Provider.ProviderID != orderBook.ProviderID || _settings.Symbol != orderBook.Symbol)
return;
// Create a snapshot and enqueue for processing
var snapshot = OrderBookSnapshot.Create();
snapshot.UpdateFrom(orderBook);
_QUEUE.Add(snapshot);
}
private void QUEUE_onRead(OrderBookSnapshot snapshot)
{
// Process the order book snapshot
// TODO: Implement your study calculation logic here
// Example: Calculate a simple spread
if (snapshot.Bids.Length > 0 && snapshot.Asks.Length > 0)
{
var bestBid = snapshot.Bids[0];
var bestAsk = snapshot.Asks[0];
if (bestBid != null && bestAsk != null)
{
lock (_lockObject)
{
_calculatedValue = (bestAsk.Price ?? 0) - (bestBid.Price ?? 0);
}
DoCalculationAndSend();
}
}
// Dispose snapshot to return arrays to pool
snapshot.Dispose();
}
private void QUEUE_onError(Exception ex)
{
var _error = $"Unhandled error in the Queue: {ex.Message}";
log.Error(_error, ex);
HelperNotificationManager.Instance.AddNotification(this.Name, _error,
HelprNorificationManagerTypes.ERROR, HelprNorificationManagerCategories.PLUGINS, ex);
Task.Run(() => HandleRestart(_error, ex));
}
private void HandleRestart(string error, Exception ex)
{
try
{
log.Warn($"Restarting plugin due to error: {error}");
// TODO: Implement restart logic if needed
}
catch (Exception restartEx)
{
log.Error("Failed to restart plugin", restartEx);
}
}
private void DoCalculationAndSend()
{
if (Status != VisualHFT.PluginManager.ePluginStatus.STARTED) return;
var newItem = new BaseStudyModel();
newItem.Value = (decimal)_calculatedValue;
newItem.Timestamp = HelperTimeProvider.Now;
newItem.MarketMidPrice = 0; // Set if you have mid-price
AddCalculation(newItem);
// Check for alert conditions
CheckAlertCondition(_calculatedValue);
}
/// <summary>
/// Check if alert conditions are met
/// </summary>
/// <param name="value">Calculated value to check</param>
private void CheckAlertCondition(double value)
{
// TODO: Implement your alert conditions
// Example: Alert if spread is too wide
const double alertThreshold = 100.0;
if (value > alertThreshold)
{
OnAlertTriggered?.Invoke(this, (decimal)value);
}
}
/// <summary>
/// This method defines how the internal AggregatedCollection should aggregate incoming items.
/// It is invoked whenever a new item is added to the collection and aggregation is required.
/// The method takes the existing collection of items, the new incoming item, and a counter indicating
/// how many times the last item has been aggregated. The aggregation logic should be implemented
/// within this method to combine or process the items as needed.
/// </summary>
/// <param name="dataCollection">The existing internal collection of items.</param>
/// <param name="newItem">The new incoming item to be aggregated.</param>
/// <param name="lastItemAggregationCount">Counter indicating how many times the last item has been aggregated.</param>
protected override void onDataAggregation(List<BaseStudyModel> dataCollection, BaseStudyModel newItem, int lastItemAggregationCount)
{
//Aggregation: last
var existing = dataCollection[^1]; // Get the last item in the collection
existing.Value = newItem.Value;
existing.Timestamp = newItem.Timestamp;
existing.MarketMidPrice = newItem.MarketMidPrice;
base.onDataAggregation(dataCollection, newItem, lastItemAggregationCount);
}
#endregion
public override object GetUISettings()
{
PluginSettingsView view = new PluginSettingsView();
PluginSettingsViewModel viewModel = new PluginSettingsViewModel(_settings);
viewModel.UpdateSettingsFromUI = () =>
{
_settings.Symbol = viewModel.SelectedSymbol;
if (viewModel.SelectedProvider != null)
_settings.Provider = viewModel.SelectedProvider;
_settings.AggregationLevel = viewModel.AggregationLevelSelection;
_settings.TimePeriodMs = viewModel.TimePeriodMs;
_settings.MinVolumeThreshold = viewModel.MinVolumeThreshold;
_settings.AlertThreshold = viewModel.AlertThreshold;
_settings.EnableAlerts = viewModel.EnableAlerts;
_settings.CustomParameter1 = viewModel.CustomParameter1;
_settings.CustomParameter2 = viewModel.CustomParameter2;
SaveSettings();
};
view.DataContext = viewModel;
return view;
}
#region IDisposable
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// Dispose managed resources
CloseSettingWindow?.Invoke();
_QUEUE?.Dispose();
}
// Dispose unmanaged resources
_disposed = true;
}
base.Dispose(disposing);
}
#endregion
}
}