forked from QuantConnect/Lean
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQCAlgorithm.History.cs
More file actions
1551 lines (1417 loc) · 86.2 KB
/
QCAlgorithm.History.cs
File metadata and controls
1551 lines (1417 loc) · 86.2 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
4
7440
59
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 NodaTime;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Util;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using QuantConnect.Data.Market;
using System.Collections.Generic;
using QuantConnect.Python;
using Python.Runtime;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Configuration;
namespace QuantConnect.Algorithm
{
public partial class QCAlgorithm
{
private static readonly int SeedLookbackPeriod = Config.GetInt("seed-lookback-period", 5);
private static readonly int SeedRetryMinuteLookbackPeriod = Config.GetInt("seed-retry-minute-lookback-period", 24 * 60);
private static readonly int SeedRetryHourLookbackPeriod = Config.GetInt("seed-retry-hour-lookback-period", 24);
private static readonly int SeedRetryDailyLookbackPeriod = Config.GetInt("seed-retry-daily-lookback-period", 10);
private bool _dataDictionaryTickWarningSent;
/// <summary>
/// Gets or sets the history provider for the algorithm
/// </summary>
public IHistoryProvider HistoryProvider
{
get;
set;
}
/// <summary>
/// Gets whether or not this algorithm is still warming up
/// </summary>
[DocumentationAttribute(HistoricalData)]
public bool IsWarmingUp
{
get;
private set;
}
/// <summary>
/// Sets the warm up period to the specified value
/// </summary>
/// <param name="timeSpan">The amount of time to warm up, this does not take into account market hours/weekends</param>
[DocumentationAttribute(HistoricalData)]
public void SetWarmup(TimeSpan timeSpan)
{
SetWarmUp(timeSpan, null);
}
/// <summary>
/// Sets the warm up period to the specified value
/// </summary>
/// <param name="timeSpan">The amount of time to warm up, this does not take into account market hours/weekends</param>
[DocumentationAttribute(HistoricalData)]
public void SetWarmUp(TimeSpan timeSpan)
{
SetWarmup(timeSpan);
}
/// <summary>
/// Sets the warm up period to the specified value
/// </summary>
/// <param name="timeSpan">The amount of time to warm up, this does not take into account market hours/weekends</param>
/// <param name="resolution">The resolution to request</param>
[DocumentationAttribute(HistoricalData)]
public void SetWarmup(TimeSpan timeSpan, Resolution? resolution)
{
SetWarmup(null, timeSpan, resolution);
}
/// <summary>
/// Sets the warm up period to the specified value
/// </summary>
/// <param name="timeSpan">The amount of time to warm up, this does not take into account market hours/weekends</param>
/// <param name="resolution">The resolution to request</param>
[DocumentationAttribute(HistoricalData)]
public void SetWarmUp(TimeSpan timeSpan, Resolution? resolution)
{
SetWarmup(timeSpan, resolution);
}
/// <summary>
/// Sets the warm up period by resolving a start date that would send that amount of data into
/// the algorithm. The highest (smallest) resolution in the securities collection will be used.
/// For example, if an algorithm has minute and daily data and 200 bars are requested, that would
/// use 200 minute bars.
/// </summary>
/// <param name="barCount">The number of data points requested for warm up</param>
[DocumentationAttribute(HistoricalData)]
public void SetWarmup(int barCount)
{
SetWarmUp(barCount, null);
}
/// <summary>
/// Sets the warm up period by resolving a start date that would send that amount of data into
/// the algorithm. The highest (smallest) resolution in the securities collection will be used.
/// For example, if an algorithm has minute and daily data and 200 bars are requested, that would
/// use 200 minute bars.
/// </summary>
/// <param name="barCount">The number of data points requested for warm up</param>
[DocumentationAttribute(HistoricalData)]
public void SetWarmUp(int barCount)
{
SetWarmup(barCount);
}
/// <summary>
/// Sets the warm up period by resolving a start date that would send that amount of data into
/// the algorithm.
/// </summary>
/// <param name="barCount">The number of data points requested for warm up</param>
/// <param name="resolution">The resolution to request</param>
[DocumentationAttribute(HistoricalData)]
public void SetWarmup(int barCount, Resolution? resolution)
{
SetWarmup(barCount, null, resolution);
}
/// <summary>
/// Sets the warm up period by resolving a start date that would send that amount of data into
/// the algorithm.
/// </summary>
/// <param name="barCount">The number of data points requested for warm up</param>
/// <param name="resolution">The resolution to request</param>
[DocumentationAttribute(HistoricalData)]
public void SetWarmUp(int barCount, Resolution? resolution)
{
SetWarmup(barCount, resolution);
}
/// <summary>
/// Sets <see cref="IAlgorithm.IsWarmingUp"/> to false to indicate this algorithm has finished its warm up
/// </summary>
[DocumentationAttribute(HistoricalData)]
public void SetFinishedWarmingUp()
{
IsWarmingUp = false;
}
/// <summary>
/// Message for exception that is thrown when the implicit conversion between symbol and string fails
/// </summary>
private readonly string _symbolEmptyErrorMessage = "Cannot create history for the given ticker. " +
"Either explicitly use a symbol object to make the history request " +
"or ensure the symbol has been added using the AddSecurity() method before making the history request.";
/// <summary>
/// Gets the history requests required for provide warm up data for the algorithm
/// </summary>
/// <returns></returns>
[DocumentationAttribute(HistoricalData)]
private bool TryGetWarmupHistoryStartTime(out DateTime result)
{
result = Time;
if (_warmupBarCount.HasValue)
{
var symbols = Securities.Keys;
if (symbols.Count != 0)
{
var startTimeUtc = CreateBarCountHistoryRequests(symbols, _warmupBarCount.Value, Settings.WarmupResolution)
.DefaultIfEmpty()
.Min(request => request == null ? default : request.StartTimeUtc);
if (startTimeUtc != default)
{
result = startTimeUtc.ConvertFromUtc(TimeZone);
return true;
}
}
var defaultResolutionToUse = UniverseSettings.Resolution;
if (Settings.WarmupResolution.HasValue)
{
defaultResolutionToUse = Settings.WarmupResolution.Value;
}
// if the algorithm has no added security, let's take a look at the universes to determine
// what the start date should be used. Defaulting to always open
result = Time - _warmupBarCount.Value * defaultResolutionToUse.ToTimeSpan();
foreach (var universe in UniverseManager.Values)
{
var config = universe.Configuration;
var resolution = universe.Configuration.Resolution;
if (Settings.WarmupResolution.HasValue)
{
resolution = Settings.WarmupResolution.Value;
}
var exchange = MarketHoursDatabase.GetExchangeHours(config);
var start = _historyRequestFactory.GetStartTimeAlgoTz(config.Symbol, _warmupBarCount.Value, resolution, exchange, config.DataTimeZone, config.Type);
// we choose the min start
result = result < start ? result : start;
}
return true;
}
if (_warmupTimeSpan.HasValue)
{
result = Time - _warmupTimeSpan.Value;
return true;
}
return false;
}
/// <summary>
/// Get the history for all configured securities over the requested span.
/// This will use the resolution and other subscription settings for each security.
/// The symbols must exist in the Securities collection.
/// </summary>
/// <param name="span">The span over which to request data. This is a calendar span, so take into consideration weekends and such</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="fillForward">True to fill forward missing data, false otherwise</param>
/// <param name="extendedMarketHours">True to include extended market hours data, false otherwise</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security history request</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the securities history</param>
/// <param name="contractDepthOffset">The continuous contract desired offset from the current front month.
/// For example, 0 will use the front month, 1 will use the back month contract</param>
/// <returns>An enumerable of slice containing data over the most recent span for all configured securities</returns>
[DocumentationAttribute(HistoricalData)]
public IEnumerable<Slice> History(TimeSpan span, Resolution? resolution = null, bool? fillForward = null, bool? extendedMarketHours = null,
DataMappingMode? dataMappingMode = null, DataNormalizationMode? dataNormalizationMode = null, int? contractDepthOffset = null)
{
return History(Securities.Keys, Time - span, Time, resolution, fillForward, extendedMarketHours, dataMappingMode,
dataNormalizationMode, contractDepthOffset).Memoize();
}
/// <summary>
/// Get the history for all configured securities over the requested span.
/// This will use the resolution and other subscription settings for each security.
/// The symbols must exist in the Securities collection.
/// </summary>
/// <param name="periods">The number of bars to request</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="fillForward">True to fill forward missing data, false otherwise</param>
/// <param name="extendedMarketHours">True to include extended market hours data, false otherwise</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security history request</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the securities history</param>
/// <param name="contractDepthOffset">The continuous contract desired offset from the current front month.
/// For example, 0 will use the front month, 1 will use the back month contract</param>
/// <returns>An enumerable of slice containing data over the most recent span for all configured securities</returns>
[DocumentationAttribute(HistoricalData)]
public IEnumerable<Slice> History(int periods, Resolution? resolution = null, bool? fillForward = null, bool? extendedMarketHours = null,
DataMappingMode? dataMappingMode = null, DataNormalizationMode? dataNormalizationMode = null, int? contractDepthOffset = null)
{
return History(Securities.Keys, periods, resolution, fillForward, extendedMarketHours, dataMappingMode, dataNormalizationMode,
contractDepthOffset).Memoize();
}
/// <summary>
/// Get the history for all configured securities over the requested span.
/// This will use the resolution and other subscription settings for each security.
/// The symbols must exist in the Securities collection.
/// </summary>
/// <param name="universe">The universe to fetch the data for</param>
/// <param name="periods">The number of bars to request</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="fillForward">True to fill forward missing data, false otherwise</param>
/// <param name="extendedMarketHours">True to include extended market hours data, false otherwise</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security history request</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the securities history</param>
/// <param name="contractDepthOffset">The continuous contract desired offset from the current front month.
/// For example, 0 will use the front month, 1 will use the back month contract</param>
/// <returns>An enumerable of slice containing data over the most recent span for all configured securities</returns>
[DocumentationAttribute(HistoricalData)]
public IEnumerable<BaseDataCollection> History(Universe universe, int periods, Resolution? resolution = null, bool? fillForward = null, bool? extendedMarketHours = null,
DataMappingMode? dataMappingMode = null, DataNormalizationMode? dataNormalizationMode = null, int? contractDepthOffset = null)
{
var symbols = new[] { universe.Configuration.Symbol };
resolution ??= universe.Configuration.Resolution;
CheckPeriodBasedHistoryRequestResolution(symbols, resolution, universe.Configuration.Type);
var requests = CreateBarCountHistoryRequests(symbols, universe.Configuration.Type, periods, resolution, fillForward, extendedMarketHours, dataMappingMode,
dataNormalizationMode, contractDepthOffset);
return GetDataTypedHistory<BaseDataCollection>(requests).Select(x => x.Values.Single());
}
/// <summary>
/// Gets the historical data for all symbols of the requested type over the requested span.
/// The symbol's configured values for resolution and fill forward behavior will be used
/// The symbols must exist in the Securities collection.
/// </summary>
/// <param name="universe">The universe to fetch the data for</param>
/// <param name="span">The span over which to request data. This is a calendar span, so take into consideration weekends and such</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="fillForward">True to fill forward missing data, false otherwise</param>
/// <param name="extendedMarketHours">True to include extended market hours data, false otherwise</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security history request</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the securities history</param>
/// <param name="contractDepthOffset">The continuous contract desired offset from the current front month.
/// For example, 0 will use the front month, 1 will use the back month contract</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
[DocumentationAttribute(HistoricalData)]
public IEnumerable<BaseDataCollection> History(Universe universe, TimeSpan span, Resolution? resolution = null, bool? fillForward = null,
bool? extendedMarketHours = null, DataMappingMode? dataMappingMode = null, DataNormalizationMode? dataNormalizationMode = null,
int? contractDepthOffset = null)
{
return History(universe, Time - span, Time, resolution, fillForward, extendedMarketHours, dataMappingMode, dataNormalizationMode, contractDepthOffset);
}
/// <summary>
/// Gets the historical data for the specified symbols between the specified dates. The symbols must exist in the Securities collection.
/// </summary>
/// <param name="universe">The universe to fetch the data for</param>
/// <param name="start">The start time in the algorithm's time zone</param>
/// <param name="end">The end time in the algorithm's time zone</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="fillForward">True to fill forward missing data, false otherwise</param>
/// <param name="extendedMarketHours">True to include extended market hours data, false otherwise</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security history request</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the securities history</param>
/// <param name="contractDepthOffset">The continuous contract desired offset from the current front month.
/// For example, 0 will use the front month, 1 will use the back month contract</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
[DocumentationAttribute(HistoricalData)]
public IEnumerable<BaseDataCollection> History(Universe universe, DateTime start, DateTime end, Resolution? resolution = null,
bool? fillForward = null, bool? extendedMarketHours = null, DataMappingMode? dataMappingMode = null,
DataNormalizationMode? dataNormalizationMode = null, int? contractDepthOffset = null)
{
resolution ??= universe.Configuration.Resolution;
var requests = CreateDateRangeHistoryRequests(new[] { universe.Symbol }, universe.DataType, start, end, resolution, fillForward, extendedMarketHours,
dataMappingMode, dataNormalizationMode, contractDepthOffset);
return GetDataTypedHistory<BaseDataCollection>(requests).Select(x => x.Values.Single());
}
/// <summary>
/// Gets the historical data for all symbols of the requested type over the requested span.
/// The symbol's configured values for resolution and fill forward behavior will be used
/// The symbols must exist in the Securities collection.
/// </summary>
/// <param name="span">The span over which to retrieve recent historical data</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="fillForward">True to fill forward missing data, false otherwise</param>
/// <param name="extendedMarketHours">True to include extended market hours data, false otherwise</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security history request</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the securities history</param>
/// <param name="contractDepthOffset">The continuous contract desired offset from the current front month.
/// For example, 0 will use the front month, 1 will use the back month contract</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
[DocumentationAttribute(HistoricalData)]
public IEnumerable<DataDictionary<T>> History<T>(TimeSpan span, Resolution? resolution = null, bool? fillForward = null,
bool? extendedMarketHours = null, DataMappingMode? dataMappingMode = null, DataNormalizationMode? dataNormalizationMode = null,
int? contractDepthOffset = null)
where T : IBaseData
{
return History<T>(Securities.Keys, span, resolution, fillForward, extendedMarketHours, dataMappingMode, dataNormalizationMode,
contractDepthOffset).Memoize();
}
/// <summary>
/// Gets the historical data for the specified symbols over the requested span.
/// The symbols must exist in the Securities collection.
/// </summary>
/// <typeparam name="T">The data type of the symbols</typeparam>
/// <param name="symbols">The symbols to retrieve historical data for</param>
/// <param name="span">The span over which to retrieve recent historical data</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="fillForward">True to fill forward missing data, false otherwise</param>
/// <param name="extendedMarketHours">True to include extended market hours data, false otherwise</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security history request</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the securities history</param>
/// <param name="contractDepthOffset">The continuous contract desired offset from the current front month.
/// For example, 0 will use the front month, 1 will use the back month contract</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
[DocumentationAttribute(HistoricalData)]
public IEnumerable<DataDictionary<T>> History<T>(IEnumerable<Symbol> symbols, TimeSpan span, Resolution? resolution = null,
bool? fillForward = null, bool? extendedMarketHours = null, DataMappingMode? dataMappingMode = null,
DataNormalizationMode? dataNormalizationMode = null, int? contractDepthOffset = null)
where T : IBaseData
{
return History<T>(symbols, Time - span, Time, resolution, fillForward, extendedMarketHours, dataMappingMode,
dataNormalizationMode, contractDepthOffset).Memoize();
}
/// <summary>
/// Gets the historical data for the specified symbols. The exact number of bars will be returned for
/// each symbol. This may result in some data start earlier/later than others due to when various
/// exchanges are open. The symbols must exist in the Securities collection.
/// </summary>
/// <typeparam name="T">The data type of the symbols</typeparam>
/// <param name="symbols">The symbols to retrieve historical data for</param>
/// <param name="periods">The number of bars to request</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="fillForward">True to fill forward missing data, false otherwise</param>
/// <param name="extendedMarketHours">True to include extended market hours data, false otherwise</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security history request</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the securities history</param>
/// <param name="contractDepthOffset">The continuous contract desired offset from the current front month.
/// For example, 0 will use the front month, 1 will use the back month contract</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
[DocumentationAttribute(HistoricalData)]
public IEnumerable<DataDictionary<T>> History<T>(IEnumerable<Symbol> symbols, int periods, Resolution? resolution = null,
bool? fillForward = null, bool? extendedMarketHours = null, DataMappingMode? dataMappingMode = null,
DataNormalizationMode? dataNormalizationMode = null, int? contractDepthOffset = null)
where T : IBaseData
{
CheckPeriodBasedHistoryRequestResolution(symbols, resolution, typeof(T));
var requests = CreateBarCountHistoryRequests(symbols, typeof(T), periods, resolution, fillForward, extendedMarketHours, dataMappingMode,
dataNormalizationMode, contractDepthOffset);
return GetDataTypedHistory<T>(requests);
}
/// <summary>
/// Gets the historical data for the specified symbols between the specified dates. The symbols must exist in the Securities collection.
/// </summary>
/// <typeparam name="T">The data type of the symbols</typeparam>
/// <param name="symbols">The symbols to retrieve historical data for</param>
/// <param name="start">The start time in the algorithm's time zone</param>
/// <param name="end">The end time in the algorithm's time zone</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="fillForward">True to fill forward missing data, false otherwise</param>
/// <param name="extendedMarketHours">True to include extended market hours data, false otherwise</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security history request</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the securities history</param>
/// <param name="contractDepthOffset">The continuous contract desired offset from the current front month.
/// For example, 0 will use the front month, 1 will use the back month contract</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
[DocumentationAttribute(HistoricalData)]
public IEnumerable<DataDictionary<T>> History<T>(IEnumerable<Symbol> symbols, DateTime start, DateTime end, Resolution? resolution = null,
bool? fillForward = null, bool? extendedMarketHours = null, DataMappingMode? dataMappingMode = null,
DataNormalizationMode? dataNormalizationMode = null, int? contractDepthOffset = null)
where T : IBaseData
{
var requests = CreateDateRangeHistoryRequests(symbols, typeof(T), start, end, resolution, fillForward, extendedMarketHours,
dataMappingMode, dataNormalizationMode, contractDepthOffset);
return GetDataTypedHistory<T>(requests);
}
/// <summary>
/// Gets the historical data for the specified symbol over the request span. The symbol must exist in the Securities collection.
/// </summary>
/// <typeparam name="T">The data type of the symbol</typeparam>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="span">The span over which to retrieve recent historical data</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="fillForward">True to fill forward missing data, false otherwise</param>
/// <param name="extendedMarketHours">True to include extended market hours data, false otherwise</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security history request</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the securities history</param>
/// <param name="contractDepthOffset">The continuous contract desired offset from the current front month.
/// For example, 0 will use the front month, 1 will use the back month contract</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
[DocumentationAttribute(HistoricalData)]
public IEnumerable<T> History<T>(Symbol symbol, TimeSpan span, Resolution? resolution = null, bool? fillForward = null,
bool? extendedMarketHours = null, DataMappingMode? dataMappingMode = null, DataNormalizationMode? dataNormalizationMode = null,
int? contractDepthOffset = null)
where T : IBaseData
{
return History<T>(symbol, Time - span, Time, resolution, fillForward, extendedMarketHours, dataMappingMode,
dataNormalizationMode, contractDepthOffset).Memoize();
}
/// <summary>
/// Gets the historical data for the specified symbol. The exact number of bars will be returned.
/// The symbol must exist in the Securities collection.
/// </summary>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="periods">The number of bars to request</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="fillForward">True to fill forward missing data, false otherwise</param>
/// <param name="extendedMarketHours">True to include extended market hours data, false otherwise</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security history request</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the securities history</param>
/// <param name="contractDepthOffset">The continuous contract desired offset from the current front month.
/// For example, 0 will use the front month, 1 will use the back month contract</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
[DocumentationAttribute(HistoricalData)]
public IEnumerable<TradeBar> History(Symbol symbol, int periods, Resolution? resolution = null, bool? fillForward = null,
bool? extendedMarketHours = null, DataMappingMode? dataMappingMode = null, DataNormalizationMode? dataNormalizationMode = null,
int? contractDepthOffset = null)
{
if (symbol == null) throw new ArgumentException(_symbolEmptyErrorMessage);
resolution = GetResolution(symbol, resolution, typeof(TradeBar));
CheckPeriodBasedHistoryRequestResolution(new[] { symbol }, resolution, typeof(TradeBar));
var marketHours = GetMarketHours(symbol);
var start = _historyRequestFactory.GetStartTimeAlgoTz(symbol, periods, resolution.Value, marketHours.ExchangeHours,
marketHours.DataTimeZone, typeof(TradeBar), extendedMarketHours);
return History(symbol, start, Time, resolution, fillForward, extendedMarketHours, dataMappingMode, dataNormalizationMode,
contractDepthOffset);
}
/// <summary>
/// Gets the historical data for the specified symbol. The exact number of bars will be returned.
/// The symbol must exist in the Securities collection.
/// </summary>
/// <typeparam name="T">The data type of the symbol</typeparam>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="periods">The number of bars to request</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="fillForward">True to fill forward missing data, false otherwise</param>
/// <param name="extendedMarketHours">True to include extended market hours data, false otherwise</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security history request</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the securities history</param>
/// <param name="contractDepthOffset">The continuous contract desired offset from the current front month.
/// For example, 0 will use the front month, 1 will use the back month contract</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
[DocumentationAttribute(HistoricalData)]
public IEnumerable<T> History<T>(Symbol symbol, int periods, Resolution? resolution = null, bool? fillForward = null,
bool? extendedMarketHours = null, DataMappingMode? dataMappingMode = null, DataNormalizationMode? dataNormalizationMode = null,
int? contractDepthOffset = null)
where T : IBaseData
{
resolution = GetResolution(symbol, resolution, typeof(T));
CheckPeriodBasedHistoryRequestResolution(new[] { symbol }, resolution, typeof(T));
var requests = CreateBarCountHistoryRequests(new[] { symbol }, typeof(T), periods, resolution, fillForward, extendedMarketHours,
dataMappingMode, dataNormalizationMode, contractDepthOffset);
return GetDataTypedHistory<T>(requests, symbol);
}
/// <summary>
/// Gets the historical data for the specified symbol between the specified dates. The symbol must exist in the Securities collection.
/// </summary>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="start">The start time in the algorithm's time zone</param>
/// <param name="end">The end time in the algorithm's time zone</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="fillForward">True to fill forward missing data, false otherwise</param>
/// <param name="extendedMarketHours">True to include extended market hours data, false otherwise</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security history request</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the securities history</param>
/// <param name="contractDepthOffset">The continuous contract desired offset from the current front month.
/// For example, 0 will use the front month, 1 will use the back month contract</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
[DocumentationAttribute(HistoricalData)]
public IEnumerable<T> History<T>(Symbol symbol, DateTime start, DateTime end, Resolution? resolution = null, bool? fillForward = null,
bool? extendedMarketHours = null, DataMappingMode? dataMappingMode = null, DataNormalizationMode? dataNormalizationMode = null,
int? contractDepthOffset = null)
where T : IBaseData
{
var requests = CreateDateRangeHistoryRequests(new[] { symbol }, typeof(T), start, end, resolution, fillForward, extendedMarketHours,
dataMappingMode, dataNormalizationMode, contractDepthOffset);
return GetDataTypedHistory<T>(requests, symbol);
}
/// <summary>
/// Gets the historical data for the specified symbol over the request span. The symbol must exist in the Securities collection.
/// </summary>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="span">The span over which to retrieve recent historical data</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="fillForward">True to fill forward missing data, false otherwise</param>
/// <param name="extendedMarketHours">True to include extended market hours data, false otherwise</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security history request</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the securities history</param>
/// <param name="contractDepthOffset">The continuous contract desired offset from the current front month.
/// For example, 0 will use the front month, 1 will use the back month contract</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
[DocumentationAttribute(HistoricalData)]
public IEnumerable<TradeBar> History(Symbol symbol, TimeSpan span, Resolution? resolution = null, bool? fillForward = null,
bool? extendedMarketHours = null, DataMappingMode? dataMappingMode = null, DataNormalizationMode? dataNormalizationMode = null,
int? contractDepthOffset = null)
{
return History(symbol, Time - span, Time, resolution, fillForward, extendedMarketHours, dataMappingMode, dataNormalizationMode,
contractDepthOffset);
}
/// <summary>
/// Gets the historical data for the specified symbol over the request span. The symbol must exist in the Securities collection.
/// </summary>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="start">The start time in the algorithm's time zone</param>
/// <param name="end">The end time in the algorithm's time zone</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="fillForward">True to fill forward missing data, false otherwise</param>
/// <param name="extendedMarketHours">True to include extended market hours data, false otherwise</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security history request</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the securities history</param>
/// <param name="contractDepthOffset">The continuous contract desired offset from the current front month.
/// For example, 0 will use the front month, 1 will use the back month contract</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
[DocumentationAttribute(HistoricalData)]
public IEnumerable<TradeBar> History(Symbol symbol, DateTime start, DateTime end, Resolution? resolution = null, bool? fillForward = null,
bool? extendedMarketHours = null, DataMappingMode? dataMappingMode = null, DataNormalizationMode? dataNormalizationMode = null,
int? contractDepthOffset = null)
{
var securityType = symbol.ID.SecurityType;
if (securityType == SecurityType.Forex || securityType == SecurityType.Cfd)
{
Error("Calling History<TradeBar> method on a Forex or CFD security will return an empty result. Please use the generic version with QuoteBar type parameter.");
}
var resolutionToUse = resolution ?? GetResolution(symbol, resolution, typeof(TradeBar));
if (resolutionToUse == Resolution.Tick)
{
throw new InvalidOperationException("Calling History<TradeBar> method with Resolution.Tick will return an empty result." +
" Please use the generic version with Tick type parameter or provide a list of Symbols to use the Slice history request API.");
}
return History(new[] { symbol }, start, end, resolutionToUse, fillForward, extendedMarketHours, dataMappingMode, dataNormalizationMode,
contractDepthOffset).Get(symbol).Memoize();
}
/// <summary>
/// Gets the historical data for the specified symbols over the requested span.
/// The symbol's configured values for resolution and fill forward behavior will be used
/// The symbols must exist in the Securities collection.
/// </summary>
/// <param name="symbols">The symbols to retrieve historical data for</param>
/// <param name="span">The span over which to retrieve recent historical data</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="fillForward">True to fill forward missing data, false otherwise</param>
/// <param name="extendedMarketHours">True to include extended market hours data, false otherwise</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security history request</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the securities history</param>
/// <param name="contractDepthOffset">The continuous contract desired offset from the current front month.
/// For example, 0 will use the front month, 1 will use the back month contract</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
[DocumentationAttribute(HistoricalData)]
public IEnumerable<Slice> History(IEnumerable<Symbol> symbols, TimeSpan span, Resolution? resolution = null, bool? fillForward = null,
bool? extendedMarketHours = null, DataMappingMode? dataMappingMode = null, DataNormalizationMode? dataNormalizationMode = null,
int? contractDepthOffset = null)
{
return History(symbols, Time - span, Time, resolution, fillForward, extendedMarketHours, dataMappingMode,
dataNormalizationMode, contractDepthOffset).Memoize();
}
/// <summary>
/// Gets the historical data for the specified symbols. The exact number of bars will be returned for
/// each symbol. This may result in some data start earlier/later than others due to when various
/// exchanges are open. The symbols must exist in the Securities collection.
/// </summary>
/// <param name="symbols">The symbols to retrieve historical data for</param>
/// <param name="periods">The number of bars to request</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="fillForward">True to fill forward missing data, false otherwise</param>
/// <param name="extendedMarketHours">True to include extended market hours data, false otherwise</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security history request</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the securities history</param>
/// <param name="contractDepthOffset">The continuous contract desired offset from the current front month.
/// For example, 0 will use the front month, 1 will use the back month contract</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
[DocumentationAttribute(HistoricalData)]
public IEnumerable<Slice> History(IEnumerable<Symbol> symbols, int periods, Resolution? resolution = null, bool? fillForward = null,
bool? extendedMarketHours = null, DataMappingMode? dataMappingMode = null, DataNormalizationMode? dataNormalizationMode = null,
int? contractDepthOffset = null)
{
CheckPeriodBasedHistoryRequestResolution(symbols, resolution, null);
return History(CreateBarCountHistoryRequests(symbols, periods, resolution, fillForward, extendedMarketHours, dataMappingMode,
dataNormalizationMode, contractDepthOffset)).Memoize();
}
/// <summary>
/// Gets the historical data for the specified symbols between the specified dates. The symbols must exist in the Securities collection.
/// </summary>
/// <param name="symbols">The symbols to retrieve historical data for</param>
/// <param name="start">The start time in the algorithm's time zone</param>
/// <param name="end">The end time in the algorithm's time zone</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="fillForward">True to fill forward missing data, false otherwise</param>
/// <param name="extendedMarketHours">True to include extended market hours data, false otherwise</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security history request</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the securities history</param>
/// <param name="contractDepthOffset">The continuous contract desired offset from the current front month.
/// For example, 0 will use the front month, 1 will use the back month contract</param>
/// <returns>An enumerable of slice containing the requested historical data</returns>
[DocumentationAttribute(HistoricalData)]
public IEnumerable<Slice> History(IEnumerable<Symbol> symbols, DateTime start, DateTime end, Resolution? resolution = null,
bool? fillForward = null, bool? extendedMarketHours = null, DataMappingMode? dataMappingMode = null,
DataNormalizationMode? dataNormalizationMode = null, int? contractDepthOffset = null)
{
return History(CreateDateRangeHistoryRequests(symbols, start, end, resolution, fillForward, extendedMarketHours, dataMappingMode,
dataNormalizationMode, contractDepthOffset)).Memoize();
}
/// <summary>
/// Executes the specified history request
/// </summary>
/// <param name="request">the history request to execute</param>
/// <returns>An enumerable of slice satisfying the specified history request</returns>
[DocumentationAttribute(HistoricalData)]
public IEnumerable<Slice> History(HistoryRequest request)
{
return History(new[] { request }).Memoize();
}
/// <summary>
/// Executes the specified history requests
/// </summary>
/// <param name="requests">the history requests to execute</param>
/// <returns>An enumerable of slice satisfying the specified history request</returns>
[DocumentationAttribute(HistoricalData)]
public IEnumerable<Slice> History(IEnumerable<HistoryRequest> requests)
{
return History(requests, TimeZone).Memoize();
}
/// <summary>
/// Yields data to warmup a security for all it's subscribed data types
/// </summary>
/// <param name="security"><see cref="Security"/> object for which to retrieve historical data</param>
/// <returns>Securities historical data</returns>
[DocumentationAttribute(AddingData)]
[DocumentationAttribute(HistoricalData)]
public IEnumerable<BaseData> GetLastKnownPrices(Security security)
{
return GetLastKnownPrices(security.Symbol);
}
/// <summary>
/// Yields data to warm up a security for all its subscribed data types
/// </summary>
/// <param name="symbol">The symbol we want to get seed data for</param>
/// <returns>Securities historical data</returns>
[DocumentationAttribute(AddingData)]
[DocumentationAttribute(HistoricalData)]
public IEnumerable<BaseData> GetLastKnownPrices(Symbol symbol)
{
if (!HistoryRequestValid(symbol) || HistoryProvider == null)
{
return Enumerable.Empty<BaseData>();
}
var data = GetLastKnownPrices([symbol]);
return data.Values.FirstOrDefault() ?? Enumerable.Empty<BaseData>();
}
/// <summary>
/// Yields data to warm up multiple securities for all their subscribed data types
/// </summary>
/// <param name="securities">The securities we want to get seed data for</param>
/// <returns>Securities historical data</returns>
[DocumentationAttribute(AddingData)]
[DocumentationAttribute(HistoricalData)]
public DataDictionary<IEnumerable<BaseData>> GetLastKnownPrices(IEnumerable<Security> securities)
{
return GetLastKnownPrices(securities.Select(s => s.Symbol));
}
/// <summary>
/// Yields data to warm up multiple securities for all their subscribed data types
/// </summary>
/// <param name="symbols">The symbols we want to get seed data for</param>
/// <returns>Securities historical data</returns>
[DocumentationAttribute(AddingData)]
[DocumentationAttribute(HistoricalData)]
public DataDictionary<IEnumerable<BaseData>> GetLastKnownPrices(IEnumerable<Symbol> symbols)
{
if (HistoryProvider == null)
{
return new DataDictionary<IEnumerable<BaseData>>();
}
var data = new Dictionary<(Symbol, Type, TickType), BaseData>();
GetLastKnownPricesImpl(symbols, data);
return data
.GroupBy(kvp => kvp.Key.Item1)
.ToDataDictionary(
g => g.Key,
g => g.OrderBy(kvp => kvp.Value.Time)
.ThenBy(kvp => GetTickTypeOrder(kvp.Key.Item1.SecurityType, kvp.Key.Item3))
.Select(kvp => kvp.Value)
);
}
/// <summary>
/// Get the last known price using the history provider.
/// Useful for seeding securities with the correct price
/// </summary>
/// <param name="security"><see cref="Security"/> object for which to retrieve historical data</param>
/// <returns>A single <see cref="BaseData"/> object with the last known price</returns>
[Obsolete("This method is obsolete please use 'GetLastKnownPrices' which will return the last data point" +
" for each type associated with the requested security")]
[DocumentationAttribute(AddingData)]
[DocumentationAttribute(HistoricalData)]
public BaseData GetLastKnownPrice(Security security)
{
return GetLastKnownPrice(security.Symbol);
}
/// <summary>
/// Get the last known price using the history provider.
/// Useful for seeding securities wit
393B
h the correct price
/// </summary>
/// <param name="symbol">Symbol for which to retrieve historical data</param>
/// <returns>A single <see cref="BaseData"/> object with the last known price</returns>
[Obsolete("This method is obsolete please use 'GetLastKnownPrices' which will return the last data point" +
" for each type associated with the requested security")]
[DocumentationAttribute(AddingData)]
[DocumentationAttribute(HistoricalData)]
public BaseData GetLastKnownPrice(Symbol symbol)
{
return GetLastKnownPrices(symbol)
// since we are returning a single data point let's respect order
.OrderByDescending(data => GetTickTypeOrder(data.Symbol.SecurityType, LeanData.GetCommonTickTypeForCommonDataTypes(data.GetType(), data.Symbol.SecurityType)))
.LastOrDefault();
}
private void GetLastKnownPricesImpl(IEnumerable<Symbol> symbols, Dictionary<(Symbol, Type, TickType), BaseData> result,
int attempts = 0, IEnumerable<HistoryRequest> failedRequests = null)
{
IEnumerable<HistoryRequest> historyRequests;
var isRetry = failedRequests != null;
symbols = symbols?.Where(x => !x.IsCanonical() || x.SecurityType == SecurityType.Future);
if (attempts == 0)
{
historyRequests = CreateBarCountHistoryRequests(symbols, SeedLookbackPeriod,
fillForward: false, useAllSubscriptions: true)
.SelectMany(request =>
{
// Make open interest request daily, higher resolutions will need greater periods to return data
if (request.DataType == typeof(OpenInterest) && request.Resolution < Resolution.Daily)
{
return CreateBarCountHistoryRequests([request.Symbol], typeof(OpenInterest), SeedLookbackPeriod,
Resolution.Daily, fillForward: false, useAllSubscriptions: true);
}
if (request.Resolution < Resolution.Minute)
{
var dataType = request.DataType;
if (dataType == typeof(Tick))
{
dataType = request.TickType == TickType.Trade ? typeof(TradeBar) : typeof(QuoteBar);
}
return CreateBarCountHistoryRequests([request.Symbol], dataType, SeedLookbackPeriod,
Resolution.Minute, fillForward: false, useAllSubscriptions: true);
}
return [request];
});
}
else if (attempts == 1)
{
// If the first attempt to get the last know price returns no data, it maybe the case of an illiquid security.
// We increase the look-back period for this case accordingly to the resolution to cover a longer period
historyRequests = failedRequests
.GroupBy(request => request.Symbol)
.Select(group =>
{
var symbolRequests = group.ToArray();
var resolution = symbolRequests[0].Resolution;
var periods = resolution == Resolution.Daily
? SeedRetryDailyLookbackPeriod
: resolution == Resolution.Hour ? SeedRetryHourLookbackPeriod : SeedRetryMinuteLookbackPeriod;
return CreateBarCountHistoryRequests([group.Key], periods, resolution, fillForward: false, useAllSubscriptions: true)
.Where(request => symbolRequests.Any(x => x.DataType == request.DataType));
})
.SelectMany(x => x);
}
else
{
// Fall back to bigger daily requests as a last resort
historyRequests = CreateBarCountHistoryRequests(failedRequests.Select(x => x.Symbol).Distinct(),
Math.Min(60, 5 * SeedRetryDailyLookbackPeriod), Resolution.Daily, fillForward: false, useAllSubscriptions: true);
}
var requests = historyRequests.ToArray();
if (requests.Length == 0)
{
return;
}
foreach (var slice in History(requests))
{
for (var i = 0; i < requests.Length; i++)
{
var historyRequest = requests[i];
// keep the last data point per tick type
BaseData data = null;
if (historyRequest.DataType == typeof(QuoteBar))
{
if (slice.QuoteBars.TryGetValue(historyRequest.Symbol, out var quoteBar))
{
data = quoteBar;
}
}
else if (historyRequest.DataType == typeof(TradeBar))
{
if (slice.Bars.TryGetValue(historyRequest.Symbol, out var quoteBar))
{
data = quoteBar;
}
}
else if (historyRequest.DataType == typeof(OpenInterest))
{
if (slice.Ticks.TryGetValue(historyRequest.Symbol, out var openInterests))
{
data = openInterests[0];
}
}
// No Tick data, resolution is limited to Minute as minimum
else
{
var typeData = slice.Get(historyRequest.DataType);
if (typeData.ContainsKey(historyRequest.Symbol))
{
data = typeData[historyRequest.Symbol];
}
}
if (data != null)
{
result[(historyRequest.Symbol, historyRequest.DataType, historyRequest.TickType)] = data;
}
}
}
if (attempts < 2)
{
// Give it another try to get data for all symbols and all data types
GetLastKnownPricesImpl(null, result, attempts + 1,
requests.Where((request, i) => !result.ContainsKey((request.Symbol, request.DataType, request.TickType))));
}
}
/// <summary>
/// Centralized logic to get data typed history given a list of requests for the specified symbol.
/// This method is used to keep backwards compatibility for those History methods that expect an ArgumentException to be thrown
/// when the security and the requested data type do not match
/// </summary>
/// <remarks>
/// This method will check for Python custom data types in order to call the right Slice.Get dynamic method
/// </remarks>
private IEnumerable<T> GetDataTypedHistory<T>(IEnumerable<HistoryRequest> requests, Symbol symbol)
where T : IBaseData
{
var type = typeof(T);
var historyRequests = requests.Where(x => x != null).ToList();
if (historyRequests.Count == 0)
{
throw new ArgumentException($"No history data could be fetched. " +
$"This could be due to the specified security not being of the requested type. Symbol: {symbol} Requested Type: {type.Name}");
}
var slices = History(historyRequests, TimeZone);
IEnumerable<T> result = null;
// If T is a custom data coming from Python (a class derived from PythonData), T will get here as PythonData
// and not the actual custom type. We take care of this especial case by using a dynamic version of GetDataTypedHistory that
// receives the Python type, and we get it from the history requests.
if (type == typeof(PythonData))
{
result = GetPythonCustomDataTypeHistory(slices, historyRequests, symbol).OfType<T>();
}
// TODO: This is a patch to fix the issue with the Slice.GetImpl method returning only the last tick
// for each symbol instead of the whole list of ticks.
// The actual issue is Slice.GetImpl, so patch this can be removed right after it is properly addressed.
// A proposed solution making the Tick class a BaseDataCollection and make the Ticks class a dictionary Symbol->Tick instead of
// Symbol->List<Tick> so we can use the Slice.Get methods to collect all ticks in every slice instead of only the last one.
else if (type == typeof(Tick))
{
result = (IEnumerable<T>)slices.Select(x => x.Ticks).Where(x => x.ContainsKey(symbol)).SelectMany(x => x[symbol]);
}
else
{
result = slices.Get<T>(symbol);
}
return result.Memoize();
}
/// <summary>
/// Centralized logic to get data typed history for a given list of requests.
/// </summary>
/// <remarks>
/// This method will check for Python custom data types in order to call the right Slice.Get dynamic method
/// </remarks>
protected IEnumerable<DataDictionary<T>> GetDataTypedHistory<T>(IEnumerable<HistoryRequest> requests)
where T : IBaseData
{
var historyRequests = requests.Where(x => x != null).ToList();
var slices = History(historyRequests, TimeZone);
IEnumerable<DataDictionary<T>> result = null;
if (typeof(T) == typeof(PythonData))
{
result = GetPythonCustomDataTypeHistory(slices, historyRequests).OfType<DataDictionary<T>>();
}
else
{
if (typeof(T) == typeof(Tick) && !_dataDictionaryTickWarningSent)