-
-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Expand file tree
/
Copy pathLiveTradingResultHandler.cs
More file actions
1287 lines (1126 loc) · 56 KB
/
Copy pathLiveTradingResultHandler.cs
File metadata and controls
1287 lines (1126 loc) · 56 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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using QuantConnect.Brokerages;
using QuantConnect.Configuration;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
using QuantConnect.Notifications;
using QuantConnect.Orders;
using QuantConnect.Packets;
using QuantConnect.Securities;
using QuantConnect.Securities.Positions;
using QuantConnect.Statistics;
using QuantConnect.Util;
namespace QuantConnect.Lean.Engine.Results
{
/// <summary>
/// Live trading result handler implementation passes the messages to the QC live trading interface.
/// </summary>
/// <remarks>Live trading result handler is quite busy. It sends constant price updates, equity updates and order/holdings updates.</remarks>
public class LiveTradingResultHandler : BaseResultsHandler, IResultHandler
{
// Required properties for the cloud app.
private LiveNodePacket _job;
//Update loop:
private DateTime _nextUpdate;
private DateTime _nextChartsUpdate;
private DateTime _nextChartTrimming;
private DateTime _nextLogStoreUpdate;
private DateTime _nextStatisticsUpdate;
private DateTime _nextInsightStoreUpdate;
private DateTime _currentUtcDate;
private readonly TimeSpan _storeInsightPeriod;
private DateTime _nextPortfolioMarginUpdate;
private DateTime _previousPortfolioMarginUpdate;
private readonly TimeSpan _samplePortfolioPeriod;
private readonly Chart _intradayPortfolioState = new(PortfolioMarginKey) { LegendDisabled = true };
/// <summary>
/// The earliest time of next dump to the status file
/// </summary>
private DateTime _nextStatusUpdate;
//Log Message Store:
private DateTime _nextSample;
private IApi _api;
private readonly CancellationTokenSource _cancellationTokenSource;
private readonly int _streamedChartLimit;
private readonly int _streamedChartGroupSize;
private bool _sampleChartAlways;
private bool _userExchangeIsOpen;
private DateTime _lastChartSampleLogicCheck;
private readonly Dictionary<string, SecurityExchangeHours> _exchangeHours;
/// <summary>
/// Creates a new instance
/// </summary>
public LiveTradingResultHandler()
{
_exchangeHours = new Dictionary<string, SecurityExchangeHours>();
_cancellationTokenSource = new CancellationTokenSource();
ResamplePeriod = TimeSpan.FromSeconds(2);
NotificationPeriod = TimeSpan.FromSeconds(1);
_samplePortfolioPeriod = _storeInsightPeriod = TimeSpan.FromMinutes(10);
_streamedChartLimit = Config.GetInt("streamed-chart-limit", 12);
_streamedChartGroupSize = Config.GetInt("streamed-chart-group-size", 3);
}
/// <summary>
/// Initialize the result handler with this result packet.
/// </summary>
/// <param name="parameters">DTO parameters class to initialize a result handler</param>
public override void Initialize(ResultHandlerInitializeParameters parameters)
{
_api = parameters.Api;
_job = (LiveNodePacket)parameters.Job;
if (_job == null) throw new Exception("LiveResultHandler.Constructor(): Submitted Job type invalid.");
var utcNow = DateTime.UtcNow;
_currentUtcDate = utcNow.Date;
_nextPortfolioMarginUpdate = utcNow.RoundDown(_samplePortfolioPeriod).Add(_samplePortfolioPeriod);
base.Initialize(parameters);
}
/// <summary>
/// Live trading result handler thread.
/// </summary>
protected override void Run()
{
// give the algorithm time to initialize, else we will log an error right away
ExitEvent.WaitOne(3000);
// -> 1. Run Primary Sender Loop: Continually process messages from queue as soon as they arrive.
while (!(ExitTriggered && Messages.IsEmpty))
{
try
{
//1. Process Simple Messages in Queue
Packet packet;
if (Messages.TryDequeue(out packet))
{
MessagingHandler.Send(packet);
}
//2. Update the packet scanner:
Update();
if (Messages.IsEmpty)
{
// prevent thread lock/tight loop when there's no work to be done
ExitEvent.WaitOne(Time.GetSecondUnevenWait(1000));
}
}
catch (Exception err)
{
Log.Error(err);
}
} // While !End.
Log.Trace("LiveTradingResultHandler.Run(): Ending Thread...");
} // End Run();
/// <summary>
/// Every so often send an update to the browser with the current state of the algorithm.
/// </summary>
private void Update()
{
//Error checks if the algorithm & threads have not loaded yet, or are closing down.
if (Algorithm?.Transactions == null || TransactionHandler.Orders == null || !Algorithm.GetLocked())
{
Log.Debug("LiveTradingResultHandler.Update(): Algorithm not yet initialized.");
ExitEvent.WaitOne(1000);
return;
}
if (ExitTriggered)
{
return;
}
var utcNow = DateTime.UtcNow;
if (utcNow > _nextUpdate)
{
try
{
Dictionary<int, Order> deltaOrders;
{
var stopwatch = Stopwatch.StartNew();
deltaOrders = GetDeltaOrders(LastDeltaOrderPosition, shouldStop: orderCount => stopwatch.ElapsedMilliseconds > 15);
}
var deltaOrderEvents = TransactionHandler.OrderEvents.Skip(LastDeltaOrderEventsPosition).Take(50).ToList();
LastDeltaOrderEventsPosition += deltaOrderEvents.Count;
//Create and send back the changes in chart since the algorithm started.
var deltaCharts = new Dictionary<string, Chart>();
var performanceCharts = new Dictionary<string, Chart>();
lock (ChartLock)
{
//Get the updates since the last chart
foreach (var chart in Charts)
{
var chartUpdates = chart.Value.GetUpdates();
// we only want to stream charts that have new updates
if (!chartUpdates.IsEmpty())
{
// remove directory pathing characters from chart names
var safeName = chart.Value.Name.Replace('/', '-');
DictionarySafeAdd(deltaCharts, safeName, chartUpdates, "deltaCharts");
}
if (AlgorithmPerformanceCharts.Contains(chart.Key))
{
performanceCharts[chart.Key] = chart.Value.Clone();
}
if (chartUpdates.Name == PortfolioMarginKey)
{
PortfolioMarginChart.RemoveSinglePointSeries(chartUpdates);
}
}
}
//Profit loss changes, get the banner statistics, summary information on the performance for the headers.
var serverStatistics = GetServerStatistics(utcNow);
var holdings = GetHoldings(Algorithm.Securities.Values, Algorithm.SubscriptionManager.SubscriptionDataConfigService);
//Add the algorithm statistics first.
var statistics = GenerateStatisticsResults(performanceCharts);
var runtimeStatistics = GetAlgorithmRuntimeStatistics(statistics.Summary);
AlgorithmPerformance algorithmPerformance;
{
var stopwatch = Stopwatch.StartNew();
var deltaTrades = GetDeltaTrades(statistics.TotalPerformance.ClosedTrades, LastTradeId, shouldStop: _ => stopwatch.ElapsedMilliseconds > 15);
algorithmPerformance = new AlgorithmPerformance(statistics.TotalPerformance) { ClosedTrades = deltaTrades };
}
// since we're sending multiple packets, let's do it async and forget about it
// chart data can get big so let's break them up into groups
var splitPackets = SplitPackets(deltaCharts, deltaOrders, holdings, Algorithm.Portfolio.CashBook, runtimeStatistics, serverStatistics, deltaOrderEvents, algorithmPerformance);
foreach (var liveResultPacket in splitPackets)
{
MessagingHandler.Send(liveResultPacket);
}
//Send full packet to storage.
if (utcNow > _nextChartsUpdate)
{
Log.Debug("LiveTradingResultHandler.Update(): Pre-store result");
var chartComplete = new Dictionary<string, Chart>();
lock (ChartLock)
{
foreach (var chart in Charts)
{
// remove directory pathing characters from chart names
var safeName = chart.Value.Name.Replace('/', '-');
DictionarySafeAdd(chartComplete, safeName, chart.Value.Clone(), "chartComplete");
}
}
var orderEvents = GetOrderEventsToStore();
var deltaStatistics = new Dictionary<string, string>();
var orders = new Dictionary<int, Order>(TransactionHandler.Orders);
var complete = new LiveResultPacket(_job, new LiveResult(new LiveResultParameters(chartComplete, orders,
Algorithm.Transactions.TransactionRecord, holdings, Algorithm.Portfolio.CashBook, deltaStatistics,
runtimeStatistics, orderEvents, statistics.TotalPerformance, serverStatistics, state: GetAlgorithmState())));
StoreResult(complete);
_nextChartsUpdate = DateTime.UtcNow.Add(ChartUpdateInterval);
Log.Debug("LiveTradingResultHandler.Update(): End-store result");
}
// Upload the logs every 1-2 minutes; this can be a heavy operation depending on amount of live logging and should probably be done asynchronously.
if (utcNow > _nextLogStoreUpdate)
{
List<LogEntry> logs;
Log.Debug("LiveTradingResultHandler.Update(): Storing log...");
lock (LogStore)
{
// we need a new container instance so we can store the logs outside the lock
logs = new List<LogEntry>(LogStore);
LogStore.Clear();
}
SaveLogs(AlgorithmId, logs);
_nextLogStoreUpdate = DateTime.UtcNow.AddMinutes(2);
Log.Debug("LiveTradingResultHandler.Update(): Finished storing log");
}
// Every minute send usage statistics:
if (utcNow > _nextStatisticsUpdate)
{
try
{
_api.SendStatistics(
_job.AlgorithmId,
Algorithm.Portfolio.TotalUnrealizedProfit,
Algorithm.Portfolio.TotalFees,
Algorithm.Portfolio.TotalNetProfit,
Algorithm.Portfolio.TotalHoldingsValue,
Algorithm.Portfolio.TotalPortfolioValue,
GetNetReturn(),
Algorithm.Portfolio.TotalSaleVolume,
TotalTradesCount(), 0);
}
catch (Exception err)
{
Log.Error(err, "Error sending statistics:");
}
_nextStatisticsUpdate = utcNow.AddMinutes(1);
}
if (utcNow > _nextStatusUpdate)
{
var chartComplete = new Dictionary<string, Chart>();
lock (ChartLock)
{
foreach (var chart in Charts)
{
// remove directory pathing characters from chart names
var safeName = chart.Value.Name.Replace('/', '-');
DictionarySafeAdd(chartComplete, safeName, chart.Value.Clone(), "chartComplete");
}
}
StoreStatusFile(
runtimeStatistics,
// only store holdings we are invested in
holdings.Where(pair => pair.Value.Quantity != 0).ToDictionary(pair => pair.Key, pair => pair.Value),
chartComplete,
GetAlgorithmState(),
new SortedDictionary<DateTime, decimal>(Algorithm.Transactions.TransactionRecord),
serverStatistics);
SetNextStatusUpdate();
}
if (_currentUtcDate != utcNow.Date)
{
StoreOrderEvents(_currentUtcDate, GetOrderEventsToStore());
// start storing in a new date file
_currentUtcDate = utcNow.Date;
}
if (utcNow > _nextChartTrimming)
{
Log.Debug("LiveTradingResultHandler.Update(): Trimming charts");
var timeLimitUtc = utcNow.AddDays(-2);
lock (ChartLock)
{
foreach (var chart in Charts)
{
foreach (var series in chart.Value.Series)
{
// trim data that's older than 2 days
series.Value.Values =
(from v in series.Value.Values
where v.Time > timeLimitUtc
select v).ToList();
}
}
}
_nextChartTrimming = DateTime.UtcNow.AddMinutes(10);
Log.Debug("LiveTradingResultHandler.Update(): Finished trimming charts");
}
if (utcNow > _nextInsightStoreUpdate)
{
StoreInsights();
_nextInsightStoreUpdate = DateTime.UtcNow.Add(_storeInsightPeriod);
}
}
catch (Exception err)
{
Log.Error(err, "LiveTradingResultHandler().Update(): ", true);
}
//Set the new update time after we've finished processing.
// The processing can takes time depending on how large the packets are.
_nextUpdate = DateTime.UtcNow.Add(MainUpdateInterval);
} // End Update Charts:
}
/// <summary>
/// Assigns the next earliest status update time
/// </summary>
protected virtual void SetNextStatusUpdate()
{
// Update the status json file every X
_nextStatusUpdate = DateTime.UtcNow.AddMinutes(10);
}
/// <summary>
/// Stores the order events
/// </summary>
/// <param name="utcTime">The utc date associated with these order events</param>
/// <param name="orderEvents">The order events to store</param>
protected override void StoreOrderEvents(DateTime utcTime, List<OrderEvent> orderEvents)
{
if (orderEvents.Count <= 0)
{
return;
}
var filename = $"{AlgorithmId}-{utcTime:yyyy-MM-dd}-order-events.json";
var path = GetResultsPath(filename);
var data = JsonConvert.SerializeObject(orderEvents, Formatting.None, SerializerSettings);
File.WriteAllText(path, data);
}
/// <summary>
/// Gets the order events generated in '_currentUtcDate'
/// </summary>
private List<OrderEvent> GetOrderEventsToStore()
{
return TransactionHandler.OrderEvents.Where(orderEvent => orderEvent.UtcTime >= _currentUtcDate).ToList();
}
/// <summary>
/// Will store the complete status of the algorithm in a single json file
/// </summary>
/// <remarks>Will sample charts every 12 hours, 2 data points per day at maximum,
/// to reduce file size</remarks>
private void StoreStatusFile(SortedDictionary<string, string> runtimeStatistics,
Dictionary<string, Holding> holdings,
Dictionary<string, Chart> chartComplete,
Dictionary<string, string> algorithmState,
SortedDictionary<DateTime, decimal> profitLoss,
Dictionary<string, string> serverStatistics = null,
StatisticsResults statistics = null)
{
try
{
Log.Debug("LiveTradingResultHandler.Update(): status update start...");
if (statistics == null)
{
statistics = GenerateStatisticsResults(chartComplete, profitLoss);
}
// sample the entire charts with a 12 hours resolution
var dailySampler = new SeriesSampler(TimeSpan.FromHours(12));
chartComplete = dailySampler.SampleCharts(chartComplete, Time.Start, Time.EndOfTime);
if (chartComplete.TryGetValue(PortfolioMarginKey, out var marginChart))
{
PortfolioMarginChart.RemoveSinglePointSeries(marginChart);
}
var result = new LiveResult(new LiveResultParameters(chartComplete,
new Dictionary<int, Order>(TransactionHandler.Orders),
Algorithm?.Transactions.TransactionRecord ?? new(),
holdings,
Algorithm?.Portfolio.CashBook ?? new(),
statistics: statistics.Summary,
runtimeStatistics: runtimeStatistics,
orderEvents: null, // we stored order events separately
serverStatistics: serverStatistics,
state: algorithmState));
SaveResults($"{AlgorithmId}.json", result);
Log.Debug("LiveTradingResultHandler.Update(): status update end.");
}
catch (Exception err)
{
Log.Error(err, "Error storing status update");
}
}
/// <summary>
/// Run over all the data and break it into smaller packets to ensure they all arrive at the terminal
/// </summary>
private IEnumerable<LiveResultPacket> SplitPackets(Dictionary<string, Chart> deltaCharts,
Dictionary<int, Order> deltaOrders,
Dictionary<string, Holding> holdings,
CashBook cashbook,
SortedDictionary<string, string> runtimeStatistics,
Dictionary<string, string> serverStatistics,
List<OrderEvent> deltaOrderEvents,
AlgorithmPerformance algorithmPerformance)
{
// break the charts into groups
var current = new Dictionary<string, Chart>();
var chartPackets = new List<LiveResultPacket>();
// First add send charts
// Loop through all the charts, add them to packets to be sent.
// Group three charts per packet
foreach (var deltaChart in deltaCharts.Values)
{
current.Add(deltaChart.Name, deltaChart);
if (current.Count >= _streamedChartGroupSize)
{
// Add the micro packet to transport.
chartPackets.Add(new LiveResultPacket(_job, new LiveResult { Charts = current }));
// Reset the carrier variable.
current = new Dictionary<string, Chart>();
if (chartPackets.Count * _streamedChartGroupSize >= _streamedChartLimit)
{
// stream a maximum number of charts
break;
}
}
}
// Add whatever is left over here too
// unless it is a wildcard subscription
if (current.Count > 0)
{
chartPackets.Add(new LiveResultPacket(_job, new LiveResult { Charts = current }));
}
// these are easier to split up, not as big as the chart objects
var packets = new[]
{
new LiveResultPacket(_job, new LiveResult { Holdings = holdings, CashBook = cashbook}),
new LiveResultPacket(_job, new LiveResult
{
RuntimeStatistics = runtimeStatistics,
ServerStatistics = serverStatistics
})
};
var result = packets.Concat(chartPackets);
// only send order and order event packet if there is actually any update
if (deltaOrders.Count > 0 || deltaOrderEvents.Count > 0)
{
result = result.Concat(new[] { new LiveResultPacket(_job, new LiveResult { Orders = deltaOrders, OrderEvents = deltaOrderEvents }) });
}
// only send trades packet if there is actually any update
if (algorithmPerformance.ClosedTrades != null && algorithmPerformance.ClosedTrades.Count > 0)
{
result = result.Concat(new[] { new LiveResultPacket(_job, new LiveResult { TotalPerformance = algorithmPerformance }) });
}
return result;
}
/// <summary>
/// Send a live trading debug message to the live console.
/// </summary>
/// <param name="message">Message we'd like shown in console.</param>
/// <remarks>When there are already 500 messages in the queue it stops adding new messages.</remarks>
public void DebugMessage(string message)
{
if (Messages.Count > 500) return; //if too many in the queue already skip the logging.
Messages.Enqueue(new DebugPacket(_job.ProjectId, AlgorithmId, CompileId, message));
AddToLogStore(message);
}
/// <summary>
/// Send a live trading system debug message to the live console.
/// </summary>
/// <param name="message">Message we'd like shown in console.</param>
public void SystemDebugMessage(string message)
{
Messages.Enqueue(new SystemDebugPacket(_job.ProjectId, AlgorithmId, CompileId, message));
AddToLogStore(message);
}
/// <summary>
/// Log string messages and send them to the console.
/// </summary>
/// <param name="message">String message wed like logged.</param>
/// <remarks>When there are already 500 messages in the queue it stops adding new messages.</remarks>
public void LogMessage(string message)
{
//Send the logging messages out immediately for live trading:
if (Messages.Count > 500) return;
Messages.Enqueue(new LogPacket(AlgorithmId, message));
AddToLogStore(message);
}
/// <summary>
/// Send an error message back to the browser console and highlight it read.
/// </summary>
/// <param name="message">Message we'd like shown in console.</param>
/// <param name="stacktrace">Stacktrace to show in the console.</param>
public void ErrorMessage(string message, string stacktrace = "")
{
if (Messages.Count > 500) return;
Messages.Enqueue(new HandledErrorPacket(AlgorithmId, message, stacktrace));
AddToLogStore(message + (!string.IsNullOrEmpty(stacktrace) ? ": StackTrace: " + stacktrace : string.Empty));
}
/// <summary>
/// Send a runtime error back to the users browser and highlight it red.
/// </summary>
/// <param name="message">Runtime error message</param>
/// <param name="stacktrace">Associated error stack trace.</param>
public virtual void RuntimeError(string message, string stacktrace = "")
{
Messages.Enqueue(new RuntimeErrorPacket(_job.UserId, AlgorithmId, message, stacktrace));
AddToLogStore(message + (!string.IsNullOrEmpty(stacktrace) ? ": StackTrace: " + stacktrace : string.Empty));
SetAlgorithmState(message, stacktrace);
}
/// <summary>
/// Process brokerage message events
/// </summary>
/// <param name="brokerageMessageEvent">The brokerage message event</param>
public virtual void BrokerageMessage(BrokerageMessageEvent brokerageMessageEvent)
{
// NOP
}
/// <summary>
/// Add a sample to the chart specified by the chartName, and seriesName.
/// </summary>
/// <param name="chartName">String chart name to place the sample.</param>
/// <param name="seriesName">Series name for the chart.</param>
/// <param name="seriesIndex">Series chart index - which chart should this series belong</param>
/// <param name="seriesType">Series type for the chart.</param>
/// <param name="value">Value for the chart sample.</param>
/// <param name="unit">Unit for the chart axis</param>
/// <remarks>Sample can be used to create new charts or sample equity - daily performance.</remarks>
protected override void Sample(string chartName, string seriesName, int seriesIndex, SeriesType seriesType, ISeriesPoint value,
string unit = "$")
{
// Sampling during warming up period skews statistics
if (Algorithm.IsWarmingUp)
{
return;
}
lock (ChartLock)
{
//Add a copy locally:
if (!Charts.TryGetValue(chartName, out var chart))
{
Charts.AddOrUpdate(chartName, new Chart(chartName));
chart = Charts[chartName];
}
//Add the sample to our chart:
if (!chart.Series.TryGetValue(seriesName, out var series))
{
series = BaseSeries.Create(seriesType, seriesName, seriesIndex, unit);
chart.Series.Add(seriesName, series);
}
//Add our value:
series.Values.Add(value);
}
}
/// <summary>
/// Add a range of samples from the users algorithms to the end of our current list.
/// </summary>
/// <param name="updates">Chart updates since the last request.</param>
/// <seealso cref="Sample(string,string,int,SeriesType,ISeriesPoint,string)"/>
protected void SampleRange(IEnumerable<Chart> updates)
{
lock (ChartLock)
{
foreach (var update in updates)
{
//Create the chart if it doesn't exist already:
Chart chart;
if (!Charts.TryGetValue(update.Name, out chart))
{
chart = new Chart(update.Name);
Charts.AddOrUpdate(update.Name, chart);
}
//Add these samples to this chart.
foreach (BaseSeries series in update.Series.Values)
{
if (series.Values.Count > 0)
{
var thisSeries = chart.TryAddAndGetSeries(series.Name, series, forceAddNew: false);
if (series.SeriesType == SeriesType.Pie)
{
var dataPoint = series.ConsolidateChartPoints();
if (dataPoint != null)
{
thisSeries.AddPoint(dataPoint);
}
}
else
{
//We already have this record, so just the new samples to the end:
thisSeries.Values.AddRange(series.Values);
}
}
}
}
}
}
/// <summary>
/// Set the algorithm of the result handler after its been initialized.
/// </summary>
/// <param name="algorithm">Algorithm object matching IAlgorithm interface</param>
/// <param name="startingPortfolioValue">Algorithm starting capital for statistics calculations</param>
public override void SetAlgorithm(IAlgorithm algorithm, decimal startingPortfolioValue)
{
base.SetAlgorithm(algorithm, startingPortfolioValue);
Algorithm.SetStatisticsService(this);
// we need to forward Console.Write messages to the algorithm's Debug function
var debug = new FuncTextWriter(algorithm.Debug);
var error = new FuncTextWriter(algorithm.Error);
Console.SetOut(debug);
Console.SetError(error);
UpdateAlgorithmStatus();
}
/// <summary>
/// Send a algorithm status update to the user of the algorithms running state.
/// </summary>
/// <param name="status">Status enum of the algorithm.</param>
/// <param name="message">Optional string message describing reason for status change.</param>
public void SendStatusUpdate(AlgorithmStatus status, string message = "")
{
Log.Trace($"LiveTradingResultHandler.SendStatusUpdate(): status: '{status}'. {(string.IsNullOrEmpty(message) ? string.Empty : " " + message)}");
var packet = new AlgorithmStatusPacket(_job.AlgorithmId, _job.ProjectId, status, message);
Messages.Enqueue(packet);
}
/// <summary>
/// Set a dynamic runtime statistic to show in the (live) algorithm header
/// </summary>
/// <param name="key">Runtime headline statistic name</param>
/// <param name="value">Runtime headline statistic value</param>
public void RuntimeStatistic(string key, string value)
{
Log.Debug("LiveTradingResultHandler.RuntimeStatistic(): Begin setting statistic");
lock (RuntimeStatistics)
{
if (!RuntimeStatistics.ContainsKey(key))
{
RuntimeStatistics.Add(key, value);
}
RuntimeStatistics[key] = value;
}
Log.Debug("LiveTradingResultHandler.RuntimeStatistic(): End setting statistic");
}
/// <summary>
/// Send a final analysis result back to the IDE.
/// </summary>
protected void SendFinalResult()
{
Log.Trace("LiveTradingResultHandler.SendFinalResult(): Starting...");
try
{
var endTime = DateTime.UtcNow;
var endState = GetAlgorithmState(endTime);
LiveResultPacket result;
// could happen if algorithm failed to init
if (Algorithm != null)
{
//Convert local dictionary:
var charts = new Dictionary<string, Chart>();
lock (ChartLock)
{
foreach (var kvp in Charts)
{
charts.Add(kvp.Key, kvp.Value.Clone());
}
}
var orders = new Dictionary<int, Order>(TransactionHandler.Orders);
var profitLoss = new SortedDictionary<DateTime, decimal>(Algorithm.Transactions.TransactionRecord);
var holdings = GetHoldings(Algorithm.Securities.Values, Algorithm.SubscriptionManager.SubscriptionDataConfigService, onlyInvested: true);
var statisticsResults = GenerateStatisticsResults(charts, profitLoss);
var runtime = GetAlgorithmRuntimeStatistics(statisticsResults.Summary);
StoreStatusFile(runtime, holdings, charts, endState, profitLoss, statistics: statisticsResults);
//Create a packet:
result = new LiveResultPacket(_job,
new LiveResult(new LiveResultParameters(charts, orders, profitLoss, new Dictionary<string, Holding>(),
Algorithm.Portfolio.CashBook, statisticsResults.Summary, runtime, GetOrderEventsToStore(),
algorithmConfiguration: AlgorithmConfiguration.Create(Algorithm, null), state: endState, totalPerformance: statisticsResults.TotalPerformance)));
}
else
{
StoreStatusFile(new(), new(), new(), endState, new());
result = LiveResultPacket.CreateEmpty(_job);
result.Results.State = endState;
}
StoreInsights();
//Store to S3:
StoreResult(result);
Log.Trace("LiveTradingResultHandler.SendFinalResult(): Finished storing results. Start sending...");
//Truncate packet to fit within 32kb:
result.Results = new LiveResult();
//Send the truncated packet:
MessagingHandler.Send(result);
}
catch (Exception err)
{
Log.Error(err);
}
Log.Trace("LiveTradingResultHandler.SendFinalResult(): Ended");
}
/// <summary>
/// Process the log entries and save it to permanent storage
/// </summary>
/// <param name="id">Id that will be incorporated into the algorithm log name</param>
/// <param name="logs">Log list</param>
/// <returns>Returns the location of the logs</returns>
public override string SaveLogs(string id, List<LogEntry> logs)
{
try
{
var logLines = logs.Select(x => x.Message);
var filename = $"{id}-log.txt";
var path = GetResultsPath(filename);
File.AppendAllLines(path, logLines);
return path;
}
catch (Exception err)
{
Log.Error(err);
}
return "";
}
/// <summary>
/// Save the snapshot of the total results to storage.
/// </summary>
/// <param name="packet">Packet to store.</param>
protected override void StoreResult(Packet packet)
{
try
{
Log.Debug("LiveTradingResultHandler.StoreResult(): Begin store result sampling");
// Make sure this is the right type of packet:
if (packet.Type != PacketType.LiveResult) return;
// Port to packet format:
var live = packet as LiveResultPacket;
if (live != null)
{
if (live.Results.OrderEvents != null)
{
// we store order events separately
StoreOrderEvents(_currentUtcDate, live.Results.OrderEvents);
// lets null the orders events so that they aren't stored again and generate a giant file
live.Results.OrderEvents = null;
}
// we need to down sample
var start = DateTime.UtcNow.Date;
var stop = start.AddDays(1);
// truncate to just today, we don't need more than this for anyone
Truncate(live.Results, start, stop);
var highResolutionCharts = new Dictionary<string, Chart>(live.Results.Charts);
// minute resolution data, save today
var minuteSampler = new SeriesSampler(TimeSpan.FromMinutes(1));
var minuteCharts = minuteSampler.SampleCharts(live.Results.Charts, start, stop);
// swap out our charts with the sampled data
minuteCharts.Remove(PortfolioMarginKey);
live.Results.Charts = minuteCharts;
var totalPerformance = live.Results.TotalPerformance;
live.Results.TotalPerformance = null; // we don't need to save this in minute data
SaveResults(CreateKey("minute"), live.Results);
// restore total performance
live.Results.TotalPerformance = totalPerformance;
// 10 minute resolution data, save today
var tenminuteSampler = new SeriesSampler(TimeSpan.FromMinutes(10));
var tenminuteCharts = tenminuteSampler.SampleCharts(live.Results.Charts, start, stop);
lock (_intradayPortfolioState)
{
var clone = _intradayPortfolioState.Clone();
PortfolioMarginChart.RemoveSinglePointSeries(clone);
tenminuteCharts[PortfolioMarginKey] = clone;
}
live.Results.Charts = tenminuteCharts;
SaveResults(CreateKey("10minute"), live.Results);
// high resolution data, we only want to save an hour
highResolutionCharts.Remove(PortfolioMarginKey);
live.Results.Charts = highResolutionCharts;
start = DateTime.UtcNow.RoundDown(TimeSpan.FromHours(1));
stop = DateTime.UtcNow.RoundUp(TimeSpan.FromHours(1));
Truncate(live.Results, start, stop);
foreach (var name in live.Results.Charts.Keys)
{
var result = new LiveResult
{
Orders = new Dictionary<int, Order>(live.Results.Orders),
Holdings = new Dictionary<string, Holding>(live.Results.Holdings),
Charts = new Dictionary<string, Chart> { { name, live.Results.Charts[name] } }
};
SaveResults(CreateKey("second_" + CreateSafeChartName(name), "yyyy-MM-dd-HH"), result);
}
}
else
{
Log.Error("LiveResultHandler.StoreResult(): Result Null.");
}
Log.Debug("LiveTradingResultHandler.StoreResult(): End store result sampling");
}
catch (Exception err)
{
Log.Error(err);
}
}
/// <summary>
/// New order event for the algorithm
/// </summary>
/// <param name="newEvent">New event details</param>
public override void OrderEvent(OrderEvent newEvent)
{
var brokerIds = string.Empty;
var order = TransactionHandler.GetOrderById(newEvent.OrderId);
if (order != null && order.BrokerId.Count > 0) brokerIds = string.Join(", ", order.BrokerId);
//Send the message to frontend as packet:
Log.Trace("LiveTradingResultHandler.OrderEvent(): " + newEvent + " BrokerId: " + brokerIds, true);
Messages.Enqueue(new OrderEventPacket(AlgorithmId, newEvent));
var message = "New Order Event: " + newEvent;
DebugMessage(message);
}
/// <summary>
/// Terminate the result thread and apply any required exit procedures like sending final results
/// </summary>
public override void Exit()
{
if (!ExitTriggered)
{
_cancellationTokenSource.Cancel();
if (Algorithm != null)
{
// first process synchronous events so we add any new message or log
ProcessSynchronousEvents(true);
}
// Set exit flag, update task will send any message before stopping
ExitTriggered = true;
ExitEvent.Set();
lock (LogStore)
{
SaveLogs(AlgorithmId, LogStore);
LogStore.Clear();
}
StopUpdateRunner();
SendFinalResult();
base.Exit();
_cancellationTokenSource.DisposeSafely();
}
}
/// <summary>
/// Truncates the chart and order data in the result packet to within the specified time frame
/// </summary>
private static void Truncate(LiveResult result, DateTime start, DateTime stop)
{
//Log.Trace("LiveTradingResultHandler.Truncate: Start: " + start.ToString("u") + " Stop : " + stop.ToString("u"));
//Log.Trace("LiveTradingResultHandler.Truncate: Truncate Delta: " + (unixDateStop - unixDateStart) + " Incoming Points: " + result.Charts["Strategy Equity"].Series["Equity"].Values.Count);
var charts = new Dictionary<string, Chart>();
foreach (var kvp in result.Charts)
{
var chart = kvp.Value;
var newChart = new Chart(chart.Name);
charts.Add(kvp.Key, newChart);
foreach (var series in chart.Series.Values)
{
var newSeries = series.Clone(empty: true);
newSeries.Values.AddRange(series.Values.Where(chartPoint => chartPoint.Time >= start && chartPoint.Time <= stop));
newChart.AddSeries(newSeries);
}
}