public override void Initialize()
        {
            SetStartDate(2020, 1, 5);
            SetEndDate(2020, 6, 30);

            // We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
            // which causes delisting events to never be processed, thus leading to options that might never
            // be exercised until the next data point arrives.
            AddEquity("AAPL", Resolution.Daily);

            _es19m20 = AddFutureContract(
                QuantConnect.Symbol.CreateFuture(
                    Futures.Indices.SP500EMini,
                    Market.CME,
                    new DateTime(2020, 6, 19)),
                Resolution.Minute).Symbol;

            // Select a future option expiring ITM, and adds it to the algorithm.
            _esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time)
                                                .Where(x => x.ID.StrikePrice >= 3400m && x.ID.OptionRight == OptionRight.Call)
                                                .OrderBy(x => x.ID.StrikePrice)
                                                .Take(1)
                                                .Single(), Resolution.Minute).Symbol;

            _expectedContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Call, 3400m, new DateTime(2020, 6, 19));
            if (_esOption != _expectedContract)
            {
                throw new Exception($"Contract {_expectedContract} was not found in the chain");
            }

            Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () =>
            {
                MarketOrder(_esOption, -1);
            });
        }
        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        public override void Initialize()
        {
            SetStartDate(2013, 10, 07);  //Set Start Date
            SetEndDate(2013, 10, 11);    //Set End Date
            SetCash(100000);             //Set Strategy Cash


            SetSecurityInitializer(x => x.SetDataNormalizationMode(DataNormalizationMode.Raw));

            _symbol = AddEquity("IBM", Resolution.Minute).Symbol;
            AddEquity("AAPL", Resolution.Daily);

            // 2013-10-07 was Monday, that's why we ask 3 days history to get  data from previous Friday.
            var history = History(new[] { _symbol }, TimeSpan.FromDays(3), Resolution.Minute).ToList();

            Log($"{Time} - history.Count: {history.Count}");

            const int expectedSliceCount = 390;

            if (history.Count != expectedSliceCount)
            {
                throw new Exception($"History slices - expected: {expectedSliceCount}, actual: {history.Count}");
            }


            if (history.Any(s => s.Bars.Count != 1 && s.QuoteBars.Count != 1))
            {
                throw new Exception($"History not all slices have trades and quotes.");
            }

            Schedule.On(DateRules.EveryDay(_symbol), TimeRules.AfterMarketOpen(_symbol, 0), () => { _canTrade = true; });

            Schedule.On(DateRules.EveryDay(_symbol), TimeRules.BeforeMarketClose(_symbol, 16), () => { _canTrade = false; });
        }
Beispiel #3
0
        public override void Initialize()
        {
            SetStartDate(2007, 6, 1);
            SetEndDate(DateTime.Now.Date.AddDays(-1));
            SetCash(10000);

            AddSecurity(SecurityType.Equity, spy, Resolution.Minute);

            foreach (var security in securities)
            {
                AddSecurity(SecurityType.Equity, security, Resolution.Minute);
                Securities[security].SetLeverage(8m);
            }

            Schedule.On(DateRules.Every(DayOfWeek.Tuesday), TimeRules.At(11, 0), () =>
            {
                foreach (var security in hedges.Where(s => Securities[s].Price > 0m))
                {
                    SetHoldings(security, _leverage * 1.06m / (hedges.Where(s => Securities[s].Price > 0m).Count()));
                }

                foreach (var security in riskyAssets.Where(s => Securities[s].Price > 0m))
                {
                    SetHoldings(security, _leverage * 0.27m / (riskyAssets.Where(s => Securities[s].Price > 0m).Count()));
                }
            });
        }
Beispiel #4
0
        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        public override void Initialize()
        {
            SetStartDate(2013, 10, 07);
            SetEndDate(2013, 10, 11);

            var security = AddEquity("SPY", Resolution.Minute);

            _spy = security.Symbol;

            _closedMarketLeverage     = 2;
            _openMarketLeverage       = 5;
            security.BuyingPowerModel = new PatternDayTradingMarginModel(_closedMarketLeverage, _openMarketLeverage);

            Schedule.On(
                DateRules.EveryDay(_spy),
                // 15 minutes before market close, because PatternDayTradingMarginModel starts using closed
                // market leverage 10 minutes before market closes.
                TimeRules.BeforeMarketClose(_spy, 15),
                () => {
                // before market close we reduce our position to closed market leverage
                SetHoldings(_spy, _closedMarketLeverage);
            }
                );

            Schedule.On(
                DateRules.EveryDay(_spy),
                TimeRules.AfterMarketOpen(_spy, 1), // 1 min so that price is set
                () => {
                // at market open we increase our position to open market leverage
                SetHoldings(_spy, _openMarketLeverage);
            }
                );
        }
Beispiel #5
0
        public override void Initialize()
        {
            AddEquity(SYM, Resolution.Minute);

            AddEquity("TLT", Resolution.Minute);
            AddEquity("IEF", Resolution.Minute);
            AddEquity("DBC", Resolution.Minute);
            //AddEquity("VEA", Resolution.Minute);
            AddEquity("GLD", Resolution.Minute);

            //var week5Consolidator = new TradeBarConsolidator(TimeSpan.FromDays(22));
            RegisterIndicator(SYM, ma, TimeSpan.FromDays(22));
            //week5Consolidator.DataConsolidated += (sender, consolidated) => OnWeek5(sender, (TradeBar) consolidated);

            // this call adds our 3 day to the manager to receive updates from the engine
            //SubscriptionManager.AddConsolidator(SYM, week5Consolidator);

            // There are other assets with similar methods. See "Selecting Options" etc for more details.
            // AddFuture, AddForex, AddCfd, AddOption
            Schedule.On(DateRules.EveryDay(SYM), TimeRules.AfterMarketOpen(SYM, 5), () =>
            {
                //Log("EveryDay.SPY 10 min after open: Fired at: " + Time);
                if (fullOn)
                {
                    if (Securities[SYM].Price < ma && prevRebalCondition)
                    {
                        var ratio = 1;
                        SetAllWeatherHoldings(ratio);
                        fullOn = false;
                    }
                    prevRebalCondition = Securities[SYM].Price > ma;
                }
            });
        }
Beispiel #6
0
        public override void Initialize()
        {
            SetStartDate(2016, 01, 01);  //Set Start Date
            SetEndDate(2016, 10, 14);    //Set End Date
            SetCash(10000);              //Set Strategy Cash

            // Find more symbols here: http://quantconnect.com/data
            // Forex, CFD, Equities Resolutions: Tick, Second, Minute, Hour, Daily.
            // Futures Resolution: Tick, Second, Minute
            // Options Resolution: Minute Only.
            // Add each equity so we receive data
            AddEquity(_spy, Resolution.Daily);
            AddEquity(_qqq, Resolution.Daily);
            AddEquity(_tlt, Resolution.Daily);
            AddEquity(_agg, Resolution.Daily);

            //Build window
            _close_window = new RollingWindow <decimal>(84);
            IEnumerable <TradeBar> slices = History(_benchmark, 84);

            foreach (TradeBar bar in slices)
            {
                _close_window.Add(bar.Close);
            }

            // Schedule EveryDayOnMarketOpen function to be called
            // each day 10 minutes after market open
            Schedule.On(DateRules.EveryDay(_benchmark),
                        TimeRules.AfterMarketOpen(_benchmark, 10),
                        EveryDayOnMarketOpen);
        }
Beispiel #7
0
        public override void Initialize()
        {
            SetStartDate(2001, 1, 1);
            SetEndDate(DateTime.Now);
            SetCash(10000);

            mean  = SMA(symbol, n, Resolution.Daily);
            sigma = STD(symbol, n, Resolution.Daily);

            var history = History(symbol, TimeSpan.FromDays(150), Resolution.Daily);

            foreach (var tb in history)
            {
                mean.Update(tb.EndTime, tb.Close);
                sigma.Update(tb.EndTime, tb.Close);
            }

            Schedule.On(DateRules.EveryDay(), TimeRules.At(11, 0), () =>
            {
                var z      = (Securities[symbol].Price - mean) / sigma;
                var target = 2.0 / (1 + Math.Exp((double)(-1.2m * z)));

                if (z >= -4 && z <= 4)
                {
                    SetHoldings(symbol, target);
                    SetHoldings("TLT", 2 - target);
                }
                else
                {
                    SetHoldings(symbol, 0);
                    SetHoldings("TLT", 1);
                }
            });
        }
Beispiel #8
0
        public override void Initialize()
        {
            SetStartDate(2020, 1, 5);
            SetEndDate(2020, 6, 30);

            _es19m20 = AddFutureContract(
                QuantConnect.Symbol.CreateFuture(
                    Futures.Indices.SP500EMini,
                    Market.CME,
                    new DateTime(2020, 6, 19)),
                Resolution.Minute).Symbol;

            // Select a future option expiring ITM, and adds it to the algorithm.
            _esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time)
                                                .Where(x => x.ID.StrikePrice <= 3200m && x.ID.OptionRight == OptionRight.Call)
                                                .OrderByDescending(x => x.ID.StrikePrice)
                                                .Take(1)
                                                .Single(), Resolution.Minute).Symbol;

            _expectedOptionContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Call, 3200m, new DateTime(2020, 6, 19));
            if (_esOption != _expectedOptionContract)
            {
                throw new Exception($"Contract {_expectedOptionContract} was not found in the chain");
            }

            Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () =>
            {
                MarketOrder(_esOption, 1);
            });
        }
Beispiel #9
0
        public async Task <IActionResult> PutTimeRules([FromRoute] int id, [FromBody] TimeRules timeRules)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != timeRules.TimeRuleId)
            {
                return(BadRequest());
            }

            _context.Entry(timeRules).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TimeRulesExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        public override void Initialize()
        {
            SetStartDate(2021, 1, 4);
            SetEndDate(2021, 1, 31);

            _spx = AddIndex("SPX", Resolution.Minute).Symbol;

            // Select a index option expiring ITM, and adds it to the algorithm.
            _spxOption = AddIndexOptionContract(OptionChainProvider.GetOptionContractList(_spx, Time)
                                                .Where(x => x.ID.StrikePrice <= 3200m && x.ID.OptionRight == OptionRight.Put && x.ID.Date.Year == 2021 && x.ID.Date.Month == 1)
                                                .OrderByDescending(x => x.ID.StrikePrice)
                                                .Take(1)
                                                .Single(), Resolution.Minute).Symbol;

            _expectedContract = QuantConnect.Symbol.CreateOption(_spx, Market.USA, OptionStyle.European, OptionRight.Put, 3200m, new DateTime(2021, 1, 15));
            if (_spxOption != _expectedContract)
            {
                throw new Exception($"Contract {_expectedContract} was not found in the chain");
            }

            Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_spx, 1), () =>
            {
                MarketOrder(_spxOption, 1);
            });
        }
Beispiel #11
0
        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        public override void Initialize()
        {
            SetStartDate(2013, 10, 07);
            SetEndDate(2013, 10, 11);

            _spy = AddEquity("SPY").Symbol;

            var test     = 0;
            var dateRule = DateRules.EveryDay(_spy);

            var aEventCount = 0;
            var bEventCount = 0;
            var cEventCount = 0;

            // we add each twice and assert the order in which they are added is also respected for events at the same time
            for (var i = 0; i < 2; i++)
            {
                var id = i;
                Schedule.On(dateRule, TimeRules.At(9, 25), (name, time) =>
                {
                    // for id 0 event count should always be 0, for id 1 should be 1
                    if (aEventCount != id)
                    {
                        throw new Exception($"Scheduled event triggered out of order: {Time} expected id {id} but was {aEventCount}");
                    }
                    aEventCount++;
                    // goes from 0 to 1
                    aEventCount %= 2;
                    AssertScheduledEventTime();
                    Debug($"{Time} :: Test: {test}"); test++;
                });
                Schedule.On(dateRule, TimeRules.BeforeMarketClose(_spy, 5), (name, time) =>
                {
                    // for id 0 event count should always be 0, for id 1 should be 1
                    if (bEventCount != id)
                    {
                        throw new Exception($"Scheduled event triggered out of order: {Time} expected id {id} but was {bEventCount}");
                    }
                    bEventCount++;
                    // goes from 0 to 1
                    bEventCount %= 2;
                    AssertScheduledEventTime();
                    Debug($"{Time} :: Test: {test}"); test++;
                });
                Schedule.On(dateRule, TimeRules.At(16, 5), (name, time) =>
                {
                    // for id 0 event count should always be 0, for id 1 should be 1
                    if (cEventCount != id)
                    {
                        throw new Exception($"Scheduled event triggered out of order: {Time} expected id {id} but was {cEventCount}");
                    }
                    cEventCount++;
                    // goes from 0 to 1
                    cEventCount %= 2;
                    AssertScheduledEventTime();
                    Debug($"{Time} :: Test: {test}"); test = 0;
                });
            }
        }
Beispiel #12
0
        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        public override void Initialize()
        {
            SetStartDate(2013, 10, 07);  //Set Start Date
            SetEndDate(2013, 10, 11);    //Set End Date
            SetCash(100000);             //Set Strategy Cash
            // Find more symbols here: http://quantconnect.com/data
            AddSecurity(SecurityType.Equity, "SPY", Resolution.Minute);

            // events are scheduled using date and time rules
            // date rules specify on what dates and event will fire
            // time rules specify at what time on thos dates the event will fire

            // schedule an event to fire at a specific date/time
            Schedule.On(DateRules.On(2013, 10, 7), TimeRules.At(13, 0), () =>
            {
                Log("SpecificTime: Fired at : " + Time);
            });

            // schedule an event to fire every trading day for a security
            // the time rule here tells it to fire 10 minutes after SPY's market open
            Schedule.On(DateRules.EveryDay("SPY"), TimeRules.AfterMarketOpen("SPY", 10), () =>
            {
                Log("EveryDay.SPY 10 min after open: Fired at: " + Time);
            });

            // schedule an event to fire every trading day for a security
            // the time rule here tells it to fire 10 minutes before SPY's market close
            Schedule.On(DateRules.EveryDay("SPY"), TimeRules.BeforeMarketClose("SPY", 10), () =>
            {
                Log("EveryDay.SPY 10 min before close: Fired at: " + Time);
            });

            // schedule an event to fire on certain days of the week
            Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Friday), TimeRules.At(12, 0), () =>
            {
                Log("Mon/Fri at 12pm: Fired at: " + Time);
            });


            // the scheduling methods return the ScheduledEvent object which can be used for other things
            // here I set the event up to check the portfolio value every 10 minutes, and liquidate if we have too many losses
            Schedule.On(DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromMinutes(10)), () =>
            {
                // if we have over 1000 dollars in unrealized losses, liquidate
                if (Portfolio.TotalUnrealizedProfit < -1000)
                {
                    Log("Liquidated due to unrealized losses at: " + Time);
                    Liquidate();
                }
            });

            // schedule an event to fire at the beginning of the month, the symbol is optional if
            // specified, it will fire the first trading day for that symbol of the month, if not specified
            // it will fire on the first day of the month
            Schedule.On(DateRules.MonthStart("SPY"), TimeRules.AfterMarketOpen("SPY"), () =>
            {
                // good spot for rebalancing code?
            });
        }
Beispiel #13
0
        public override void Initialize()
        {
            SetStartDate(2014, 6, 5);
            SetEndDate(2014, 6, 9);

            _twx = AddEquity("TWX", Resolution.Minute, extendedMarketHours: true).Symbol;
            Schedule.On(DateRules.EveryDay(_twx), TimeRules.Every(TimeSpan.FromHours(1)), PlotPrice);
        }
 public static string TimeRulesToString(TimeRules timeRules)
 {
     if (timeRules == null)
     {
         return("<null>");
     }
     return($"{timeRules.PlayerTime.Minutes}min + {timeRules.SecondsPerMove}s");
 }
        public override void Initialize()
        {
            SetStartDate(2013, 10, 07);  //Set Start Date
            SetEndDate(2013, 10, 11);    //Set End Date
            SetCash(2500000);
            SetCash("TRY", 111000, 1);   //Set Strategy Cash
            security = AddSecurity(SecurityType.Equity, BIST_SECURITY_NAME, Resolution.Second);


            Schedule.On(DateRules.On(2016, 05, 11), TimeRules.At(11, 38), () =>
            {
                Log("SpecificTime: Fired at : " + Time);
            });

            // schedule an event to fire every trading day for a security
            // the time rule here tells it to fire 10 minutes after SPY's market open
            Schedule.On(DateRules.EveryDay(BIST_SECURITY_NAME), TimeRules.AfterMarketOpen(BIST_SECURITY_NAME, 10), () =>
            {
                Log("EveryDay.GARAN 10 min after open: Fired at: " + Time);
            });

            // schedule an event to fire every trading day for a security
            // the time rule here tells it to fire 10 minutes before SPY's market close
            Schedule.On(DateRules.EveryDay(BIST_SECURITY_NAME), TimeRules.BeforeMarketClose(BIST_SECURITY_NAME, 10), () =>
            {
                Log("EveryDay.GARAN 10 min before close: Fired at: " + Time);
            });

            // schedule an event to fire on certain days of the week
            Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Friday), TimeRules.At(12, 0), () =>
            {
                Log("Mon/Fri at 12pm: Fired at: " + Time);
            });


            // the scheduling methods return the ScheduledEvent object which can be used for other things
            // here I set the event up to check the portfolio value every 10 minutes, and liquidate if we have too many losses
            Schedule.On(DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromMinutes(10)), () =>
            {
                Log("EveryDay 10 min Fired at: " + Time);
                // if we have over 1000 dollars in unrealized losses, liquidate
                if (Portfolio.TotalUnrealizedProfit < -1000)
                {
                    Log("Liquidated due to unrealized losses at: " + Time);
                    Liquidate();
                }
            });

            //SetBrokerageModel(BrokerageName.TEB);

            //QuantConnect.Securities.Security sec = AddSecurity(SecurityType.Equity, SECURITY_NAME, Resolution.Second);

            //security.DataFilter = new CustomDataFilter(); //Securities[securityName].DataFilter = new CustomDataFilter();
            //sec.FeeModel = new QuantConnect.Orders.Fees.TEBFeeModel(0);
            //sec.FillModel = new QuantConnect.Orders.Fills.TEBFillModel();
            //sec.MarginModel = new QuantConnect.Securities.TEBSecurityMarginModel(1m);
            //sec.SlippageModel = new QuantConnect.Orders.Slippage.TEBSlippageModel(0m);
        }
Beispiel #16
0
        public override void Initialize()
        {
            // backtest parameters
            // we have data for these dates locally
            var start = new DateTime(2020, 01, 01, 09, 30, 0);

            SetStartDate(start);
            SetEndDate(start.AddDays(30));
            SetCash(100000);

            // set security and option universe for tradebar
            _spy = AddEquity("SPY", Resolution.Minute);
            var option = AddOption("SPY", Resolution.Minute);

            // set filter on option universe
            _optionSymbol = option.Symbol;
            option.SetFilter(universe =>
                             from symbol in universe
                             .WeeklysOnly().Expiration(TimeSpan.Zero, TimeSpan.FromDays(10))
                             where symbol.ID.OptionRight != OptionRight.Put
                             select symbol);

            // use the underlying equity as the benchmark
            SetBenchmark("SPY");

            // Creates a Rolling Window indicator to hold 2 TradeBars
            _window = new RollingWindow <TradeBar>(2);

            // Creates a Rolling Window indicator to hold 1 option contract
            _optionWindow = new RollingWindow <OptionContract>(1);

            // create RSI indicator
            fast = new RelativeStrengthIndex("SPY", 14, MovingAverageType.Wilders);

            // Create a Rolling Window to keep two Indicator Data Points
            _rsiLag = new RollingWindow <IndicatorDataPoint>(2);

            // define our 5 minute trade bar consolidator. we can access the 5 minute bar
            // from the DataConsolidated events
            var minConsolidator = new TradeBarConsolidator(TimeSpan.FromMinutes(5));

            // attach our event handler. the event handler is a function that will be called each time we produce
            // a new consolidated piece of data.
            minConsolidator.DataConsolidated += OnFiveMinutes;

            // this call adds our daily consolidator to the manager to receive updates from the engine
            SubscriptionManager.AddConsolidator("SPY", minConsolidator);

            // we need to manually register these indicators for automatic updates
            RegisterIndicator("SPY", fast, minConsolidator);

            Schedule.On(DateRules.EveryDay(), TimeRules.BeforeMarketClose(_spy.Symbol, 4), () =>
            {
                CloseOpenPositions(_spy);
            });

            SetWarmUp(TimeSpan.FromDays(100));
        }
Beispiel #17
0
        /// <summary>
        /// Move the config rules into lists for warp, time and keypress
        /// and register events as needed
        ///
        /// Use with caution, locks on this
        /// </summary>
        private void CheckRulesAndUpdateEventReg()
        {
            lock (this)
            {
                WarpRules.Clear();
                TimeRules.Clear();
                KeyRules.Clear();
                foreach (ModRule rule in m_config.SnapshotRules)
                {
                    if (rule.Trigger.IsWaitingOnWarp())
                    {
                        WarpRules.Add(rule);
                    }
                    else if (rule.Trigger.IsWaitingOnTime())
                    {
                        TimeRules.Add(rule);
                    }
                    else if (rule.Trigger.IsWaitingOnKeypress())
                    {
                        KeyRules.Add(rule);
                    }
                }
                EventAction warpAction = ShouldAlterEventReg(WarpEventRegistered, WarpRules.Count);
                EventAction timeAction = ShouldAlterEventReg(TimeEventRegistered, TimeRules.Count);
                EventAction keyAction  = ShouldAlterEventReg(KeyEventRegistered, KeyRules.Count);
                MTrace($"Warp = {WarpRules.Count} {warpAction}, Time = {TimeRules.Count} {timeAction}, Key = {KeyRules.Count} {keyAction}");
                // Events cannot be passed, so this code must be duplicated
                if (EventAction.Add == warpAction)
                {
                    Helper.Events.Player.Warped += OnWarped;
                }
                else if (EventAction.Remove == warpAction)
                {
                    Helper.Events.Player.Warped -= OnWarped;
                }
                WarpEventRegistered = 0 < WarpRules.Count;

                if (EventAction.Add == timeAction)
                {
                    Helper.Events.GameLoop.TimeChanged += OnTimeChanged;
                }
                else if (EventAction.Remove == timeAction)
                {
                    Helper.Events.GameLoop.TimeChanged -= OnTimeChanged;
                }
                TimeEventRegistered = 0 < TimeRules.Count;

                if (EventAction.Add == keyAction)
                {
                    Helper.Events.Input.ButtonPressed += OnButtonPressed;
                }
                else if (EventAction.Remove == keyAction)
                {
                    Helper.Events.Input.ButtonPressed -= OnButtonPressed;
                }
                KeyEventRegistered = 0 < KeyRules.Count;
            }
        }
        public override void Initialize()
        {
            SetStartDate(2020, 1, 5);
            SetEndDate(2020, 6, 30);

            // We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
            // which causes delisting events to never be processed, thus leading to options that might never
            // be exercised until the next data point arrives.
            AddEquity("AAPL", Resolution.Daily);

            var es20h20 = AddFutureContract(
                QuantConnect.Symbol.CreateFuture(
                    Futures.Indices.SP500EMini,
                    Market.CME,
                    new DateTime(2020, 3, 20)),
                Resolution.Minute).Symbol;

            var es20m20 = AddFutureContract(
                QuantConnect.Symbol.CreateFuture(
                    Futures.Indices.SP500EMini,
                    Market.CME,
                    new DateTime(2020, 6, 19)),
                Resolution.Minute).Symbol;

            // Select a future option expiring ITM, and adds it to the algorithm.
            var esOptions = OptionChainProvider.GetOptionContractList(es20m20, Time)
                            .Concat(OptionChainProvider.GetOptionContractList(es20h20, Time))
                            .Where(x => x.ID.StrikePrice == 3200m && x.ID.OptionRight == OptionRight.Call)
                            .Select(x => AddFutureOptionContract(x, Resolution.Minute).Symbol)
                            .ToList();

            var expectedContracts = new[]
            {
                QuantConnect.Symbol.CreateOption(es20h20, Market.CME, OptionStyle.American, OptionRight.Call, 3200m,
                                                 new DateTime(2020, 3, 20)),
                QuantConnect.Symbol.CreateOption(es20m20, Market.CME, OptionStyle.American, OptionRight.Call, 3200m,
                                                 new DateTime(2020, 6, 19))
            };

            foreach (var esOption in esOptions)
            {
                if (!expectedContracts.Contains(esOption))
                {
                    throw new Exception($"Contract {esOption} was not found in the chain");
                }
            }

            Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(es20m20, 1), () =>
            {
                MarketOrder(esOptions[0], 1);
                MarketOrder(esOptions[1], -1);
            });
            Schedule.On(DateRules.Tomorrow, TimeRules.Noon, () =>
            {
                Liquidate();
            });
        }
Beispiel #19
0
        public void Setup()
        {
            _timezone   = TimeZones.NewYork;
            _timekeeper = new TimeKeeper(new DateTime(2000, 1, 1), _timezone);
            _securities = new SecurityManager(_timekeeper);

            _dateRules = new DateRules(_securities, _timezone);
            _timeRules = new TimeRules(_securities, _timezone);
        }
        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        public override void Initialize()
        {
            SetStartDate(2013, 10, 07);
            SetEndDate(2013, 10, 09);
            SetCash(100000);

            AddEquity("SPY", Resolution.Minute, extendedMarketHours: true, fillDataForward: false);

            Schedule.On("RunHistoryCall", DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromHours(1)), RunHistoryCall);
        }
Beispiel #21
0
        public override void Initialize()
        {
            UniverseSettings.Resolution = globalResolution;
            SetStartDate(1998, 1, 1);  //Set Start Date
            SetEndDate(2018, 9, 1);    //Set End Date
            SetCash(1000000);          //Set Strategy Cash
            var spy = AddEquity("SPY", Resolution.Daily);

            Schedule.On(DateRules.MonthStart("SPY"), TimeRules.At(0, 0), Rebalance);
            Rebalance();
        }
        public override void Initialize()
        {
            SetStartDate(2018, 3, 26);
            SetEndDate(2018, 4, 10);
            foreach (var symbol in _symbols)
            {
                AddSecurity(symbol, Resolution.Minute);
            }

            Schedule.On(DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromHours(1)), MakeHistoryCall);
        }
Beispiel #23
0
        public override void Initialize()
        {
            SetStartDate(2021, 1, 4);
            SetEndDate(2021, 1, 31);

            var spx = AddIndex("SPX", Resolution.Minute).Symbol;

            // Select a index option expiring ITM, and adds it to the algorithm.
            var spxOptions = OptionChainProvider.GetOptionContractList(spx, Time)
                             .Where(x => (x.ID.StrikePrice == 3700m || x.ID.StrikePrice == 3800m) && x.ID.OptionRight == OptionRight.Call && x.ID.Date.Year == 2021 && x.ID.Date.Month == 1)
                             .Select(x => AddIndexOptionContract(x, Resolution.Minute).Symbol)
                             .OrderBy(x => x.ID.StrikePrice)
                             .ToList();

            var expectedContract3700 = QuantConnect.Symbol.CreateOption(
                spx,
                Market.USA,
                OptionStyle.European,
                OptionRight.Call,
                3700m,
                new DateTime(2021, 1, 15));

            var expectedContract3800 = QuantConnect.Symbol.CreateOption(
                spx,
                Market.USA,
                OptionStyle.European,
                OptionRight.Call,
                3800m,
                new DateTime(2021, 1, 15));

            if (spxOptions.Count != 2)
            {
                throw new Exception($"Expected 2 index options symbols from chain provider, found {spxOptions.Count}");
            }

            if (spxOptions[0] != expectedContract3700)
            {
                throw new Exception($"Contract {expectedContract3700} was not found in the chain, found instead: {spxOptions[0]}");
            }
            if (spxOptions[1] != expectedContract3800)
            {
                throw new Exception($"Contract {expectedContract3800} was not found in the chain, found instead: {spxOptions[1]}");
            }

            Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(spx, 1), () =>
            {
                MarketOrder(spxOptions[0], 1);
                MarketOrder(spxOptions[1], -1);
            });
            Schedule.On(DateRules.Tomorrow, TimeRules.Noon, () =>
            {
                Liquidate();
            });
        }
Beispiel #24
0
 public override void Initialize()
 {
     SetStartDate(2011, 1, 1);
     SetEndDate(2018, 1, 1);
     SetCash(100000);
     AddEquity("SPY");
     foreach (int period in Enumerable.Range(0, 300))
     {
         Schedule.On(DateRules.EveryDay("SPY"), TimeRules.AfterMarketOpen("SPY", period), Rebalance);
         Schedule.On(DateRules.EveryDay("SPY"), TimeRules.BeforeMarketClose("SPY", period), Rebalance);
     }
 }
Beispiel #25
0
        public async Task <IActionResult> PostTimeRules([FromBody] TimeRules timeRules)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.TimeRules.Add(timeRules);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetTimeRules", new { id = timeRules.TimeRuleId }, timeRules));
        }
Beispiel #26
0
        private static TimeRules GetTimeRules(DateTimeZone dateTimeZone)
        {
            var timeKeeper            = new TimeKeeper(DateTime.Today, new List <DateTimeZone>());
            var manager               = new SecurityManager(timeKeeper);
            var securityExchangeHours = SecurityExchangeHoursProvider.FromDataFolder().GetExchangeHours("usa", null, SecurityType.Equity);
            var config = new SubscriptionDataConfig(typeof(TradeBar), SecurityType.Equity, "SPY", Resolution.Daily, "usa", securityExchangeHours.TimeZone, true, false, false);

            manager.Add("SPY", new Security(securityExchangeHours, config, 1, false));
            var rules = new TimeRules(manager, dateTimeZone);

            return(rules);
        }
Beispiel #27
0
        public override void Initialize()
        {
            SetStartDate(2020, 1, 5);
            SetEndDate(2020, 6, 30);

            var es20h20 = AddFutureContract(
                QuantConnect.Symbol.CreateFuture(
                    Futures.Indices.SP500EMini,
                    Market.CME,
                    new DateTime(2020, 3, 20)),
                Resolution.Minute).Symbol;

            var es20m20 = AddFutureContract(
                QuantConnect.Symbol.CreateFuture(
                    Futures.Indices.SP500EMini,
                    Market.CME,
                    new DateTime(2020, 6, 19)),
                Resolution.Minute).Symbol;

            // Select a future option expiring ITM, and adds it to the algorithm.
            var esOptions = OptionChainProvider.GetOptionContractList(es20m20, Time)
                            .Concat(OptionChainProvider.GetOptionContractList(es20h20, Time))
                            .Where(x => x.ID.StrikePrice == 3200m && x.ID.OptionRight == OptionRight.Call)
                            .Select(x => AddFutureOptionContract(x, Resolution.Minute).Symbol)
                            .ToList();

            var expectedContracts = new[]
            {
                QuantConnect.Symbol.CreateOption(es20h20, Market.CME, OptionStyle.American, OptionRight.Call, 3200m,
                                                 new DateTime(2020, 3, 20)),
                QuantConnect.Symbol.CreateOption(es20m20, Market.CME, OptionStyle.American, OptionRight.Call, 3200m,
                                                 new DateTime(2020, 6, 19))
            };

            foreach (var esOption in esOptions)
            {
                if (!expectedContracts.Contains(esOption))
                {
                    throw new Exception($"Contract {esOption} was not found in the chain");
                }
            }

            Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(es20m20, 1), () =>
            {
                MarketOrder(esOptions[0], 1);
                MarketOrder(esOptions[1], -1);
            });
            Schedule.On(DateRules.Tomorrow, TimeRules.Noon, () =>
            {
                Liquidate();
            });
        }
        public override void Initialize()
        {
            SetStartDate(2013, 10, 7);
            SetEndDate(2013, 10, 14);

            AddEquity("SPY", Resolution.Daily);

            // Set TrainingMethod to be executed immediately
            Train(TrainingMethod);

            // Set TrainingMethod to be executed at 8:00 am every Sunday
            Train(DateRules.Every(DayOfWeek.Sunday), TimeRules.At(8, 0), TrainingMethod);
        }
 public override void Initialize()
 {
     SetStartDate(2011, 1, 1);
     SetEndDate(2018, 1, 1);
     SetCash(100000);
     AddSecurity(SecurityType.Equity, "SPY", Resolution.Minute);
     foreach (int period in Enumerable.Range(0, 100))
     {
         Schedule.On(DateRules.EveryDay("SPY"), TimeRules.AfterMarketOpen("SPY", period), Rebalance);
         Schedule.On(DateRules.EveryDay("SPY"), TimeRules.BeforeMarketClose("SPY", period), Rebalance);
     }
     Schedule.On(DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromSeconds(5)), Rebalance);
 }
Beispiel #30
0
        private static TimeRules GetTimeRules(DateTimeZone dateTimeZone)
        {
            var timeKeeper            = new TimeKeeper(DateTime.Today, new List <DateTimeZone>());
            var manager               = new SecurityManager(timeKeeper);
            var marketHourDbEntry     = MarketHoursDatabase.FromDataFolder().GetEntry(Market.USA, null, SecurityType.Equity);
            var securityExchangeHours = marketHourDbEntry.ExchangeHours;
            var config = new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Daily, marketHourDbEntry.DataTimeZone, securityExchangeHours.TimeZone, true, false, false);

            manager.Add(Symbols.SPY, new Security(securityExchangeHours, config));
            var rules = new TimeRules(manager, dateTimeZone);

            return(rules);
        }