forked from QuantConnect/Lean
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAlgorithmManager.cs
More file actions
1045 lines (917 loc) · 49.4 KB
/
AlgorithmManager.cs
File metadata and controls
1045 lines (917 loc) · 49.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
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.Linq;
using System.Threading;
using Fasterflect;
using QuantConnect.Util;
using QuantConnect.Algorithm;
using QuantConnect.Configuration;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Lean.Engine.RealTime;
using QuantConnect.Lean.Engine.Results;
using QuantConnect.Lean.Engine.Server;
using QuantConnect.Lean.Engine.TransactionHandlers;
using QuantConnect.Logging;
using QuantConnect.Orders;
using QuantConnect.Packets;
using QuantConnect.Securities;
using QuantConnect.Securities.Option;
using QuantConnect.Securities.Volatility;
using QuantConnect.Util.RateLimit;
namespace QuantConnect.Lean.Engine
{
/// <summary>
/// Algorithm manager class executes the algorithm and generates and passes through the algorithm events.
/// </summary>
public class AlgorithmManager
{
private IAlgorithm _algorithm;
private readonly object _lock;
private readonly bool _liveMode;
private bool _cancelRequested;
private PerformanceTrackingTool _performanceTrackingTool;
private CancellationTokenSource _cancellationTokenSource;
/// <summary>
/// Publicly accessible algorithm status
/// </summary>
public AlgorithmStatus State => _algorithm?.Status ?? AlgorithmStatus.Running;
/// <summary>
/// Public access to the currently running algorithm id.
/// </summary>
public string AlgorithmId { get; private set; }
/// <summary>
/// Provides the isolator with a function for verifying that we're not spending too much time in each
/// algorithm manager time loop
/// </summary>
public AlgorithmTimeLimitManager TimeLimit { get; }
/// <summary>
/// Quit state flag for the running algorithm. When true the user has requested the backtest stops through a Quit() method.
/// </summary>
/// <seealso cref="QCAlgorithm.Quit(String)"/>
public bool QuitState => State == AlgorithmStatus.Deleted;
/// <summary>
/// Gets the number of data points processed per second
/// </summary>
public long DataPoints => _performanceTrackingTool?.DataPoints ?? 0;
/// <summary>
/// Gets the number of data points of algorithm history provider
/// </summary>
public int AlgorithmHistoryDataPoints => _performanceTrackingTool?.HistoryDataPoints ?? 0;
/// <summary>
/// Initializes a new instance of the <see cref="AlgorithmManager"/> class
/// </summary>
/// <param name="liveMode">True if we're running in live mode, false for backtest mode</param>
/// <param name="job">Provided by LEAN when creating a new algo manager. This is the job
/// that the algo manager is about to execute. Research and other consumers can provide the
/// default value of null</param>
public AlgorithmManager(bool liveMode, AlgorithmNodePacket job = null)
{
AlgorithmId = "";
_liveMode = liveMode;
_lock = new object();
// initialize the time limit manager
TimeLimit = new AlgorithmTimeLimitManager(
CreateTokenBucket(job?.Controls?.TrainingLimits),
TimeSpan.FromMinutes(Config.GetDouble("algorithm-manager-time-loop-maximum", 20))
);
}
/// <summary>
/// Launch the algorithm manager to run this strategy
/// </summary>
/// <param name="job">Algorithm job</param>
/// <param name="algorithm">Algorithm instance</param>
/// <param name="synchronizer">Instance which implements <see cref="ISynchronizer"/>. Used to stream the data</param>
/// <param name="transactions">Transaction manager object</param>
/// <param name="results">Result handler object</param>
/// <param name="realtime">Realtime processing object</param>
/// <param name="leanManager">ILeanManager implementation that is updated periodically with the IAlgorithm instance</param>
/// <param name="cancellationTokenSource">Cancellation token source to monitor</param>
/// <remarks>Modify with caution</remarks>
public void Run(AlgorithmNodePacket job, IAlgorithm algorithm, ISynchronizer synchronizer, ITransactionHandler transactions, IResultHandler results, IRealTimeHandler realtime,
ILeanManager leanManager, CancellationTokenSource cancellationTokenSource, PerformanceTrackingTool performanceTrackingTool)
{
//Initialize:
_algorithm = algorithm;
_performanceTrackingTool = performanceTrackingTool;
var token = cancellationTokenSource.Token;
_cancellationTokenSource = cancellationTokenSource;
var backtestMode = (job.Type == PacketType.BacktestNode);
var methodInvokers = new Dictionary<Type, MethodInvoker>();
var marginCallFrequency = TimeSpan.FromMinutes(5);
var nextMarginCallTime = DateTime.MinValue;
var nextSecurityModelScan = algorithm.UtcTime.RoundDown(Time.OneHour) + Time.OneHour;
var time = algorithm.StartDate.Date;
var pendingDelistings = new List<Delisting>();
var splitWarnings = new List<Split>();
//Initialize Properties:
AlgorithmId = job.AlgorithmId;
//Go through the subscription types and create invokers to trigger the event handlers for each custom type:
foreach (var config in algorithm.SubscriptionManager.Subscriptions)
{
//If type is a custom feed, check for a dedicated event handler
if (config.IsCustomData)
{
//Get the matching method for this event handler - e.g. public void OnData(Quandl data) { .. }
var genericMethod = (algorithm.GetType()).GetMethod("OnData", new[] { config.Type });
//If we already have this Type-handler then don't add it to invokers again.
if (methodInvokers.ContainsKey(config.Type)) continue;
if (genericMethod != null)
{
methodInvokers.Add(config.Type, genericMethod.DelegateForCallMethod());
}
}
}
// Schedule a daily event for sampling at midnight every night
algorithm.Schedule.On("Daily Sampling", algorithm.Schedule.DateRules.EveryDay(),
algorithm.Schedule.TimeRules.Midnight, () =>
{
results.Sample(algorithm.UtcTime);
});
//Loop over the queues: get a data collection, then pass them all into relevent methods in the algorithm.
Log.Trace($"AlgorithmManager.Run(): Begin DataStream - Start: {algorithm.StartDate} Stop: {algorithm.EndDate} Time: {algorithm.Time} Warmup: {algorithm.IsWarmingUp}");
foreach (var timeSlice in Stream(algorithm, synchronizer, results, token))
{
// reset our timer on each loop
TimeLimit.StartNewTimeStep();
//Check this backtest is still running:
if (_algorithm.Status != AlgorithmStatus.Running && _algorithm.RunTimeError == null)
{
Log.Error($"AlgorithmManager.Run(): Algorithm state changed to {_algorithm.Status} at {timeSlice.Time.ToStringInvariant()}");
break;
}
//Execute with TimeLimit Monitor:
if (token.IsCancellationRequested)
{
Log.Error($"AlgorithmManager.Run(): CancellationRequestion at {timeSlice.Time.ToStringInvariant()}");
return;
}
// Update the ILeanManager
leanManager.Update();
time = timeSlice.Time;
performanceTrackingTool.Sample(timeSlice.DataPointCount, time);
if (backtestMode && algorithm.Portfolio.TotalPortfolioValue <= 0)
{
var logMessage = "AlgorithmManager.Run(): Portfolio value is less than or equal to zero, stopping algo
46C5
rithm.";
Log.Error(logMessage);
results.SystemDebugMessage(logMessage);
break;
}
// If backtesting/warmup, we need to check if there are realtime events in the past
// which didn't fire because at the scheduled times there was no data (i.e. markets closed)
// and fire them with the correct date/time.
performanceTrackingTool.Start(PerformanceTarget.Schedule);
realtime.ScanPastEvents(time);
performanceTrackingTool.Stop(PerformanceTarget.Schedule);
// will scan registered consolidators for which we've past the expected scan call.
// In live mode we want to round down to the second, so we don't scan too far into the future:
// The time slice might carry the data needed to complete a current consolidated bar but the
// time slice time might be slightly ahead (a few milliseconds or even ticks) because in live we
// use DateTime.UtcNow. So we don't want to scan past the data time so that the consolidators can
// complete the current bar.
var pastConsolidatorsScanTime = _liveMode ? time.RoundDown(Time.OneSecond) : time;
performanceTrackingTool.Start(PerformanceTarget.Consolidators);
algorithm.SubscriptionManager.ScanPastConsolidators(pastConsolidatorsScanTime, algorithm);
performanceTrackingTool.Stop(PerformanceTarget.Consolidators);
performanceTrackingTool.Start(PerformanceTarget.Securities);
//Set the algorithm and real time handler's time
algorithm.SetDateTime(time);
// the time pulse are just to advance algorithm time, lets shortcut the loop here
if (timeSlice.IsTimePulse)
{
continue;
}
// Update the current slice before firing scheduled events or any other task
algorithm.SetCurrentSlice(timeSlice.Slice);
if (timeSlice.SecurityChanges != SecurityChanges.None)
{
algorithm.ProcessSecurityChanges(timeSlice.SecurityChanges);
leanManager.OnSecuritiesChanged(timeSlice.SecurityChanges);
realtime.OnSecuritiesChanged(timeSlice.SecurityChanges);
results.OnSecuritiesChanged(timeSlice.SecurityChanges);
}
//Update the securities properties: first before calling user code to avoid issues with data
foreach (var update in timeSlice.SecuritiesUpdateData)
{
var security = update.Target;
security.Update(update.Data, update.DataType, update.ContainsFillForwardData, update.IsInternalConfig);
// Send market price updates to the TradeBuilder
algorithm.TradeBuilder.SetMarketPrice(security.Symbol, security.Price);
}
// TODO: potentially push into a scheduled event
if (time >= nextSecurityModelScan)
{
foreach (var security in algorithm.Securities.Values)
{
security.MarginInterestRateModel.ApplyMarginInterestRate(new MarginInterestRateParameters(security, time));
// perform check for settlement of unsettled funds
security.SettlementModel.Scan(new ScanSettlementModelParameters(algorith
C503
m.Portfolio, security, time));
}
nextSecurityModelScan = time.RoundDown(Time.OneHour) + Time.OneHour;
}
//Update the securities properties with any universe data
if (timeSlice.UniverseData.Count > 0)
{
foreach (var dataCollection in timeSlice.UniverseData.Values)
{
if (!dataCollection.ShouldCacheToSecurity()) continue;
foreach (var data in dataCollection.Data)
{
if (algorithm.Securities.TryGetValue(data.Symbol, out var security))
{
security.Cache.StoreData(new[] { data }, data.GetType());
}
}
}
}
// poke each cash object to update from the recent security data
foreach (var cash in algorithm.Portfolio.CashBook.Values.Where(x => x.CurrencyConversion != null))
{
cash.Update();
}
// security prices got updated
algorithm.Portfolio.InvalidateTotalPortfolioValue();
if (timeSlice.Slice.SymbolChangedEvents.Count != 0)
{
try
{
algorithm.OnSymbolChangedEvents(timeSlice.Slice.SymbolChangedEvents);
}
catch (Exception err)
{
algorithm.SetRuntimeError(err, "OnSymbolChangedEvents");
return;
}
foreach (var symbol in timeSlice.Slice.SymbolChangedEvents.Keys)
{
// cancel all orders for the old symbol
foreach (var ticket in transactions.GetOpenOrderTickets(x => x.Symbol == symbol))
{
ticket.Cancel("Open order cancelled on symbol changed event");
}
}
}
performanceTrackingTool.Stop(PerformanceTarget.Securities);
// process fill models on the updated data before entering algorithm, applies to all non-market orders
performanceTrackingTool.Start(PerformanceTarget.Transactions);
transactions.ProcessSynchronousEvents();
performanceTrackingTool.Stop(PerformanceTarget.Transactions);
// fire real time events after we've updated based on the new data
performanceTrackingTool.Start(PerformanceTarget.Schedule);
realtime.SetTime(timeSlice.Time);
performanceTrackingTool.Stop(PerformanceTarget.Schedule);
// process split warnings for options
performanceTrackingTool.Start(PerformanceTarget.SplitsDividendsDelisting);
ProcessSplitSymbols(algorithm, splitWarnings, pendingDelistings);
performanceTrackingTool.Stop(PerformanceTarget.SplitsDividendsDelisting);
//Check if the user's signalled Quit: loop over data until day changes.
if (_algorithm.Status != AlgorithmStatus.Running && _algorithm.RunTimeError == null)
{
Log.Error($"AlgorithmManager.Run(): Algorithm state changed to {_algorithm.Status} at {timeSlice.Time.ToStringInvariant()}");
break;
}
if (algorithm.RunTimeError != null)
{
Log.Error($"AlgorithmManager.Run(): Stopping, encountered a runtime error at {algorithm.UtcTime} UTC.");
return;
}
// perform margin calls, in live mode we can also use realtime to emit these
if (time >= nextMarginCallTime || (_liveMode && nextMarginCallTime > DateTime.UtcNow))
{
// determine if there are possible margin call orders to be executed
bool issueMarginCallWarning;
var marginCallOrders = algorithm.Portfolio.MarginCallModel.GetMarginCallOrders(out issueMarginCallWarning);
var executedTicketsCount = 0;
if (marginCallOrders.Count != 0)
{
var executingMarginCall = false;
try
{
if (marginCallOrders.All(order => algorithm.Portfolio.Securities[order.Symbol].Exchange.ExchangeOpen))
{
// tell the algorithm we're about to issue the margin call
algorithm.OnMarginCall(marginCallOrders);
// execute the margin call orders
var executedTickets = algorithm.Portfolio.MarginCallModel.ExecuteMarginCall(marginCallOrders);
executedTicketsCount = executedTickets.Count;
foreach (var ticket in executedTickets)
{
algorithm.Error($"{algorithm.Time.ToStringInvariant()} - Executed MarginCallOrder: {ticket.Symbol} - " +
$"Quantity: {ticket.Quantity.ToStringInvariant()} @ {ticket.AverageFillPrice.ToStringInvariant()}"
);
}
}
}
catch (Exception err)
{
algorithm.SetRuntimeError(err, executingMarginCall ? "Portfolio.MarginCallModel.ExecuteMarginCall" : "OnMarginCall");
return;
}
}
// we didn't perform a margin call, but got the warning flag back, so issue the warning to the algorithm
if (executedTicketsCount == 0 && issueMarginCallWarning)
{
try
{
algorithm.OnMarginCallWarning();
}
catch (Exception err)
{
algorithm.SetRuntimeError(err, "OnMarginCallWarning");
return;
}
}
nextMarginCallTime = time + marginCallFrequency;
}
// before we call any events, let the algorithm know about universe changes
if (timeSlice.SecurityChanges != SecurityChanges.None)
{
try
{
var algorithmSecurityChanges = new SecurityChanges(timeSlice.SecurityChanges)
{
// by default for user code we want to filter out custom securities
FilterCustomSecurities = true,
// by default for user code we want to filter out internal securities
FilterInternalSecurities = true
};
algorithm.OnSecuritiesChanged(algorithmSecurityChanges);
algorithm.OnFrameworkSecuritiesChanged(algorithmSecurityChanges);
}
catch (Exception err)
{
algorithm.SetRuntimeError(err, "OnSecuritiesChanged");
return;
}
}
performanceTrackingTool.Start(PerformanceTarget.SplitsDividendsDelisting);
// apply dividends
HandleDividends(timeSlice, algorithm, _liveMode);
// apply splits
HandleSplits(timeSlice, algorithm, _liveMode);
performanceTrackingTool.Stop(PerformanceTarget.SplitsDividendsDelisting);
//Update registered consolidators for this symbol index
performanceTrackingTool.Start(PerformanceTarget.Consolidators);
try
{
if (timeSlice.ConsolidatorUpdateData.Count > 0)
{
var timeKeeper = algorithm.TimeKeeper;
foreach (var update in timeSlice.ConsolidatorUpdateData)
{
var localTime = timeKeeper.GetLocalTimeKeeper(update.Target.ExchangeTimeZone).LocalTime;
var consolidators = update.Target.Consolidators;
foreach (var consolidator in consolidators)
{
foreach (var dataPoint in update.Data)
{
consolidator.Update(dataPoint);
}
// scan for time after we've pumped all the data through for this consolidator
consolidator.Scan(localTime);
}
}
}
}
catch (Exception err)
{
algorithm.SetRuntimeError(err, "Consolidators update");
return;
}
performanceTrackingTool.Stop(PerformanceTarget.Consolidators);
// fire custom event handlers
foreach (var update in timeSlice.CustomData)
{
MethodInvoker methodInvoker;
if (!methodInvokers.TryGetValue(update.DataType, out methodInvoker))
{
continue;
}
try
{
foreach (var dataPoint in update.Data)
{
if (update.DataType.IsInstanceOfType(dataPoint))
{
methodInvoker(algorithm, dataPoint);
}
}
}
catch (Exception err)
{
algorithm.SetRuntimeError(err, "Custom Data");
return;
}
}
performanceTrackingTool.Start(PerformanceTarget.SplitsDividendsDelisting);
try
{
if (timeSlice.Slice.Splits.Count != 0)
{
algorithm.OnSplits(timeSlice.Slice.Splits);
}
}
catch (Exception err)
{
algorithm.SetRuntimeError(err, "OnSplits");
return;
}
try
{
if (timeSlice.Slice.Dividends.Count != 0)
{
algorithm.OnDividends(timeSlice.Slice.Dividends);
}
}
catch (Exception err)
{
algorithm.SetRuntimeError(err, "OnDividends");
return;
}
try
{
if (timeSlice.Slice.Delistings.Count != 0)
{
algorithm.OnDelistings(timeSlice.Slice.Delistings);
}
C503
}
catch (Exception err)
{
algorithm.SetRuntimeError(err, "OnDelistings");
return;
}
// Only track pending delistings in non-live mode.
if (!algorithm.LiveMode)
{
// Keep this up to date even though we don't process delistings here anymore
foreach (var delisting in timeSlice.Slice.Delistings.Values)
{
if (delisting.Type == DelistingType.Warning)
{
// Store our delistings warnings because they are still used by ProcessSplitSymbols above
pendingDelistings.Add(delisting);
}
else
{
// If we have an actual delisting event, remove it from pending delistings
var index = pendingDelistings.FindIndex(x => x.Symbol == delisting.Symbol);
if (index != -1)
{
pendingDelistings.RemoveAt(index);
}
}
}
}
// run split logic after firing split events
HandleSplitSymbols(timeSlice.Slice.Splits, splitWarnings);
performanceTrackingTool.Stop(PerformanceTarget.SplitsDividendsDelisting);
try
{
performanceTrackingTool.Start(PerformanceTarget.OnData);
if (timeSlice.Slice.HasData)
{
// EVENT HANDLER v3.0 -- all data in a single event
algorithm.OnData(algorithm.CurrentSlice);
}
// always turn the crank on this method to ensure universe selection models function properly on day changes w/out data
algorithm.OnFrameworkData(timeSlice.Slice);
performanceTrackingTool.Stop(PerformanceTarget.OnData);
}
catch (Exception err)
{
algorithm.SetRuntimeError(err, "OnData");
return;
}
performanceTrackingTool.Start(PerformanceTarget.Transactions);
//If its the historical/paper trading models, wait until market orders have been "filled"
// Manually trigger the event handler to prevent thread switch.
transactions.ProcessSynchronousEvents();
performanceTrackingTool.Stop(PerformanceTarget.Transactions);
// Process any required events of the results handler such as sampling assets, equity, or stock prices.
results.ProcessSynchronousEvents();
// poke the algorithm at the end of each time step
algorithm.OnEndOfTimeStep();
} // End of ForEach feed.Bridge.GetConsumingEnumerable
_performanceTrackingTool.Shutdown();
// stop timing the loops
TimeLimit.StopEnforcingTimeLimit();
//Stream over:: Send the final packet and fire final events:
Log.Trace("AlgorithmManager.Run(): Firing On End Of Algorithm...");
try
{
algorithm.OnEndOfAlgorithm();
}
catch (Exception err)
{
algorithm.SetRuntimeError(err, "OnEndOfAlgorithm");
return;
}
// Process any required events of the results handler such as sampling assets, equity, or stock prices.
results.ProcessSynchronousEvents(forceProcess: true);
//Liquidate Holdings for Calculations:
if (_algorithm.Status == AlgorithmStatus.Liquidated && _liveMode)
{
Log.Trace("AlgorithmManager.Run(): Liquidating algorithm holdings...");
algorithm.Liquidate();
results.LogMessage("Algorithm Liquidated");
results.SendStatusUpdate(AlgorithmStatus.Liquidated);
}
//Manually stopped the algorithm
if (_algorithm.Status == AlgorithmStatus.Stopped)
{
Log.Trace("AlgorithmManager.Run(): Stopping algorithm...");
results.LogMessage("Algorithm Stopped");
results.SendStatusUpdate(AlgorithmStatus.Stopped);
}
//Backtest deleted.
if (_algorithm.Status == AlgorithmStatus.Deleted)
{
Log.Trace("AlgorithmManager.Run(): Deleting algorithm...");
results.DebugMessage("Algorithm Id:(" + job.AlgorithmId + ") Deleted by request.");
results.SendStatusUpdate(AlgorithmStatus.Deleted);
}
//Algorithm finished, send regardless of commands:
results.SendStatusUpdate(AlgorithmStatus.Completed);
SetStatus(AlgorithmStatus.Completed);
//Take final samples:
results.Sample(time);
} // End of Run();
/// <summary>
/// Set the quit state.
/// </summary>
public void SetStatus(AlgorithmStatus state)
{
lock (_lock)
{
//We don't want anyone else to set our internal state to "Running".
//This is controlled by the algorithm private variable only.
//Algorithm could be null after it's initialized and they call Run on us
if (state != AlgorithmStatus.Running && _algorithm != null)
{
_algorithm.SetStatus(state);
}
if (_cancellationTokenSource != null && !_cancellationTokenSource.IsCancellationRequested && !_cancelRequested)
{
if (state == AlgorithmStatus.Deleted)
{
_cancelRequested = true;
// if the algorithm was deleted, let's give the algorithm a few seconds to shutdown and cancel it out
_cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(5));
}
else if (state == AlgorithmStatus.Stopped)
{
_cancelRequested = true;
// if the algorithm was stopped, let's give the algorithm a few seconds to shutdown and cancel it out
_cancellationTokenSource.CancelAfter(TimeSpan.FromMinutes(1));
}
}
}
}
private IEnumerable<TimeSlice> Stream(IAlgorithm algorithm, ISynchronizer synchronizer, IResultHandler results, CancellationToken cancellationToken)
{
var nextWarmupStatusTime = DateTime.MinValue;
var warmingUp = algorithm.IsWarmingUp;
var warmingUpPercent = 0;
var logSubscriptionCountFlag = false;
if (warmingUp)
{
nextWarmupStatusTime = DateTime.UtcNow.AddSeconds(1);
algorithm.Debug("Algorithm starting warm up...");
results.SendStatusUpdate(AlgorithmStatus.History, $"{warmingUpPercent}");
}
else
{
results.SendStatusUpdate(AlgorithmStatus.Running);
// let's be polite, and call warmup finished even though there was no warmup period and avoid algorithms having to handle it instead.
// we trigger this callback here and not internally in the algorithm so that we can go through python if required
algorithm.OnWarmupFinished();
}
// bellow we compare with slice.Time which is in UTC
var startTimeTicks = algorithm.UtcTime.Ticks;
var warmupEndTicks = algorithm.StartDate.ConvertToUtc(algorithm.TimeZone).Ticks;
// fulfilling history requirements of volatility models in live mode
if (algorithm.LiveMode)
{
warmupEndTicks = DateTime.UtcNow.Ticks;
ProcessVolatilityHistoryRequirements(algorithm, _liveMode);
}
foreach (var timeSlice in synchronizer.StreamData(cancellationToken))
{
if (algorithm.IsWarmingUp)
{
var now = DateTime.UtcNow;
if (now > nextWarmupStatusTime)
{
// send some status to the user letting them know we're done history, but still warming up,
// catching up to real time data
nextWarmupStatusTime = now.AddSeconds(2);
var newPercent = (int)(100 * (timeSlice.Time.Ticks - startTimeTicks) / (double)(warmupEndTicks - startTimeTicks));
// if there isn't any progress don't send the same update many times
if (newPercent != warmingUpPercent)
{
warmingUpPercent = newPercent;
algorithm.Debug($"Processing algorithm warm-up request {warmingUpPercent}%...");
results.SendStatusUpdate(AlgorithmStatus.History, $"{warmingUpPercent}");
}
}
if (!logSubscriptionCountFlag)
{
Log.Trace($"AlgorithmManager.Stream(): Subscriptions count before warm up: {algorithm.SubscriptionManager.Count}");
logSubscriptionCountFlag = true;
}
}
else if (warmingUp)
{
// warmup finished, send an update
warmingUp = false;
// we trigger this callback here and not internally in the algorithm so that we can go through python if required
algorithm.OnWarmupFinished();
algorithm.Debug("Algorithm finished warming up.");
Log.Trace($"AlgorithmManager.Stream(): Subscriptions count after warm up: {algorithm.SubscriptionManager.Count}");
results.SendStatusUpdate(AlgorithmStatus.Running, "100");
}
yield return timeSlice;
}
}
/// <summary>
/// Helper method used to process securities volatility history requirements
/// </summary>
/// <remarks>Implemented as static to facilitate testing</remarks>
/// <param name="algorithm">The algorithm instance</param>
/// <param name="liveMode">Whether the algorithm is in live mode</param>
public static void ProcessVolatilityHistoryRequirements(IAlgorithm algorithm, bool liveMode)
{
Log.Trace("ProcessVolatilityHistoryRequirements(): Updating volatility models with historical data...");
foreach (var security in algorithm.Securities.Values)
{
security.VolatilityModel.WarmUp(algorithm.HistoryProvider, algorithm.SubscriptionManager, security, algorithm.UtcTime,
algorithm.TimeZone, liveMode);
}
Log.Trace("ProcessVolatilityHistoryRequirements(): finished.");
}
/// <summary>
/// Helper method to apply a split to an algorithm instance
/// </summary>
public static void HandleSplits(TimeSlice timeSlice, IAlgorithm algorithm, bool liveMode)
{
foreach (var split in timeSlice.Slice.Splits.Values)
{
try
{
// only process split occurred events (ignore warnings)
if (split.Type != SplitType.SplitOccurred)
{
continu
85EA
e;
}
if (algorithm.Securities.TryGetValue(split.Symbol, out var security) && liveMode && !algorithm.IsWarmingUp)
{
Log.Trace($"AlgorithmManager.Run(): {algorithm.Time}: Pre-Split for {split}. Security Price: {security.Price} Holdings: {security.Holdings.Quantity}");
}
var mode = algorithm.SubscriptionManager.SubscriptionDataConfigService
.GetSubscriptionDataConfigs(split.Symbol)
.DataNormalizationMode();
if (algorithm.IsWarmingUp)
{
// skip past split during live warmup, the algorithms position already reflects them
Log.Trace($"AlgorithmManager.Run(): {algorithm.Time}: Skip Split during warmup: {split}");
}
else
{
if (Log.DebuggingEnabled)
{
Log.Debug($"AlgorithmManager.Run(): {algorithm.Time}: Applying Split for {split.Symbol}");
}
// apply the split event to the portfolio
algorithm.Portfolio.ApplySplit(split, security, liveMode, mode);
// apply the split event to the trade builder
algorithm.TradeBuilder.ApplySplit(split, liveMode, mode);
// apply the split to open orders as well in raw mode, all other modes are split adjusted
if (liveMode || mode == DataNormalizationMode.Raw)
{
// in live mode we always want to have our order match the order at the brokerage, so apply the split to the orders
var openOrders = algorithm.Transactions.GetOpenOrderTickets(ticket => ticket.Symbol == split.Symbol);
algorithm.BrokerageModel.ApplySplit(openOrders.ToList(), split);
}
}
// apply the split event to the security volatility model
ApplySplitOrDividendToVolatilityModel(algorithm, security, liveMode, mode);
if (liveMode && security != null && !algorithm.IsWarmingUp)
{
Log.Trace($"AlgorithmManager.Run(): {algorithm.Time}: Post-Split for {split}. Security Price: {security.Price} Holdings: {security.Holdings.Quantity}");
}
}
catch (Exception err)
{
algorithm.SetRuntimeError(err, "Split event");
return;
}
}
}
/// <summary>
/// Helper method to apply a dividend to an algorithm instance
/// </summary>
public static void HandleDividends(TimeSlice timeSlice, IAlgorithm algorithm, bool liveMode)
{
foreach (var dividend in timeSlice.Slice.Dividends.Values)
{
if (Log.DebuggingEnabled)
{
Log.Debug($"AlgorithmManager.Run(): {algorithm.Time}: Applying Dividend: {dividend}");
}
if (algorithm.Securities.TryGetValue(dividend.Symbol, out var security) && liveMode && !algorithm.IsWarmingUp)
{
Log.Trace($"AlgorithmManager.Run(): {algorithm.Time}: Pre-Dividend: {dividend}. " +
$"Security Holdings: {security.Holdings.Quantity} Account Currency Holdings: " +
$"{algorithm.Portfolio.CashBook[algorithm.AccountCurrency].Amount}");
}
var mode = algorithm.SubscriptionManager.SubscriptionDataConfigService
.GetSubscriptionDataConfigs(dividend.Symbol)
.DataNormalizationMode();
if (algorithm.IsWarmingUp)
{
// skip past dividends during warmup, the algorithms position already reflects them
Log.Trace($"AlgorithmManager.Run(): {algorithm.Time}: Skip Dividend during warmup: {dividend}");
}
else
{
// apply the dividend event to the portfolio
algorithm.Portfolio.ApplyDividend(dividend, liveMode, mode);
}
// apply the dividend event to the security volatility model
ApplySplitOrDividendToVolatilityModel(algorithm, security, liveMode, mode);
if (liveMode && security != null && !algorithm.IsWarmingUp)
{
Log.Trace($"AlgorithmManager.Run(): {algorithm.Time}: Post-Dividend: {dividend}. Security " +
$"Holdings: {security.Holdings.Quantity} Account Currency Holdings: " +
$"{algorithm.Portfolio.CashBook[algorithm.AccountCurrency].Amount}");
}
}
}
/// <summary>
/// Keeps track of split warnings so we can later liquidate option contracts
/// </summary>
private void HandleSplitSymbols(Splits newSplits, List<Split> splitWarnings)
{
foreach (var split in newSplits.Values)
{
if (split.Type != SplitType.Warning)
{
if (Log.DebuggingEnabled)
{
Log.Debug($"AlgorithmManager.HandleSplitSymbols(): {_algorithm.Time} - Security split occurred: Split Factor: {split} Reference Price: {split.ReferencePrice}");
}
continue;
}
if (Log.DebuggingEnabled)
{
Log.Debug($"AlgorithmManager.HandleSplitSymbols(): {_algorithm.Time} - Security split warning: {split}");
}
if (!splitWarnings.Any(x => x.Symbol == split.Symbol && x.Type == SplitType.Warning))
{
splitWarnings.Add(split);
}
}
}
/// <summary>
/// Liquidate option contact holdings who's underlying security has split
/// </summary>
private void ProcessSplitSymbols(IAlgorithm algorithm, List<Split> splitWarnings, List<Delisting> pendingDelistings)
{
// NOTE: This method assumes option contracts have the same core trading hours as their underlying contract
// This is a small performance optimization to prevent scanning every contract on every time step,
// instead we scan just the underlyings, thereby reducing the time footprint of this methods by a factor
// of N, the number of derivative subscriptions
for (int i = splitWarnings.Count - 1; i >= 0; i--)
{
var split = splitWarnings[i];
var security = algorithm.Securities[split.Symbol];
if (!security.IsTradable
&& !algorithm.UniverseManager.ActiveSecurities.Keys.Contains(split.Symbol))
{
Log.Debug($"AlgorithmManager.ProcessSplitSymbols(): {_algorithm.Time} - Removing split warning for {security.Symbol}");
// remove the warning from out list
splitWarnings.RemoveAt(i);
// Since we are storing the split warnings for a loop
// we need to check if the security was removed.
// When removed, it will be marked as non tradable but just in case
// we expect it not to be an active security either
continue;
}
var nextMarketClose = security.Exchange.Hours.GetNextMarketClose(security.LocalTime, false);
// determine the latest possible time we can submit a MOC order
var configs = algorithm.SubscriptionManager.SubscriptionDataConfigService
.GetSubscriptionDataConfigs(security.Symbol);
if (configs.Count == 0)
{
// should never happen at this point, if it does let's give some extra info
throw new Exception(
$"AlgorithmManager.ProcessSplitSymbols(): {_algorithm.Time} - No subscriptions found for {security.Symbol}" +
$", IsTradable: {security.IsTradable}" +
$", Active: {algorithm.UniverseManager.ActiveSecurities.Keys.Contains(split.Symbol)}");
}
var latestMarketOnCloseTimeRoundedDownByResolution = nextMarketClose.Subtract(MarketOnCloseOrder.SubmissionTimeBuffer)
.RoundDownInTimeZone(configs.GetHighestResolution().ToTimeSpan(), security.Exchange.TimeZone, configs.First().DataTimeZone);
// we don't need to do anyhing until the market closes
if (security.LocalTime < latestMarketOnCloseTimeRoundedDownByResolution) continue;
// Skip processing split warnings during warmup
// Historical splits are already reflected in current positions
if (algorithm.IsWarmingUp)
{
splitWarnings.RemoveAt(i);
// skip past split during warmup
60B0
, the algorithms position already reflects them
Log.Trace($"AlgorithmManager.Run(): {algorithm.Time}: Skip Splits during warmup {split}");
continue;
}
// fetch all option derivatives of the underlying with holdings (excluding the canonical security)
var derivatives = algorithm.Securities.Values.Where(potentialDerivate =>
potentialDerivate.Symbol.SecurityType.IsOption() &&
potentialDerivate.Symbol.Underlying == security.Symbol &&
!potentialDerivate.Symbol.Underlying.IsCanonical() &&
potentialDerivate.HoldStock
);
foreach (var derivative in derivatives)
{
var optionContractSymbol = derivative.Symbol;
var optionContractSecurity = (Option)derivative;
if (pendingDelistings.Any(x => x.Symbol == optionContractSymbol
&& x.Time.Date == optionContractSecurity.LocalTime.Date))
{
// if the option is going to be delisted today we skip sending the market on close order
continue;
}
// close any open orders
algorithm.Transactions.CancelOpenOrders(optionContractSymbol, "Canceled due to impending split. Separate MarketOnClose order submitted to liquidate position.");
var request = new SubmitOrderRequest(OrderType.MarketOnClose, optionContractSecurity.Type, optionContractSymbol,
-optionContractSecurity.Holdings.Quantity, 0, 0, algorithm.UtcTime,
"Liquidated due to impending split. Option splits are not currently supported."
);
// send MOC order to liquidate option contract holdings
algorithm.Transactions.AddOrder(request);
// mark option contract as not tradable
optionContractSecurity.IsTradable = false;
algorithm.Debug($"MarketOnClose order submitted for option contract '{optionContractSymbol}' due to impending {split.Symbol.Value} split event. "
+ "Option splits are not currently supported.");
}
// remove the warning from out list
splitWarnings.RemoveAt(i);
}
}