Lean  $LEAN_TAG$
Global.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14 */
15 
16 using System;
17 using Newtonsoft.Json;
18 using Newtonsoft.Json.Linq;
19 using System.ComponentModel;
21 using Newtonsoft.Json.Converters;
22 using System.Runtime.Serialization;
23 using System.Runtime.CompilerServices;
24 
25 namespace QuantConnect
26 {
27  /// <summary>
28  /// Shortcut date format strings
29  /// </summary>
30  public static class DateFormat
31  {
32  /// Year-Month-Date 6 Character Date Representation
33  public const string SixCharacter = "yyMMdd";
34  /// YYYY-MM-DD Eight Character Date Representation
35  public const string EightCharacter = "yyyyMMdd";
36  /// Daily and hourly time format
37  public const string TwelveCharacter = "yyyyMMdd HH:mm";
38  /// JSON Format Date Representation
39  public static string JsonFormat { get; } = "yyyy-MM-ddTHH:mm:ss";
40  /// MySQL Format Date Representation
41  public const string DB = "yyyy-MM-dd HH:mm:ss";
42  /// QuantConnect UX Date Representation
43  public const string UI = "yyyy-MM-dd HH:mm:ss";
44  /// en-US Short Date and Time Pattern
45  public const string USShort = "M/d/yy h:mm tt";
46  /// en-US Short Date Pattern
47  public const string USShortDateOnly = "M/d/yy";
48  /// en-US format
49  public const string US = "M/d/yyyy h:mm:ss tt";
50  /// en-US Date format
51  public const string USDateOnly = "M/d/yyyy";
52  /// Date format of QC forex data
53  public const string Forex = "yyyyMMdd HH:mm:ss.ffff";
54  /// Date format of FIX Protocol UTC Timestamp without milliseconds
55  public const string FIX = "yyyyMMdd-HH:mm:ss";
56  /// Date format of FIX Protocol UTC Timestamp with milliseconds
57  public const string FIXWithMillisecond = "yyyyMMdd-HH:mm:ss.fff";
58  /// YYYYMM Year and Month Character Date Representation (used for futures)
59  public const string YearMonth = "yyyyMM";
60  }
61 
62  /// <summary>
63  /// Singular holding of assets from backend live nodes:
64  /// </summary>
65  [JsonConverter(typeof(HoldingJsonConverter))]
66  public class Holding
67  {
68  private decimal? _conversionRate;
69  private decimal _marketValue;
70  private decimal _unrealizedPnl;
71  private decimal _unrealizedPnLPercent;
72 
73  /// Symbol of the Holding:
74  [JsonIgnore]
75  public Symbol Symbol { get; set; } = Symbol.Empty;
76 
77  /// Type of the security
78  [JsonIgnore]
80 
81  /// The currency symbol of the holding, such as $
82  [DefaultValue("$")]
83  [JsonProperty(PropertyName = "c", DefaultValueHandling = DefaultValueHandling.Ignore)]
84  public string CurrencySymbol { get; set; }
85 
86  /// Average Price of our Holding in the currency the symbol is traded in
87  [JsonConverter(typeof(DecimalJsonConverter))]
88  [JsonProperty(PropertyName = "a", DefaultValueHandling = DefaultValueHandling.Ignore)]
89  public decimal AveragePrice { get; set; }
90 
91  /// Quantity of Symbol We Hold.
92  [JsonConverter(typeof(DecimalJsonConverter))]
93  [JsonProperty(PropertyName = "q", DefaultValueHandling = DefaultValueHandling.Ignore)]
94  public decimal Quantity { get; set; }
95 
96  /// Current Market Price of the Asset in the currency the symbol is traded in
97  [JsonConverter(typeof(DecimalJsonConverter))]
98  [JsonProperty(PropertyName = "p", DefaultValueHandling = DefaultValueHandling.Ignore)]
99  public decimal MarketPrice { get; set; }
100 
101  /// Current market conversion rate into the account currency
102  [JsonConverter(typeof(DecimalJsonConverter))]
103  [JsonProperty(PropertyName = "r", DefaultValueHandling = DefaultValueHandling.Ignore)]
104  public decimal? ConversionRate
105  {
106  get
107  {
108  return _conversionRate;
109  }
110  set
111  {
112  if (value != 1)
113  {
114  _conversionRate = value;
115  }
116  }
117  }
118 
119  /// Current market value of the holding
120  [JsonConverter(typeof(DecimalJsonConverter))]
121  [JsonProperty(PropertyName = "v", DefaultValueHandling = DefaultValueHandling.Ignore)]
122  public decimal MarketValue
123  {
124  get
125  {
126  return _marketValue;
127  }
128  set
129  {
130  _marketValue = value.SmartRoundingShort();
131  }
132  }
133 
134  /// Current unrealized P/L of the holding
135  [JsonConverter(typeof(DecimalJsonConverter))]
136  [JsonProperty(PropertyName = "u", DefaultValueHandling = DefaultValueHandling.Ignore)]
137  public decimal UnrealizedPnL
138  {
139  get
140  {
141  return _unrealizedPnl;
142  }
143  set
144  {
145  _unrealizedPnl = value.SmartRoundingShort();
146  }
147  }
148 
149  /// Current unrealized P/L % of the holding
150  [JsonConverter(typeof(DecimalJsonConverter))]
151  [JsonProperty(PropertyName = "up", DefaultValueHandling = DefaultValueHandling.Ignore)]
152  public decimal UnrealizedPnLPercent
153  {
154  get
155  {
156  return _unrealizedPnLPercent;
157  }
158  set
159  {
160  _unrealizedPnLPercent = value.SmartRoundingShort();
161  }
162  }
163 
164  /// Create a new default holding:
165  public Holding()
166  {
167  CurrencySymbol = "$";
168  }
169 
170  /// <summary>
171  /// Create a simple JSON holdings from a Security holding class.
172  /// </summary>
173  /// <param name="security">The security instance</param>
174  public Holding(Security security)
175  : this()
176  {
177  var holding = security.Holdings;
178 
179  Symbol = holding.Symbol;
180  Quantity = holding.Quantity;
181  MarketValue = holding.HoldingsValue;
184 
185  var rounding = security.SymbolProperties.MinimumPriceVariation.GetDecimalPlaces();
186 
187  AveragePrice = Math.Round(holding.AveragePrice, rounding);
188  MarketPrice = Math.Round(holding.Price, rounding);
189  UnrealizedPnL = Math.Round(holding.UnrealizedProfit, 2);
190  UnrealizedPnLPercent = Math.Round(holding.UnrealizedProfitPercent * 100, 2);
191  }
192 
193  /// <summary>
194  /// Clones this instance
195  /// </summary>
196  /// <returns>A new Holding object with the same values as this one</returns>
197  public Holding Clone()
198  {
199  return new Holding
200  {
202  Symbol = Symbol,
203  Quantity = Quantity,
210  };
211  }
212 
213  /// <summary>
214  /// Writes out the properties of this instance to string
215  /// </summary>
216  public override string ToString()
217  {
218  return Messages.Holding.ToString(this);
219  }
220 
221  private class DecimalJsonConverter : JsonConverter
222  {
223  public override bool CanRead => false;
224  public override bool CanConvert(Type objectType) => typeof(decimal) == objectType;
225  public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
226  {
227  writer.WriteRawValue(((decimal)value).NormalizeToStr());
228  }
229  public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
230  {
231  throw new NotImplementedException();
232  }
233  }
234  private class HoldingJsonConverter : JsonConverter
235  {
236  public override bool CanWrite => false;
237  public override bool CanConvert(Type objectType) => typeof(Holding) == objectType;
238  public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
239  {
240  var jObject = JObject.Load(reader);
241  var result = new Holding
242  {
243  Symbol = jObject["symbol"]?.ToObject<Symbol>() ?? jObject["Symbol"]?.ToObject<Symbol>() ?? Symbol.Empty,
244  CurrencySymbol = jObject["c"]?.Value<string>() ?? jObject["currencySymbol"]?.Value<string>() ?? jObject["CurrencySymbol"]?.Value<string>() ?? string.Empty,
245  AveragePrice = jObject["a"]?.Value<decimal>() ?? jObject["averagePrice"]?.Value<decimal>() ?? jObject["AveragePrice"]?.Value<decimal>() ?? 0,
246  Quantity = jObject["q"]?.Value<decimal>() ?? jObject["quantity"]?.Value<decimal>() ?? jObject["Quantity"]?.Value<decimal>() ?? 0,
247  MarketPrice = jObject["p"]?.Value<decimal>() ?? jObject["marketPrice"]?.Value<decimal>() ?? jObject["MarketPrice"]?.Value<decimal>() ?? 0,
248  ConversionRate = jObject["r"]?.Value<decimal>() ?? jObject["conversionRate"]?.Value<decimal>() ?? jObject["ConversionRate"]?.Value<decimal>() ?? null,
249  MarketValue = jObject["v"]?.Value<decimal>() ?? jObject["marketValue"]?.Value<decimal>() ?? jObject["MarketValue"]?.Value<decimal>() ?? 0,
250  UnrealizedPnL = jObject["u"]?.Value<decimal>() ?? jObject["unrealizedPnl"]?.Value<decimal>() ?? jObject["UnrealizedPnl"]?.Value<decimal>() ?? 0,
251  UnrealizedPnLPercent = jObject["up"]?.Value<decimal>() ?? jObject["unrealizedPnLPercent"]?.Value<decimal>() ?? jObject["UnrealizedPnLPercent"]?.Value<decimal>() ?? 0,
252  };
253  if (!result.ConversionRate.HasValue)
254  {
255  result.ConversionRate = 1;
256  }
257  if (string.IsNullOrEmpty(result.CurrencySymbol))
258  {
259  result.CurrencySymbol = "$";
260  }
261  return result;
262  }
263  public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
264  {
265  throw new NotImplementedException();
266  }
267  }
268  }
269 
270  /// <summary>
271  /// Represents the types of environments supported by brokerages for trading
272  /// </summary>
273  [JsonConverter(typeof(StringEnumConverter))]
275  {
276  /// <summary>
277  /// Live trading (0)
278  /// </summary>
279  [EnumMember(Value = "live")]
280  Live,
281 
282  /// <summary>
283  /// Paper trading (1)
284  /// </summary>
285  [EnumMember(Value = "paper")]
286  Paper
287  }
288 
289  /// <summary>
290  /// Multilanguage support enum: which language is this project for the interop bridge converter.
291  /// </summary>
292  [JsonConverter(typeof(StringEnumConverter))]
293  public enum Language
294  {
295  /// <summary>
296  /// C# Language Project (0)
297  /// </summary>
298  [EnumMember(Value = "C#")]
299  CSharp,
300 
301  /// <summary>
302  /// FSharp Project (1)
303  /// </summary>
304  [EnumMember(Value = "F#")]
305  FSharp,
306 
307  /// <summary>
308  /// Visual Basic Project (2)
309  /// </summary>
310  [EnumMember(Value = "VB")]
311  VisualBasic,
312 
313  /// <summary>
314  /// Java Language Project (3)
315  /// </summary>
316  [EnumMember(Value = "Ja")]
317  Java,
318 
319  /// <summary>
320  /// Python Language Project (4)
321  /// </summary>
322  [EnumMember(Value = "Py")]
323  Python
324  }
325 
326  /// <summary>
327  /// Live server types available through the web IDE. / QC deployment.
328  /// </summary>
329  public enum ServerType
330  {
331  /// <summary>
332  /// Additional server (0)
333  /// </summary>
334  Server512,
335 
336  /// <summary>
337  /// Upgraded server (1)
338  /// </summary>
339  Server1024,
340 
341  /// <summary>
342  /// Server with 2048 MB Ram (2)
343  /// </summary>
344  Server2048
345  }
346 
347  /// <summary>
348  /// Type of tradable security / underlying asset
349  /// </summary>
350  public enum SecurityType
351  {
352  /// <summary>
353  /// Base class for all security types (0)
354  /// </summary>
355  Base,
356 
357  /// <summary>
358  /// US Equity Security (1)
359  /// </summary>
360  Equity,
361 
362  /// <summary>
363  /// Option Security Type (2)
364  /// </summary>
365  Option,
366 
367  /// <summary>
368  /// Commodity Security Type (3)
369  /// </summary>
370  Commodity,
371 
372  /// <summary>
373  /// FOREX Security (4)
374  /// </summary>
375  Forex,
376 
377  /// <summary>
378  /// Future Security Type (5)
379  /// </summary>
380  Future,
381 
382  /// <summary>
383  /// Contract For a Difference Security Type (6)
384  /// </summary>
385  Cfd,
386 
387  /// <summary>
388  /// Cryptocurrency Security Type (7)
389  /// </summary>
390  Crypto,
391 
392  /// <summary>
393  /// Futures Options Security Type (8)
394  /// </summary>
395  /// <remarks>
396  /// Futures options function similar to equity options, but with a few key differences.
397  /// Firstly, the contract unit of trade is 1x, rather than 100x. This means that each
398  /// option represents the right to buy or sell 1 future contract at expiry/exercise.
399  /// The contract multiplier for Futures Options plays a big part in determining the premium
400  /// of the option, which can also differ from the underlying future's multiplier.
401  /// </remarks>
402  FutureOption,
403 
404  /// <summary>
405  /// Index Security Type (9)
406  /// </summary>
407  Index,
408 
409  /// <summary>
410  /// Index Option Security Type (10)
411  /// </summary>
412  /// <remarks>
413  /// For index options traded on American markets, they tend to be European-style options and are Cash-settled.
414  /// </remarks>
415  IndexOption,
416 
417  /// <summary>
418  /// Crypto Future Type (11)
419  /// </summary>
420  CryptoFuture,
421  }
422 
423  /// <summary>
424  /// Account type: margin or cash
425  /// </summary>
426  public enum AccountType
427  {
428  /// <summary>
429  /// Margin account type (0)
430  /// </summary>
431  Margin,
432 
433  /// <summary>
434  /// Cash account type (1)
435  /// </summary>
436  Cash
437  }
438 
439  /// <summary>
440  /// Market data style: is the market data a summary (OHLC style) bar, or is it a time-price value.
441  /// </summary>
442  public enum MarketDataType
443  {
444  /// Base market data type (0)
445  Base,
446  /// TradeBar market data type (OHLC summary bar) (1)
447  TradeBar,
448  /// Tick market data type (price-time pair) (2)
449  Tick,
450  /// Data associated with an instrument (3)
451  Auxiliary,
452  /// QuoteBar market data type (4) [Bid(OHLC), Ask(OHLC) and Mid(OHLC) summary bar]
453  QuoteBar,
454  /// Option chain data (5)
455  OptionChain,
456  /// Futures chain data (6)
458  }
459 
460  /// <summary>
461  /// Datafeed enum options for selecting the source of the datafeed.
462  /// </summary>
463  public enum DataFeedEndpoint
464  {
465  /// Backtesting Datafeed Endpoint (0)
466  Backtesting,
467  /// Loading files off the local system (1)
468  FileSystem,
469  /// Getting datafeed from a QC-Live-Cloud (2)
470  LiveTrading,
471  /// Database (3)
472  Database
473  }
474 
475  /// <summary>
476  /// Cloud storage permission options.
477  /// </summary>
478  public enum StoragePermissions
479  {
480  /// Public Storage Permissions (0)
481  Public,
482 
483  /// Authenticated Read Storage Permissions (1)
485  }
486 
487  /// <summary>
488  /// Types of tick data
489  /// </summary>
490  /// <remarks>QuantConnect currently only has trade, quote, open interest tick data.</remarks>
491  public enum TickType
492  {
493  /// Trade type tick object (0)
494  Trade ,
495  /// Quote type tick object (1)
496  Quote,
497  /// Open Interest type tick object (for options, futures) (2)
499  }
500 
501  /// <summary>
502  /// Specifies the type of <see cref="QuantConnect.Data.Market.Delisting"/> data
503  /// </summary>
504  public enum DelistingType
505  {
506  /// <summary>
507  /// Specifies a warning of an imminent delisting (0)
508  /// </summary>
509  Warning = 0,
510 
511  /// <summary>
512  /// Specifies the symbol has been delisted (1)
513  /// </summary>
514  Delisted = 1
515  }
516 
517  /// <summary>
518  /// Specifies the type of <see cref="QuantConnect.Data.Market.Split"/> data
519  /// </summary>
520  public enum SplitType
521  {
522  /// <summary>
523  /// Specifies a warning of an imminent split event (0)
524  /// </summary>
525  Warning = 0,
526 
527  /// <summary>
528  /// Specifies the symbol has been split (1)
529  /// </summary>
530  SplitOccurred = 1
531  }
532 
533  /// <summary>
534  /// Resolution of data requested.
535  /// </summary>
536  /// <remarks>Always sort the enum from the smallest to largest resolution</remarks>
537  public enum Resolution
538  {
539  /// Tick Resolution (0)
540  Tick,
541  /// Second Resolution (1)
542  Second,
543  /// Minute Resolution (2)
544  Minute,
545  /// Hour Resolution (3)
546  Hour,
547  /// Daily Resolution (4)
548  Daily
549  }
550 
551  /// <summary>
552  /// Specifies what side a position is on, long/short
553  /// </summary>
554  public enum PositionSide
555  {
556  /// <summary>
557  /// A short position, quantity less than zero (-1)
558  /// </summary>
559  Short = -1,
560 
561  /// <summary>
562  /// No position, quantity equals zero (0)
563  /// </summary>
564  None = 0,
565 
566  /// <summary>
567  /// A long position, quantity greater than zero (1)
568  /// </summary>
569  Long = 1
570  }
571 
572  /// <summary>
573  /// Specifies the different types of options
574  /// </summary>
575  public enum OptionRight
576  {
577  /// <summary>
578  /// A call option, the right to buy at the strike price (0)
579  /// </summary>
580  Call,
581 
582  /// <summary>
583  /// A put option, the right to sell at the strike price (1)
584  /// </summary>
585  Put
586  }
587 
588  /// <summary>
589  /// Specifies the style of an option
590  /// </summary>
591  public enum OptionStyle
592  {
593  /// <summary>
594  /// American style options are able to be exercised at any time on or before the expiration date (0)
595  /// </summary>
596  American,
597 
598  /// <summary>
599  /// European style options are able to be exercised on the expiration date only (1)
600  /// </summary>
601  European
602  }
603 
604  /// <summary>
605  /// Specifies the type of settlement in derivative deals
606  /// </summary>
607  public enum SettlementType
608  {
609  /// <summary>
610  /// Physical delivery of the underlying security (0)
611  /// </summary>
613 
614  /// <summary>
615  /// Cash is paid/received on settlement (1)
616  /// </summary>
617  Cash
618  }
619 
620  /// <summary>
621  /// Wrapper for algorithm status enum to include the charting subscription.
622  /// </summary>
623  public class AlgorithmControl
624  {
625  /// <summary>
626  /// Default initializer for algorithm control class.
627  /// </summary>
629  {
630  // default to true, API can override
631  Initialized = false;
632  HasSubscribers = true;
633  Status = AlgorithmStatus.Running;
635  }
636 
637  /// <summary>
638  /// Register this control packet as not defaults.
639  /// </summary>
640  public bool Initialized { get; set; }
641 
642  /// <summary>
643  /// Current run status of the algorithm id.
644  /// </summary>
645  public AlgorithmStatus Status { get; set; }
646 
647  /// <summary>
648  /// Currently requested chart.
649  /// </summary>
650  public string ChartSubscription { get; set; }
651 
652  /// <summary>
653  /// True if there's subscribers on the channel
654  /// </summary>
655  public bool HasSubscribers { get; set; }
656  }
657 
658  /// <summary>
659  /// States of a live deployment.
660  /// </summary>
661  public enum AlgorithmStatus
662  {
663  /// Error compiling algorithm at start (0)
664  DeployError,
665  /// Waiting for a server (1)
666  InQueue,
667  /// Running algorithm (2)
668  Running,
669  /// Stopped algorithm or exited with runtime errors (3)
670  Stopped,
671  /// Liquidated algorithm (4)
672  Liquidated,
673  /// Algorithm has been deleted (5)
674  Deleted,
675  /// Algorithm completed running (6)
676  Completed,
677  /// Runtime Error Stoped Algorithm (7)
678  RuntimeError,
679  /// Error in the algorithm id (not used) (8)
680  Invalid,
681  /// The algorithm is logging into the brokerage (9)
682  LoggingIn,
683  /// The algorithm is initializing (10)
684  Initializing,
685  /// History status update (11)
686  History
687  }
688 
689  /// <summary>
690  /// Specifies where a subscription's data comes from
691  /// </summary>
693  {
694  /// <summary>
695  /// The subscription's data comes from disk (0)
696  /// </summary>
697  LocalFile,
698 
699  /// <summary>
700  /// The subscription's data is downloaded from a remote source (1)
701  /// </summary>
702  RemoteFile,
703 
704  /// <summary>
705  /// The subscription's data comes from a rest call that is polled and returns a single line/data point of information (2)
706  /// </summary>
707  Rest,
708 
709  /// <summary>
710  /// The subscription's data is streamed (3)
711  /// </summary>
712  Streaming,
713 
714  /// <summary>
715  /// The subscription's data comes from the object store (4)
716  /// </summary>
718  }
719 
720  /// <summary>
721  /// Used by the <see cref="Data.LeanDataWriter"/> to determine which merge write policy should be applied
722  /// </summary>
723  public enum WritePolicy
724  {
725  /// <summary>
726  /// Will overwrite any existing file or zip entry with the new content (0)
727  /// </summary>
728  Overwrite = 0,
729 
730  /// <summary>
731  /// Will inject and merge new content with the existings file content (1)
732  /// </summary>
733  Merge,
734 
735  /// <summary>
736  /// Will append new data to the end of the file or zip entry (2)
737  /// </summary>
738  Append
739  }
740 
741  /// <summary>
742  /// enum Period - Enum of all the analysis periods, AS integers. Reference "Period" Array to access the values
743  /// </summary>
744  public enum Period
745  {
746  /// Period Short Codes - 10
747  TenSeconds = 10,
748  /// Period Short Codes - 30 Second
749  ThirtySeconds = 30,
750  /// Period Short Codes - 60 Second
751  OneMinute = 60,
752  /// Period Short Codes - 120 Second
753  TwoMinutes = 120,
754  /// Period Short Codes - 180 Second
755  ThreeMinutes = 180,
756  /// Period Short Codes - 300 Second
757  FiveMinutes = 300,
758  /// Period Short Codes - 600 Second
759  TenMinutes = 600,
760  /// Period Short Codes - 900 Second
761  FifteenMinutes = 900,
762  /// Period Short Codes - 1200 Second
763  TwentyMinutes = 1200,
764  /// Period Short Codes - 1800 Second
765  ThirtyMinutes = 1800,
766  /// Period Short Codes - 3600 Second
767  OneHour = 3600,
768  /// Period Short Codes - 7200 Second
769  TwoHours = 7200,
770  /// Period Short Codes - 14400 Second
771  FourHours = 14400,
772  /// Period Short Codes - 21600 Second
773  SixHours = 21600
774  }
775 
776  /// <summary>
777  /// Specifies how data is normalized before being sent into an algorithm
778  /// </summary>
780  {
781  /// <summary>
782  /// No modifications to the asset price at all. For Equities, dividends are paid in cash and splits are applied directly to your portfolio quantity. (0)
783  /// </summary>
784  Raw,
785  /// <summary>
786  /// Splits and dividends are backward-adjusted into the price of the asset. The price today is identical to the current market price. (1)
787  /// </summary>
788  Adjusted,
789  /// <summary>
790  /// Equity splits are applied to the price adjustment but dividends are paid in cash to your portfolio. This normalization mode allows you to manage dividend payments (e.g. reinvestment) while still giving a smooth time series of prices for indicators. (2)
791  /// </summary>
793  /// <summary>
794  /// Equity splits are applied to the price adjustment and the value of all future dividend payments is added to the initial asset price. (3)
795  /// </summary>
796  TotalReturn,
797  /// <summary>
798  /// Eliminates price jumps between two consecutive contracts, adding a factor based on the difference of their prices. The first contract has the true price. Factor 0. (4)
799  /// </summary>
800  /// <remarks>First contract is the true one, factor 0</remarks>
802  /// <summary>
803  /// Eliminates price jumps between two consecutive contracts, adding a factor based on the difference of their prices. The last contract has the true price. Factor 0. (5)
804  /// </summary>
805  /// <remarks>Last contract is the true one, factor 0</remarks>
807  /// <summary>
808  /// Eliminates price jumps between two consecutive contracts, multiplying the prices by their ratio. The last contract has the true price. Factor 1. (6)
809  /// </summary>
810  /// <remarks>Last contract is the true one, factor 1</remarks>
812  /// <summary>
813  /// Splits and dividends are adjusted into the prices in a given date. Only for history requests. (7)
814  /// </summary>
815  ScaledRaw,
816  }
817 
818  /// <summary>
819  /// Continuous contracts mapping modes
820  /// </summary>
821  public enum DataMappingMode
822  {
823  /// <summary>
824  /// The contract maps on the previous day of expiration of the front month (0)
825  /// </summary>
827  /// <summary>
828  /// The contract maps on the first date of the delivery month of the front month. If the contract expires prior to this date,
829  /// then it rolls on the contract's last trading date instead (1)
830  /// </summary>
831  /// <remarks>For example, the Crude Oil WTI (CL) 'DEC 2021 CLZ1' contract expires on November, 19 2021, so the mapping date will be its expiration date.</remarks>
832  /// <remarks>Another example is the Corn 'DEC 2021 ZCZ1' contract, which expires on December, 14 2021, so the mapping date will be December 1, 2021.</remarks>
834  /// <summary>
835  /// The contract maps when the following back month contract has a higher open interest that the current front month (2)
836  /// </summary>
837  OpenInterest,
838  /// <summary>
839  /// The contract maps when any of the back month contracts of the next year have a higher volume that the current front month (3)
840  /// </summary>
842  }
843 
844  /// <summary>
845  /// The different types of <see cref="CashBook.Updated"/> events
846  /// </summary>
847  public enum CashBookUpdateType
848  {
849  /// <summary>
850  /// A new <see cref="Cash.Symbol"/> was added (0)
851  /// </summary>
852  Added,
853  /// <summary>
854  /// One or more <see cref="Cash"/> instances were removed (1)
855  /// </summary>
856  Removed,
857  /// <summary>
858  /// An existing <see cref="Cash.Symbol"/> was updated (2)
859  /// </summary>
860  Updated
861  }
862 
863  /// <summary>
864  /// Defines Lean exchanges codes and names
865  /// </summary>
866  public static class Exchanges
867  {
868  /// <summary>
869  /// Gets the exchange as single character representation.
870  /// </summary>
871  [MethodImpl(MethodImplOptions.AggressiveInlining)]
872  public static string GetPrimaryExchangeCodeGetPrimaryExchange(this string exchange,
873  SecurityType securityType = SecurityType.Equity,
874  string market = Market.USA)
875  {
876  return exchange.GetPrimaryExchange(securityType, market).Code;
877  }
878 
879  /// <summary>
880  /// Gets the exchange as PrimaryExchange object.
881  /// </summary>
882  /// <remarks>Useful for performance</remarks>
883  [MethodImpl(MethodImplOptions.AggressiveInlining)]
884  public static Exchange GetPrimaryExchange(this string exchange,
885  SecurityType securityType = SecurityType.Equity,
886  string market = Market.USA)
887  {
888  var primaryExchange = Exchange.UNKNOWN;
889  if (string.IsNullOrEmpty(exchange))
890  {
891  return primaryExchange;
892  }
893 
894  if (securityType == SecurityType.Equity)
895  {
896  switch (exchange.LazyToUpper())
897  {
898  case "T":
899  case "Q":
900  case "NASDAQ":
901  case "NASDAQ_OMX":
902  return Exchange.NASDAQ;
903  case "Z":
904  case "BATS":
905  case "BATS Z":
906  case "BATS_Z":
907  return Exchange.BATS;
908  case "P":
909  case "ARCA":
910  return Exchange.ARCA;
911  case "N":
912  case "NYSE":
913  return Exchange.NYSE;
914  case "C":
915  case "NSX":
916  case "NSE":
917  if (market == Market.USA)
918  {
919  return Exchange.NSX;
920  }
921  else if (market == Market.India)
922  {
923  return Exchange.NSE;
924  }
925  return Exchange.UNKNOWN;
926  case "D":
927  case "FINRA":
928  return Exchange.FINRA;
929  case "I":
930  case "ISE":
931  return Exchange.ISE;
932  case "M":
933  case "CSE":
934  return Exchange.CSE;
935  case "W":
936  case "CBOE":
937  return Exchange.CBOE;
938  case "A":
939  case "AMEX":
940  return Exchange.AMEX;
941  case "SIAC":
942  return Exchange.SIAC;
943  case "J":
944  case "EDGA":
945  return Exchange.EDGA;
946  case "K":
947  case "EDGX":
948  return Exchange.EDGX;
949  case "B":
950  case "NASDAQ BX":
951  case "NASDAQ_BX":
952  return Exchange.NASDAQ_BX;
953  case "X":
954  case "NASDAQ PSX":
955  case "NASDAQ_PSX":
956  return Exchange.NASDAQ_PSX;
957  case "Y":
958  case "BATS Y":
959  case "BATS_Y":
960  case "BYX":
961  return Exchange.BATS_Y;
962  case "BB":
963  case "BOSTON":
964  return Exchange.BOSTON;
965  case "BSE":
966  return Exchange.BSE;
967  case "IEX":
968  return Exchange.IEX;
969  case "SMART":
970  return Exchange.SMART;
971  case "OTCX":
972  return Exchange.OTCX;
973  case "MP":
974  case "MIAX PEARL":
975  case "MIAX_PEARL":
976  return Exchange.MIAX_PEARL;
977  case "L":
978  case "LTSE":
979  return Exchange.LTSE;
980  case "MM":
981  case "MEMX":
982  return Exchange.MEMX;
983  case "CSFB":
984  return Exchange.CSFB;
985  }
986  }
987  else if (securityType == SecurityType.Option)
988  {
989  switch (exchange.LazyToUpper())
990  {
991  case "A":
992  case "AMEX":
993  return Exchange.AMEX_Options;
994  case "M":
995  case "MIAX":
996  return Exchange.MIAX;
997  case "ME":
998  case "MIAX EMERALD":
999  case "MIAX_EMERALD":
1000  return Exchange.MIAX_EMERALD;
1001  case "MP":
1002  case "MIAX PEARL":
1003  case "MIAX_PEARL":
1004  return Exchange.MIAX_PEARL;
1005  case "I":
1006  case "ISE":
1007  return Exchange.ISE;
1008  case "H":
1009  case "ISE GEMINI":
1010  case "ISE_GEMINI":
1011  return Exchange.ISE_GEMINI;
1012  case "J":
1013  case "ISE MERCURY":
1014  case "ISE_MERCURY":
1015  return Exchange.ISE_MERCURY;
1016  case "O":
1017  case "OPRA":
1018  return Exchange.OPRA;
1019  case "W":
1020  case "C2":
1021  return Exchange.C2;
1022  case "XNDQ":
1023  return Exchange.NASDAQ_Options;
1024  case "ARCX":
1025  return Exchange.ARCA_Options;
1026  case "EDGO":
1027  return Exchange.EDGO;
1028  case "BOX":
1029  case "B":
1030  return Exchange.BOX;
1031  case "PHLX":
1032  return Exchange.PHLX;
1033  case "SPHR":
1034  case "MIAX SAPPHIRE":
1035  case "MIAX_SAPPHIRE":
1036  return Exchange.MIAX_SAPPHIRE;
1037  default:
1038  return Exchange.UNKNOWN;
1039  }
1040  }
1041  else if (securityType == SecurityType.Future || securityType == SecurityType.FutureOption)
1042  {
1043  switch (exchange.LazyToUpper())
1044  {
1045  case "CME":
1046  return Exchange.CME;
1047  case "CBOT":
1048  return Exchange.CBOT;
1049  case "NYMEX":
1050  return Exchange.NYMEX;
1051  case "ICE":
1052  return Exchange.ICE;
1053  case "CFE":
1054  return Exchange.CFE;
1055  case "COMEX":
1056  return Exchange.COMEX;
1057  case "NYSELIFFE":
1058  return Exchange.NYSELIFFE;
1059  case "EUREX":
1060  return Exchange.EUREX;
1061  default:
1062  return Exchange.UNKNOWN;
1063  }
1064  }
1065  return Exchange.UNKNOWN;
1066  }
1067  }
1068 
1069  /// <summary>
1070  /// Defines the different channel status values
1071  /// </summary>
1072  public static class ChannelStatus
1073  {
1074  /// <summary>
1075  /// The channel is empty
1076  /// </summary>
1077  public const string Vacated = "channel_vacated";
1078 
1079  /// <summary>
1080  /// The channel has subscribers
1081  /// </summary>
1082  public const string Occupied = "channel_occupied";
1083  }
1084 
1085  /// <summary>
1086  /// Represents the types deployment targets for algorithms
1087  /// </summary>
1088  [JsonConverter(typeof(StringEnumConverter))]
1089  public enum DeploymentTarget
1090  {
1091  /// <summary>
1092  /// Cloud Platform (0)
1093  /// </summary>
1094  CloudPlatform,
1095 
1096  /// <summary>
1097  /// Local Platform (1)
1098  /// </summary>
1099  LocalPlatform,
1100 
1101  /// <summary>
1102  /// Private Cloud Platform (2)
1103  /// </summary>
1105  }
1106 
1107  /// <summary>
1108  /// Represents the deployment modes of an algorithm
1109  /// </summary>
1110  [JsonConverter(typeof(StringEnumConverter))]
1111  public enum AlgorithmMode
1112  {
1113  /// <summary>
1114  /// Live (0)
1115  /// </summary>
1116  Live,
1117 
1118  /// <summary>
1119  /// Optimization (1)
1120  /// </summary>
1121  Optimization,
1122 
1123  /// <summary>
1124  /// Backtesting (2)
1125  /// </summary>
1126  Backtesting,
1127 
1128  /// <summary>
1129  /// Research (3)
1130  /// </summary>
1131  Research
1132  }
1133 }