-
-
Notifications
You must be signed in to change notification settings - Fork 4.6k
Expand file tree
/
Copy pathAlgorithmPythonWrapper.cs
More file actions
1331 lines (1164 loc) · 56.9 KB
/
AlgorithmPythonWrapper.cs
File metadata and controls
1331 lines (1164 loc) · 56.9 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 NodaTime;
using Python.Runtime;
using QuantConnect.Algorithm;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Benchmarks;
using QuantConnect.Brokerages;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Exceptions;
using QuantConnect.Interfaces;
using QuantConnect.Notifications;
using QuantConnect.Orders;
using QuantConnect.Python;
using QuantConnect.Scheduling;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
using QuantConnect.Securities.Option;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using QuantConnect.Storage;
using QuantConnect.Statistics;
using QuantConnect.Data.Market;
using QuantConnect.Algorithm.Framework.Alphas.Analysis;
using QuantConnect.Commands;
using QuantConnect.Algorithm.Framework.Portfolio.SignalExports;
using QuantConnect.Algorithm.Framework.Execution;
using Common.Util;
namespace QuantConnect.AlgorithmFactory.Python.Wrappers
{
/// <summary>
/// Creates and wraps the algorithm written in python.
/// </summary>
public class AlgorithmPythonWrapper : BasePythonWrapper<IAlgorithm>, IAlgorithm
{
private readonly dynamic _onData;
private readonly dynamic _onMarginCall;
private readonly QCAlgorithm _baseAlgorithm;
// QCAlgorithm methods that might be implemented in the python algorithm:
// We keep them to avoid the BasePythonWrapper caching and eventual lookup overhead since these methods are called quite frequently
private dynamic _onBrokerageDisconnect;
private dynamic _onBrokerageMessage;
private dynamic _onBrokerageReconnect;
private dynamic _onSplits;
private dynamic _onDividends;
private dynamic _onDelistings;
private dynamic _onSymbolChangedEvents;
private dynamic _onEndOfDay;
private dynamic _onMarginCallWarning;
private dynamic _onOrderEvent;
private dynamic _onCommand;
private dynamic _onAssignmentOrderEvent;
private dynamic _onSecuritiesChanged;
private dynamic _onFrameworkSecuritiesChanged;
/// <summary>
/// True if the underlying python algorithm implements "OnEndOfDay"
/// </summary>
public bool IsOnEndOfDayImplemented { get; }
/// <summary>
/// True if the underlying python algorithm implements "OnEndOfDay(symbol)"
/// </summary>
public bool IsOnEndOfDaySymbolImplemented { get; }
/// <summary>
/// The wrapped algorithm instance cast to <see cref="QCAlgorithm"/>
/// </summary>
public QCAlgorithm BaseAlgorithm => _baseAlgorithm;
/// <summary>
/// <see cref = "AlgorithmPythonWrapper"/> constructor.
/// Creates and wraps the algorithm written in python.
/// </summary>
/// <param name="moduleName">Name of the module that can be found in the PYTHONPATH</param>
public AlgorithmPythonWrapper(string moduleName)
: base(false)
{
try
{
using (Py.GIL())
{
Logging.Log.Trace($"AlgorithmPythonWrapper(): Python version {PythonEngine.Version}: Importing python module {moduleName}");
var module = Py.Import(moduleName);
Logging.Log.Trace($"AlgorithmPythonWrapper(): {moduleName} successfully imported.");
var pyList = module.Dir();
foreach (var name in pyList)
{
Type type;
var attr = module.GetAttr(name.ToString());
var repr = attr.Repr().GetStringBetweenChars('\'', '\'');
if (repr.StartsWith(moduleName) && // Must be defined in the module
attr.TryConvert(out type, true) && // Must be a Type
typeof(QCAlgorithm).IsAssignableFrom(type)) // Must inherit from QCAlgorithm
{
Logging.Log.Trace("AlgorithmPythonWrapper(): Creating IAlgorithm instance.");
SetPythonInstance(attr.Invoke());
var dynAlgorithm = Instance as dynamic;
// Set pandas
dynAlgorithm.SetPandasConverter();
// IAlgorithm reference for LEAN internal C# calls (without going from C# to Python and back)
_baseAlgorithm = dynAlgorithm.AsManagedObject(type);
// determines whether OnData method was defined or inherits from QCAlgorithm
// If it is not, OnData from the base class will not be called
_onData = Instance.GetPythonMethod("OnData");
_onMarginCall = Instance.GetPythonMethod("OnMarginCall");
using PyObject endOfDayMethod = Instance.GetPythonMethod("OnEndOfDay");
if (endOfDayMethod != null)
{
// Since we have a EOD method implemented
// Determine which one it is by inspecting its arg count
var argCount = endOfDayMethod.GetPythonArgCount();
switch (argCount)
{
case 0: // EOD()
IsOnEndOfDayImplemented = true;
break;
case 1: // EOD(Symbol)
IsOnEndOfDaySymbolImplemented = true;
break;
}
// Its important to note that even if both are implemented
// python will only use the last implemented, meaning only one will
// be used and seen.
}
// Initialize the python methods
_onBrokerageDisconnect = Instance.GetMethod("OnBrokerageDisconnect");
_onBrokerageMessage = Instance.GetMethod("OnBrokerageMessage");
_onBrokerageReconnect = Instance.GetMethod("OnBrokerageReconnect");
_onSplits = Instance.GetMethod("OnSplits");
_onDividends = Instance.GetMethod("OnDividends");
_onDelistings = Instance.GetMethod("OnDelistings");
_onSymbolChangedEvents = Instance.GetMethod("OnSymbolChangedEvents");
_onEndOfDay = Instance.GetMethod("OnEndOfDay");
_onCommand = Instance.GetMethod("OnCommand");
_onMarginCallWarning = Instance.GetMethod("OnMarginCallWarning");
_onOrderEvent = Instance.GetMethod("OnOrderEvent");
_onAssignmentOrderEvent = Instance.GetMethod("OnAssignmentOrderEvent");
_onSecuritiesChanged = Instance.GetMethod("OnSecuritiesChanged");
_onFrameworkSecuritiesChanged = Instance.GetMethod("OnFrameworkSecuritiesChanged");
}
attr.Dispose();
}
module.Dispose();
pyList.Dispose();
// If _algorithm could not be set, throw exception
if (Instance == null)
{
throw new Exception("Please ensure that one class inherits from QCAlgorithm.");
}
}
}
catch (Exception e)
{
// perform exception interpretation for error in module import
var interpreter = StackExceptionInterpreter.CreateFromAssemblies();
e = interpreter.Interpret(e, interpreter);
throw new Exception($"AlgorithmPythonWrapper(): {interpreter.GetExceptionMessageHeader(e)}");
}
}
/// <summary>
/// AlgorithmId for the backtest
/// </summary>
public string AlgorithmId => _baseAlgorithm.AlgorithmId;
/// <summary>
/// Gets the function used to define the benchmark. This function will return
/// the value of the benchmark at a requested date/time
/// </summary>
public IBenchmark Benchmark => _baseAlgorithm.Benchmark;
/// <summary>
/// Gets the brokerage message handler used to decide what to do
/// with each message sent from the brokerage
/// </summary>
public IBrokerageMessageHandler BrokerageMessageHandler
{
get
{
return _baseAlgorithm.BrokerageMessageHandler;
}
set
{
SetBrokerageMessageHandler(value);
}
}
/// <summary>
/// Gets the brokerage model used to emulate a real brokerage
/// </summary>
public IBrokerageModel BrokerageModel => _baseAlgorithm.BrokerageModel;
/// <summary>
/// Gets the brokerage name.
/// </summary>
public BrokerageName BrokerageName => _baseAlgorithm.BrokerageName;
/// <summary>
/// Gets the risk free interest rate model used to get the interest rates
/// </summary>
public IRiskFreeInterestRateModel RiskFreeInterestRateModel => _baseAlgorithm.RiskFreeInterestRateModel;
/// <summary>
/// Debug messages from the strategy:
/// </summary>
public ConcurrentQueue<string> DebugMessages => _baseAlgorithm.DebugMessages;
/// <summary>
/// Get Requested Backtest End Date
/// </summary>
public DateTime EndDate => _baseAlgorithm.EndDate;
/// <summary>
/// Error messages from the strategy:
/// </summary>
public ConcurrentQueue<string> ErrorMessages => _baseAlgorithm.ErrorMessages;
/// <summary>
/// Gets or sets the history provider for the algorithm
/// </summary>
public IHistoryProvider HistoryProvider
{
get
{
return _baseAlgorithm.HistoryProvider;
}
set
{
SetHistoryProvider(value);
}
}
/// <summary>
/// Gets whether or not this algorithm is still warming up
/// </summary>
public bool IsWarmingUp => _baseAlgorithm.IsWarmingUp;
/// <summary>
/// Algorithm is running on a live server.
/// </summary>
public bool LiveMode => _baseAlgorithm.LiveMode;
/// <summary>
/// Algorithm running mode.
/// </summary>
public AlgorithmMode AlgorithmMode => _baseAlgorithm.AlgorithmMode;
/// <summary>
/// Deployment target, either local or cloud.
/// </summary>
public DeploymentTarget DeploymentTarget => _baseAlgorithm.DeploymentTarget;
/// <summary>
/// Log messages from the strategy:
/// </summary>
public ConcurrentQueue<string> LogMessages => _baseAlgorithm.LogMessages;
/// <summary>
/// Public name for the algorithm.
/// </summary>
/// <remarks>Not currently used but preserved for API integrity</remarks>
public string Name
{
get
{
return _baseAlgorithm.Name;
}
set
{
_baseAlgorithm.Name = value;
}
}
/// <summary>
/// A list of tags associated with the algorithm or the backtest, useful for categorization
/// </summary>
public HashSet<string> Tags
{
get
{
return _baseAlgorithm.Tags;
}
set
{
_baseAlgorithm.Tags = value;
}
}
/// <summary>
/// Event fired algorithm's name is changed
/// </summary>
public event AlgorithmEvent<string> NameUpdated
{
add
{
_baseAlgorithm.NameUpdated += value;
}
remove
{
_baseAlgorithm.NameUpdated -= value;
}
}
/// <summary>
/// Event fired when the tag collection is updated
/// </summary>
public event AlgorithmEvent<HashSet<string>> TagsUpdated
{
add
{
_baseAlgorithm.TagsUpdated += value;
}
remove
{
_baseAlgorithm.TagsUpdated -= value;
}
}
/// <summary>
/// Notification manager for storing and processing live event messages
/// </summary>
public NotificationManager Notify => _baseAlgorithm.Notify;
/// <summary>
/// Security portfolio management class provides wrapper and helper methods for the Security.Holdings class such as
/// IsLong, IsShort, TotalProfit
/// </summary>
/// <remarks>Portfolio is a wrapper and helper class encapsulating the Securities[].Holdings objects</remarks>
public SecurityPortfolioManager Portfolio => _baseAlgorithm.Portfolio;
/// <summary>
/// Gets the run time error from the algorithm, or null if none was encountered.
/// </summary>
public Exception RunTimeError
{
get
{
return _baseAlgorithm.RunTimeError;
}
set
{
SetRunTimeError(value);
}
}
/// <summary>
/// Customizable dynamic statistics displayed during live trading:
/// </summary>
public ConcurrentDictionary<string, string> RuntimeStatistics => _baseAlgorithm.RuntimeStatistics;
/// <summary>
/// Gets schedule manager for adding/removing scheduled events
/// </summary>
public ScheduleManager Schedule => _baseAlgorithm.Schedule;
/// <summary>
/// Security object collection class stores an array of objects representing representing each security/asset
/// we have a subscription for.
/// </summary>
/// <remarks>It is an IDictionary implementation and can be indexed by symbol</remarks>
public SecurityManager Securities => _baseAlgorithm.Securities;
/// <summary>
/// Gets an instance that is to be used to initialize newly created securities.
/// </summary>
public ISecurityInitializer SecurityInitializer => _baseAlgorithm.SecurityInitializer;
/// <summary>
/// Gets the Trade Builder to generate trades from executions
/// </summary>
public ITradeBuilder TradeBuilder => _baseAlgorithm.TradeBuilder;
/// <summary>
/// Gets the user settings for the algorithm
/// </summary>
public IAlgorithmSettings Settings => _baseAlgorithm.Settings;
/// <summary>
/// Gets the option chain provider, used to get the list of option contracts for an underlying symbol
/// </summary>
public IOptionChainProvider OptionChainProvider => _baseAlgorithm.OptionChainProvider;
/// <summary>
/// Gets the future chain provider, used to get the list of future contracts for an underlying symbol
/// </summary>
public IFutureChainProvider FutureChainProvider => _baseAlgorithm.FutureChainProvider;
/// <summary>
/// Gets the object store, used for persistence
/// </summary>
public ObjectStore ObjectStore => _baseAlgorithm.ObjectStore;
/// <summary>
/// Returns the current Slice object
/// </summary>
public Slice CurrentSlice => _baseAlgorithm.CurrentSlice;
/// <summary>
/// Algorithm start date for backtesting, set by the SetStartDate methods.
/// </summary>
public DateTime StartDate => _baseAlgorithm.StartDate;
/// <summary>
/// Gets or sets the current status of the algorithm
/// </summary>
public AlgorithmStatus Status
{
get
{
return _baseAlgorithm.Status;
}
set
{
SetStatus(value);
}
}
/// <summary>
/// Set the state of a live deployment
/// </summary>
/// <param name="status">Live deployment status</param>
public void SetStatus(AlgorithmStatus status) => _baseAlgorithm.SetStatus(status);
/// <summary>
/// Set the available <see cref="TickType"/> supported by each <see cref="SecurityType"/> in <see cref="SecurityManager"/>
/// </summary>
/// <param name="availableDataTypes">>The different <see cref="TickType"/> each <see cref="Security"/> supports</param>
public void SetAvailableDataTypes(Dictionary<SecurityType, List<TickType>> availableDataTypes) => _baseAlgorithm.SetAvailableDataTypes(availableDataTypes);
/// <summary>
/// Sets the option chain provider, used to get the list of option contracts for an underlying symbol
/// </summary>
/// <param name="optionChainProvider">The option chain provider</param>
public void SetOptionChainProvider(IOptionChainProvider optionChainProvider) => _baseAlgorithm.SetOptionChainProvider(optionChainProvider);
/// <summary>
/// Sets the future chain provider, used to get the list of future contracts for an underlying symbol
/// </summary>
/// <param name="futureChainProvider">The future chain provider</param>
public void SetFutureChainProvider(IFutureChainProvider futureChainProvider) => _baseAlgorithm.SetFutureChainProvider(futureChainProvider);
/// <summary>
/// Event fired when an algorithm generates a insight
/// </summary>
public event AlgorithmEvent<GeneratedInsightsCollection> InsightsGenerated
{
add
{
_baseAlgorithm.InsightsGenerated += value;
}
remove
{
_baseAlgorithm.InsightsGenerated -= value;
}
}
/// <summary>
/// Gets the time keeper instance
/// </summary>
public ITimeKeeper TimeKeeper => _baseAlgorithm.TimeKeeper;
/// <summary>
/// Data subscription manager controls the information and subscriptions the algorithms recieves.
/// Subscription configurations can be added through the Subscription Manager.
/// </summary>
public SubscriptionManager SubscriptionManager => _baseAlgorithm.SubscriptionManager;
/// <summary>
/// The project id associated with this algorithm if any
/// </summary>
public int ProjectId
{
set
{
_baseAlgorithm.ProjectId = value;
}
get
{
return _baseAlgorithm.ProjectId;
}
}
/// <summary>
/// Current date/time in the algorithm's local time zone
/// </summary>
public DateTime Time => _baseAlgorithm.Time;
/// <summary>
/// Gets the time zone of the algorithm
/// </summary>
public DateTimeZone TimeZone => _baseAlgorithm.TimeZone;
/// <summary>
/// Security transaction manager class controls the store and processing of orders.
/// </summary>
/// <remarks>The orders and their associated events are accessible here. When a new OrderEvent is recieved the algorithm portfolio is updated.</remarks>
public SecurityTransactionManager Transactions => _baseAlgorithm.Transactions;
/// <summary>
/// Gets the collection of universes for the algorithm
/// </summary>
public UniverseManager UniverseManager => _baseAlgorithm.UniverseManager;
/// <summary>
/// Gets the subscription settings to be used when adding securities via universe selection
/// </summary>
public UniverseSettings UniverseSettings => _baseAlgorithm.UniverseSettings;
/// <summary>
/// Current date/time in UTC.
/// </summary>
public DateTime UtcTime => _baseAlgorithm.UtcTime;
/// <summary>
/// Gets the account currency
/// </summary>
public string AccountCurrency => _baseAlgorithm.AccountCurrency;
/// <summary>
/// Gets the insight manager
/// </summary>
public InsightManager Insights => _baseAlgorithm.Insights;
/// <summary>
/// Sets the statistics service instance to be used by the algorithm
/// </summary>
/// <param name="statisticsService">The statistics service instance</param>
public void SetStatisticsService(IStatisticsService statisticsService) => _baseAlgorithm.SetStatisticsService(statisticsService);
/// <summary>
/// The current statistics for the running algorithm.
/// </summary>
public StatisticsResults Statistics => _baseAlgorithm.Statistics;
/// <summary>
/// SignalExport - Allows sending export signals to different 3rd party API's. For example, it allows to send signals
/// to Collective2, CrunchDAO and Numerai API's
/// </summary>
public SignalExportManager SignalExport => ((QCAlgorithm)_baseAlgorithm).SignalExport;
/// <summary>
/// The execution model
/// </summary>
public IExecutionModel Execution => ((QCAlgorithm)_baseAlgorithm).Execution;
/// <summary>
/// Set a required SecurityType-symbol and resolution for algorithm
/// </summary>
/// <param name="securityType">SecurityType Enum: Equity, Commodity, FOREX or Future</param>
/// <param name="symbol">Symbol Representation of the MarketType, e.g. AAPL</param>
/// <param name="resolution">The <see cref="Resolution"/> of market data, Tick, Second, Minute, Hour, or Daily.</param>
/// <param name="market">The market the requested security belongs to, such as 'usa' or 'fxcm'</param>
/// <param name="fillForward">If true, returns the last available data even if none in that timeslice.</param>
/// <param name="leverage">leverage for this security</param>
/// <param name="extendedMarketHours">Use extended market hours data</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the security</param>
public Security AddSecurity(SecurityType securityType, string symbol, Resolution? resolution, string market, bool? fillForward, decimal leverage, bool? extendedMarketHours,
DataMappingMode? dataMappingMode = null, DataNormalizationMode? dataNormalizationMode = null)
=> _baseAlgorithm.AddSecurity(securityType, symbol, resolution, market, fillForward, leverage, extendedMarketHours, dataMappingMode, dataNormalizationMode);
/// <summary>
/// Set a required SecurityType-symbol and resolution for algorithm
/// </summary>
/// <param name="symbol">The security Symbol</param>
/// <param name="resolution">Resolution of the MarketType required: MarketData, Second or Minute</param>
/// <param name="fillForward">If true, returns the last available data even if none in that timeslice.</param>
/// <param name="leverage">leverage for this security</param>
/// <param name="extendedMarketHours">Use extended market hours data</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the security</param>
/// <param name="contractDepthOffset">The continuous contract desired offset from the current front month.
/// For example, 0 (default) will use the front month, 1 will use the back month contract</param>
/// <returns>The new Security that was added to the algorithm</returns>
public Security AddSecurity(Symbol symbol, Resolution? resolution = null, bool? fillForward = null, decimal leverage = Security.NullLeverage, bool? extendedMarketHours = null,
DataMappingMode? dataMappingMode = null, DataNormalizationMode? dataNormalizationMode = null, int contractDepthOffset = 0)
=> _baseAlgorithm.AddSecurity(symbol, resolution, fillForward, leverage, extendedMarketHours, dataMappingMode, dataNormalizationMode, contractDepthOffset);
/// <summary>
/// Creates and adds a new single <see cref="Future"/> contract to the algorithm
/// </summary>
/// <param name="symbol">The futures contract symbol</param>
/// <param name="resolution">The <see cref="Resolution"/> of market data, Tick, Second, Minute, Hour, or Daily. Default is <see cref="Resolution.Minute"/></param>
/// <param name="fillForward">If true, returns the last available data even if none in that timeslice. Default is <value>true</value></param>
/// <param name="leverage">The requested leverage for this equity. Default is set by <see cref="SecurityInitializer"/></param>
/// <param name="extendedMarketHours">Use extended market hours data</param>
/// <returns>The new <see cref="Future"/> security</returns>
public Future AddFutureContract(Symbol symbol, Resolution? resolution = null, bool fillForward = true, decimal leverage = 0m,
bool extendedMarketHours = false)
=> _baseAlgorithm.AddFutureContract(symbol, resolution, fillForward, leverage, extendedMarketHours);
/// <summary>
/// Creates and adds a new single <see cref="Option"/> contract to the algorithm
/// </summary>
/// <param name="symbol">The option contract symbol</param>
/// <param name="resolution">The <see cref="Resolution"/> of market data, Tick, Second, Minute, Hour, or Daily. Default is <see cref="Resolution.Minute"/></param>
/// <param name="fillForward">If true, returns the last available data even if none in that timeslice. Default is <value>true</value></param>
/// <param name="leverage">The requested leverage for this equity. Default is set by <see cref="SecurityInitializer"/></param>
/// <param name="extendedMarketHours">Use extended market hours data</param>
/// <returns>The new <see cref="Option"/> security</returns>
public Option AddOptionContract(Symbol symbol, Resolution? resolution = null, bool fillForward = true, decimal leverage = 0m, bool extendedMarketHours = false)
=> _baseAlgorithm.AddOptionContract(symbol, resolution, fillForward, leverage, extendedMarketHours);
/// <summary>
/// Invoked at the end of every time step. This allows the algorithm
/// to process events before advancing to the next time step.
/// </summary>
public void OnEndOfTimeStep()
{
_baseAlgorithm.OnEndOfTimeStep();
}
/// <summary>
/// Send debug message
/// </summary>
/// <param name="message">String message</param>
public void Debug(string message) => _baseAlgorithm.Debug(message);
/// <summary>
/// Send an error message for the algorithm
/// </summary>
/// <param name="message">String message</param>
public void Error(string message) => _baseAlgorithm.Error(message);
/// <summary>
/// Add a Chart object to algorithm collection
/// </summary>
/// <param name="chart">Chart object to add to collection.</param>
public void AddChart(Chart chart) => _baseAlgorithm.AddChart(chart);
/// <summary>
/// Get the chart updates since the last request:
/// </summary>
/// <param name="clearChartData"></param>
/// <returns>List of Chart Updates</returns>
public IEnumerable<Chart> GetChartUpdates(bool clearChartData = false) => _baseAlgorithm.GetChartUpdates(clearChartData);
/// <summary>
/// Gets whether or not this algorithm has been locked and fully initialized
/// </summary>
public bool GetLocked() => _baseAlgorithm.GetLocked();
/// <summary>
/// Gets a read-only dictionary with all current parameters
/// </summary>
public ReadOnlyExtendedDictionary<string, string> GetParameters() => _baseAlgorithm.GetParameters();
/// <summary>
/// Gets the parameter with the specified name. If a parameter with the specified name does not exist,
/// the given default value is returned if any, else null
/// </summary>
/// <param name="name">The name of the parameter to get</param>
/// <param name="defaultValue">The default value to return</param>
/// <returns>The value of the specified parameter, or defaultValue if not found or null if there's no default value</returns>
public string GetParameter(string name, string defaultValue = null) => _baseAlgorithm.GetParameter(name, defaultValue);
/// <summary>
/// Gets the parameter with the specified name parsed as an integer. If a parameter with the specified name does not exist,
/// or the conversion is not possible, the given default value is returned
/// </summary>
/// <param name="name">The name of the parameter to get</param>
/// <param name="defaultValue">The default value to return</param>
/// <returns>The value of the specified parameter, or defaultValue if not found or null if there's no default value</returns>
public int GetParameter(string name, int defaultValue) => _baseAlgorithm.GetParameter(name, defaultValue);
/// <summary>
/// Gets the parameter with the specified name parsed as a double. If a parameter with the specified name does not exist,
/// or the conversion is not possible, the given default value is returned
/// </summary>
/// <param name="name">The name of the parameter to get</param>
/// <param name="defaultValue">The default value to return</param>
/// <returns>The value of the specified parameter, or defaultValue if not found or null if there's no default value</returns>
public double GetParameter(string name, double defaultValue) => _baseAlgorithm.GetParameter(name, defaultValue);
/// <summary>
/// Gets the parameter with the specified name parsed as a decimal. If a parameter with the specified name does not exist,
/// or the conversion is not possible, the given default value is returned
/// </summary>
/// <param name="name">The name of the parameter to get</param>
/// <param name="defaultValue">The default value to return</param>
/// <returns>The value of the specified parameter, or defaultValue if not found or null if there's no default value</returns>
public decimal GetParameter(string name, decimal defaultValue) => _baseAlgorithm.GetParameter(name, defaultValue);
/// <summary>
/// Initialise the Algorithm and Prepare Required Data:
/// </summary>
public void Initialize()
{
InvokeMethod(nameof(Initialize));
}
/// <summary>
/// Liquidate your portfolio holdings
/// </summary>
/// <param name="symbol">Specific asset to liquidate, defaults to all</param>
/// <param name="asynchronous">Flag to indicate if the symbols should be liquidated asynchronously</param>
/// <param name="tag">Custom tag to know who is calling this</param>
/// <param name="orderProperties">Order properties to use</param>
public List<OrderTicket> Liquidate(Symbol symbol = null, bool asynchronous = false, string tag = "Liquidated", IOrderProperties orderProperties = null) => _baseAlgorithm.Liquidate(symbol, asynchronous, tag, orderProperties);
/// <summary>
/// Save entry to the Log
/// </summary>
/// <param name="message">String message</param>
public void Log(string message) => _baseAlgorithm.Log(message);
/// <summary>
/// Brokerage disconnected event handler. This method is called when the brokerage connection is lost.
/// </summary>
public void OnBrokerageDisconnect()
{
_onBrokerageDisconnect();
}
/// <summary>
/// Brokerage message event handler. This method is called for all types of brokerage messages.
/// </summary>
public void OnBrokerageMessage(BrokerageMessageEvent messageEvent)
{
_onBrokerageMessage(messageEvent);
}
/// <summary>
/// Brokerage reconnected event handler. This method is called when the brokerage connection is restored after a disconnection.
/// </summary>
public void OnBrokerageReconnect()
{
_onBrokerageReconnect();
}
/// <summary>
/// v3.0 Handler for all data types
/// </summary>
/// <param name="slice">The current slice of data</param>
public void OnData(Slice slice)
{
if (_onData != null)
{
using (Py.GIL())
{
_onData(slice);
}
}
}
/// <summary>
/// Used to send data updates to algorithm framework models
/// </summary>
/// <param name="slice">The current data slice</param>
public void OnFrameworkData(Slice slice)
{
_baseAlgorithm.OnFrameworkData(slice);
}
/// <summary>
/// Event handler to be called when there's been a split event
/// </summary>
/// <param name="splits">The current time slice splits</param>
public void OnSplits(Splits splits)
{
_onSplits(splits);
}
/// <summary>
/// Event handler to be called when there's been a dividend event
/// </summary>
/// <param name="dividends">The current time slice dividends</param>
public void OnDividends(Dividends dividends)
{
_onDividends(dividends);
}
/// <summary>
/// Event handler to be called when there's been a delistings event
/// </summary>
/// <param name="delistings">The current time slice delistings</param>
public void OnDelistings(Delistings delistings)
{
_onDelistings(delistings);
}
/// <summary>
/// Event handler to be called when there's been a symbol changed event
/// </summary>
/// <param name="symbolsChanged">The current time slice symbol changed events</param>
public void OnSymbolChangedEvents(SymbolChangedEvents symbolsChanged)
{
_onSymbolChangedEvents(symbolsChanged);
}
/// <summary>
/// Call this event at the end of the algorithm running.
/// </summary>
public void OnEndOfAlgorithm()
{
InvokeMethod(nameof(OnEndOfAlgorithm));
}
/// <summary>
/// End of a trading day event handler. This method is called at the end of the algorithm day (or multiple times if trading multiple assets).
/// </summary>
/// <remarks>Method is called 10 minutes before closing to allow user to close out position.</remarks>
/// <remarks>Deprecated because different assets have different market close times,
/// and because Python does not support two methods with the same name</remarks>
[Obsolete("This method is deprecated. Please use this overload: OnEndOfDay(Symbol symbol)")]
[StubsIgnore]
public void OnEndOfDay()
{
try
{
_onEndOfDay();
}
// If OnEndOfDay is not defined in the script, but OnEndOfDay(Symbol) is, a python exception occurs
// Only throws if there is an error in its implementation body
catch (PythonException exception)
{
if (!exception.Message.Contains("OnEndOfDay() missing 1 required positional argument"))
{
_baseAlgorithm.SetRunTimeError(exception);
}
}
}
/// <summary>
/// End of a trading day event handler. This method is called at the end of the algorithm day (or multiple times if trading multiple assets).
/// </summary>
/// <remarks>
/// This method is left for backwards compatibility and is invoked via <see cref="OnEndOfDay(Symbol)"/>, if that method is
/// override then this method will not be called without a called to base.OnEndOfDay(string)
/// </remarks>
/// <param name="symbol">Asset symbol for this end of day event. Forex and equities have different closing hours.</param>
[StubsAvoidImplicits]
public void OnEndOfDay(Symbol symbol)
{
try
{
_onEndOfDay(symbol);
}
// If OnEndOfDay(Symbol) is not defined in the script, but OnEndOfDay is, a python exception occurs
// Only throws if there is an error in its implementation body
catch (PythonException exception)
{
if (!exception.Message.Contains("OnEndOfDay() takes 1 positional argument but 2 were given"))
{
_baseAlgorithm.SetRunTimeError(exception);
}
}
}
/// <summary>
/// Margin call event handler. This method is called right before the margin call orders are placed in the market.
/// </summary>
/// <param name="requests">The orders to be executed to bring this algorithm within margin limits</param>
public void OnMarginCall(List<SubmitOrderRequest> requests)
{
using (Py.GIL())
{
var result = InvokeMethod(nameof(OnMarginCall), requests);
if (_onMarginCall != null)
{
// If the method does not return or returns a non-iterable PyObject, throw an exception
if (result == null || !result.IsIterable())
{
throw new Exception("OnMarginCall must return a non-empty list of SubmitOrderRequest");
}
requests.Clear();
using var iterator = result.GetIterator();
foreach (PyObject pyRequest in iterator)
{
SubmitOrderRequest request;
if (TryConvert(pyRequest, out request))
{
requests.Add(request);
}
}
// If the PyObject is an empty list or its items are not SubmitOrderRequest objects, throw an exception
if (requests.Count == 0)
{
throw new Exception("OnMarginCall must return a non-empty list of SubmitOrderRequest");
}
}
}
}
/// <summary>
/// Margin call warning event handler. This method is called when Portfolio.MarginRemaining is under 5% of your Portfolio.TotalPortfolioValue
/// </summary>
public void OnMarginCallWarning()
{
_onMarginCallWarning();
}
/// <summary>
/// EXPERTS ONLY:: [-!-Async Code-!-]
/// New order event handler: on order status changes (filled, partially filled, cancelled etc).
/// </summary>
/// <param name="newEvent">Event information</param>
public void OnOrderEvent(OrderEvent newEvent)
{
_onOrderEvent(newEvent);
}
/// <summary>
/// Generic untyped command call handler
/// </summary>
/// <param name="data">The associated data</param>
/// <returns>True if success, false otherwise. Returning null will disable command feedback</returns>
public bool? OnCommand(dynamic data)
{
return _onCommand(data);
}
/// <summary>
/// Will submit an order request to the algorithm
/// </summary>
/// <param name="request">The request to submit</param>
/// <remarks>Will run order prechecks, which include making sure the algorithm is not warming up, security is added and has data among others</remarks>
/// <returns>The order ticket</returns>
public OrderTicket SubmitOrderRequest(SubmitOrderRequest request)
{
return _baseAlgorithm.SubmitOrderRequest(request);
}
/// <summary>
/// Option assignment event handler. On an option assignment event for short legs the resulting information is passed to this method.
/// </summary>
/// <param name="assignmentEvent">Option exercise event details containing details of the assignment</param>
/// <remarks>This method can be called asynchronously and so should only be used by seasoned C# experts. Ensure you use proper locks on thread-unsafe objects</remarks>
public void OnAssignmentOrderEvent(OrderEvent assignmentEvent)
{
_onAssignmentOrderEvent(assignmentEvent);
}
/// <summary>
/// Event fired each time the we add/remove securities from the data feed
/// </summary>
/// <param name="changes">Security additions/removals for this time step</param>
public void OnSecuritiesChanged(SecurityChanges changes)
{
_onSecuritiesChanged(changes);
}
/// <summary>
/// Used to send security changes to algorithm framework models
/// </summary>
/// <param name="changes">Security additions/removals for this time step</param>
public void OnFrameworkSecuritiesChanged(SecurityChanges changes)
{
_onFrameworkSecuritiesChanged(changes);
}
/// <summary>
/// Called by setup handlers after Initialize and allows the algorithm a chance to organize
/// the data gather in the Initialize method
/// </summary>
public void PostInitialize()
{