Ejemplo n.º 1
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);
            }
                );
        }
        /// <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; });
        }
Ejemplo n.º 3
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;
                });
            }
        }
Ejemplo n.º 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);  //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?
            });
        }
Ejemplo n.º 5
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));
        }
Ejemplo n.º 6
0
        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);
        }
Ejemplo n.º 7
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);
     }
 }
Ejemplo n.º 8
0
 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);
 }
        public override void Initialize()
        {
            SetStartDate(2022, 02, 01);
            SetEndDate(2022, 02, 08);
            var esFuture = AddFuture("ES").Symbol;

            Schedule.On(DateRules.EveryDay(esFuture),
                        TimeRules.AfterMarketOpen(esFuture),
                        EveryDayAfterMarketOpen);

            Schedule.On(DateRules.EveryDay(esFuture),
                        TimeRules.BeforeMarketClose(esFuture),
                        EveryDayBeforeMarketClose);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Initialize your algorithm and add desired assets.
        /// </summary>
        public override void Initialize()
        {
            //SetStartDate(2013, 11, 1);
            //SetEndDate(2018, 9, 30);

            SetStartDate(2015, 5, 1);
            SetEndDate(2015, 7, 30);
            SetCash(1000000000);

            foreach (string symbol in S_AND_P_500_SYMOLS)
            {
                var option = AddOption(symbol, Resolution.Daily, null, false);
                option.PriceModel = OptionPriceModels.BlackScholes();

                // set our strike/expiry filter for this option chain
                //option.SetFilter((universe) => universe.WeeklysOnly().Expiration(TimeSpan.FromDays(0), TimeSpan.FromDays(7)));
                //option.SetFilter(TimeSpan.FromDays(0), TimeSpan.FromDays(7));

                if (!this.registerForEOD)
                {
                    this.registerForEOD = true;

                    // Schedule an event to fire every trading day for a security
                    // The time rule here tells it to fire 10 minutes before market close
                    Schedule.On(DateRules.EveryDay(option.Symbol), TimeRules.BeforeMarketClose(option.Symbol, 15), () =>
                    {
                        Log("EveryDay 15 min before markets close: Fired at: " + Time);
                        this.LiquidateExpiredOptions();
                    });
                }
            }

            // set the warm-up period for the pricing model
            SetWarmup(TimeSpan.FromDays(15));

            // set the benchmark to be the initial cash
            SetBenchmark((d) => 1000000000);
        }
Ejemplo n.º 11
0
        public override void Initialize()
        {
            SetStartDate(2016, 1, 1);
            SetEndDate(2017, 1, 1);
            SetCash(3000);

            SetBrokerageMessageHandler(new CustomBrokerageMessageHandler(this));

            foreach (var symbol in Symbols)
            {
                AddForex(symbol, _dataResolution, Market.Oanda, false, 1m);

                Securities[symbol].TransactionModel = new OandaTransactionModel();
                //Securities[symbol].SlippageModel = new ConstantSlippageModel(0m);
                SetBrokerageModel(BrokerageName.OandaBrokerage);

                /******** LONG TERM TREND ********/
                var dailyConsolidator = new QuoteBarConsolidator(TimeSpan.FromDays(1));
                var alma = new ExponentialMovingAverage(symbol, 10);

                RegisterIndicator(symbol, alma, dailyConsolidator);
                SubscriptionManager.AddConsolidator(symbol, dailyConsolidator);

                /******** SHORT TERM TRADING ********/
                var consolidator     = new QuoteBarConsolidator(TimeSpan.FromMinutes(15));
                var schaffTrendCycle = new SchaffTrendCycle(symbol);
                var atr = new AverageTrueRange(symbol, 10);
                var adx = new AverageDirectionalIndex(symbol, 10);

                RegisterIndicator(symbol, schaffTrendCycle, consolidator);
                RegisterIndicator(symbol, atr, consolidator);
                RegisterIndicator(symbol, adx, consolidator);

                /****** ALMA Fibonacci ******/
                var alma5   = new ArnaudLegouxMovingAverage(symbol, 5);
                var alma8   = new ArnaudLegouxMovingAverage(symbol, 8);
                var alma13  = new ArnaudLegouxMovingAverage(symbol, 13);
                var alma21  = new ArnaudLegouxMovingAverage(symbol, 21);
                var alma34  = new ArnaudLegouxMovingAverage(symbol, 34);
                var alma55  = new ArnaudLegouxMovingAverage(symbol, 55);
                var alma89  = new ArnaudLegouxMovingAverage(symbol, 89);
                var alma144 = new ArnaudLegouxMovingAverage(symbol, 144);

                RegisterIndicator(symbol, alma5, consolidator);
                RegisterIndicator(symbol, alma8, consolidator);
                RegisterIndicator(symbol, alma13, consolidator);
                RegisterIndicator(symbol, alma21, consolidator);
                RegisterIndicator(symbol, alma34, consolidator);
                RegisterIndicator(symbol, alma55, consolidator);
                RegisterIndicator(symbol, alma89, consolidator);
                RegisterIndicator(symbol, alma144, consolidator);

                SubscriptionManager.AddConsolidator(symbol, consolidator);

                var signal = new SVMBaselineSignal(
                    dailyConsolidator, alma,
                    consolidator, alma5, alma8, alma13, alma21, alma34, alma55, alma89, alma144, schaffTrendCycle, atr, adx,
                    Portfolio[symbol], Securities[symbol], this
                    );

                var std = ATR(symbol, 100, MovingAverageType.DoubleExponential, _dataResolution);

                /******** HISTORY ********/
                var history = History <QuoteBar>(symbol, TimeSpan.FromDays(100), _dataResolution);

                foreach (var bar in history)
                {
                    std.Update(bar);
                    consolidator.Update(bar);
                    dailyConsolidator.Update(bar);
                }

                if (_store)
                {
                    var header = new string[] { "Time", "ALMA_5", "ALMA_8", "ALMA_13", "ALMA_21", "ALMA_34", "ALMA_55", "ALMA_89", "ALMA_144" };
                    Storage.CreateFile($"C:\\Users\\M\\Desktop\\{symbol}_ALMA.csv", header);

                    consolidator.DataConsolidated += (sender, args) =>
                    {
                        var line = new object[] { Storage.ToUTCTimestamp(args.Time), alma5.Current.Value, alma8.Current.Value, alma13.Current.Value,
                                                  alma21.Current.Value, alma34.Current.Value, alma55.Current.Value, alma89.Current.Value, alma144.Current.Value };
                        Storage.AppendToFile($"C:\\Users\\M\\Desktop\\{symbol}_ALMA.csv", line);
                    };
                }

                Securities[symbol].VolatilityModel = new AverageTrueRangeVolatilityModel(std);
                _tradingAssets.Add(symbol,
                                   new TradingAsset(Securities[symbol],
                                                    new OneShotTrigger(signal),
                                                    new ProfitTargetSignalExit(null, _targetProfitLoss),
                                                    _maximumTradeRisk,
                                                    _maximumTradeSize,
                                                    this
                                                    ));

                //_tradingAssets[symbol].IsTradable = true;

                var h = new object[] { "Time", "Signal", "Price" };
                Storage.CreateFile($"C:\\Users\\M\\Desktop\\{symbol}_ALMA_Signal.csv", h);
            }

            Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday),
                        TimeRules.At(7, 0, TimeZones.London), () =>
            {
                var tradeableDay = TradingCalendar.GetTradingDay().BusinessDay;
                if (tradeableDay)
                {
                    foreach (var s in Symbols)
                    {
                        _tradingAssets[s].IsTradable = true;
                    }
                }
            });

            Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday),
                        TimeRules.At(20, 0, TimeZones.London), () =>
            {
                foreach (var s in Symbols)
                {
                    //_tradingAssets[s].IsTradable = false;
                }
            });

            Schedule.On(DateRules.Every(DayOfWeek.Friday),
                        TimeRules.BeforeMarketClose(Symbols.First(), 240), () =>
            {
                foreach (var s in Symbols)
                {
                    //_tradingAssets[s].IsTradable = false;
                }
            });

            Schedule.On(DateRules.Every(DayOfWeek.Friday),
                        TimeRules.BeforeMarketClose(Symbols.First(), 180), () =>
            {
                foreach (var s in Symbols)
                {
                    //_tradingAssets[s].Liquidate();
                    //_tradingAssets[s].IsTradable = false;
                }
            });

            /******** CHARTING ********/

            /*Chart price = new Chart("Daily Price");
             * price.AddSeries(new Series("Price", SeriesType.Candle, 0));
             * price.AddSeries(new Series("MA", SeriesType.Line, 0));
             * price.AddSeries(new Series("Slope", SeriesType.Line, 1));
             * price.AddSeries(new Series("STC", SeriesType.Line, 2));
             * AddChart(price);
             *
             * Chart ma = new Chart("MA");
             * ma.AddSeries(new Series("HMA", SeriesType.Line, 0));
             * ma.AddSeries(new Series("FAMA", SeriesType.Line, 1));
             * AddChart(ma);
             *
             * Chart lsma = new Chart("LSMA");
             * lsma.AddSeries(new Series("Slope", SeriesType.Line, 0));
             * AddChart(lsma);*/

            Chart plotter = new Chart("Plotter");

            plotter.AddSeries(new Series("Close", SeriesType.Line, 0));
            plotter.AddSeries(new Series("EMA", SeriesType.Line, 1));
            plotter.AddSeries(new Series("Buy", SeriesType.Scatter, "", Color.Green, ScatterMarkerSymbol.Triangle));
            plotter.AddSeries(new Series("Sell", SeriesType.Scatter, "", Color.Red, ScatterMarkerSymbol.TriangleDown));
            //plotter.AddSeries(new Series("Stopped", SeriesType.Scatter, "", Color.Yellow, ScatterMarkerSymbol.Diamond));
            plotter.AddSeries(new Series("Diff", SeriesType.Bar, 2));
            plotter.AddSeries(new Series("Slope", SeriesType.Line, 3));
            plotter.AddSeries(new Series("STC", SeriesType.Line, 4));
            plotter.AddSeries(new Series("STOCH", SeriesType.Line, 5));
            plotter.AddSeries(new Series("Prediction", SeriesType.Bar, 6));
            plotter.AddSeries(new Series("Signal", SeriesType.Bar, 7));
            AddChart(plotter);
        }
Ejemplo n.º 12
0
        public override void Initialize()
        {
            SetStartDate(2007, 4, 1);
            SetEndDate(DateTime.Now);
            SetCash(2000);

            SetBenchmark(SecurityType.Forex, "EURUSD");

            //Add as many securities as you like. All the data will be passed into the event handler:
            foreach (var symbol in _symbols)
            {
                AddSecurity(SecurityType.Forex, symbol, _dataResolution);
                //Securities[symbol].FeeModel = new ConstantFeeModel(0.04m);
                Securities[symbol].FeeModel         = new FxcmFeeModel();
                Securities[symbol].SlippageModel    = new SpreadSlippageModel();
                Securities[symbol].TransactionModel = new FxcmTransactionModel();
                //Securities[symbol].SetLeverage(50.0m);
                SetBrokerageModel(BrokerageName.FxcmBrokerage);

                Schedule.On(DateRules.Every(DayOfWeek.Sunday, DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday),
                            TimeRules.AfterMarketOpen(symbol, -60d), () =>
                {
                    Securities[symbol].IsTradable = false;
                    // make untradeable
                });

                Schedule.On(DateRules.Every(DayOfWeek.Sunday, DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday),
                            TimeRules.AfterMarketOpen(symbol, 120d), () =>
                {
                    // make tradeable
                });

                Schedule.On(DateRules.Every(DayOfWeek.Friday), TimeRules.BeforeMarketClose(symbol, -60d), () =>
                {
                    Liquidate();
                    // make untradeable
                });

                _vwaps.Add(symbol, VWAP(symbol, 30));

                var rsi = RSI(symbol, 30, MovingAverageType.Exponential, _dataResolution);

                var momersion = MOMERSION(symbol, 10, 30, _dataResolution);

                var williams = WILR(symbol, 60, _dataResolution);

                var ind = SMA(symbol, 10, _dataResolution, x => rsi);

                var adx = ADX(symbol, 30, _dataResolution);

                var psar = PSAR(symbol, 0.02M, 0.02M, 0.2M, _dataResolution);

                var fisher = new FisherTransform(symbol, 30);

                var stoch1 = STO(symbol, 30, 30, 60);
                var stoch2 = new Stochastic(symbol, 30, 30, 60);

                var rocp = ROCP(symbol, 30, _dataResolution);

                var tradeBarHistory = History(symbol, TimeSpan.FromDays(2), _dataResolution);

                foreach (var tradeBar in tradeBarHistory)
                {
                    _vwaps[symbol].Update(tradeBar);
                }

                Securities[symbol].VolatilityModel = new ThreeSigmaVolatilityModel(STD(symbol, 390, _dataResolution));
                _tradingAssets.Add(symbol,
                                   new TradingAsset(Securities[symbol],
                                                    new OneShotTrigger(new VwapSignal(_vwaps[symbol], Portfolio[symbol])),
                                                    new ProfitTargetSignalExit(null, TargetProfitLossRatio),
                                                    RiskPerTrade,
                                                    MaximumTradeSize,
                                                    this
                                                    ));
            }
        }
Ejemplo n.º 13
0
        public override void Initialize()
        {
            SetCash(10000);
            SetStartDate(1998, 1, 1);
            SetEndDate(DateTime.Now);
            //SetBenchmark("SPY");

            SetWarmup(44);

            foreach (var symbol in _symbols)
            {
                AddSecurity(SecurityType.Equity, symbol, Resolution.Daily);
                _selectionDatas.AddOrUpdate(symbol, new TrendSelectionData(symbol));
            }

            Schedule.On(DateRules.On(new DateTime(2000, 7, 1), new DateTime(2007, 10, 1)), TimeRules.BeforeMarketClose("SPY"), () =>
            {
                Log("Sell >> " + Securities["SPY"].Price + " Symbol " + "SPY");
                SetHoldings("SPY", -FractionOfPortfolio);
            });

            _chart = new Chart("ICH", ChartType.Overlay);
            _chart.AddSeries(new Series("Price", SeriesType.Line));
            _chart.AddSeries(new Series("Tenkan", SeriesType.Line));
            _chart.AddSeries(new Series("Kijun", SeriesType.Line));
            _chart.AddSeries(new Series("SenkouA", SeriesType.Line));
            _chart.AddSeries(new Series("SenkouB", SeriesType.Line));
            _chart.AddSeries(new Series("ADX", SeriesType.Line));
            _chart.AddSeries(new Series("ADX.NegativeDirectionalIndex", SeriesType.Line));
            _chart.AddSeries(new Series("ADX.PositiveDirectionalIndex", SeriesType.Line));
        }
Ejemplo n.º 14
0
        // TODO: check volatilitymodel https://github.com/QuantConnect/Lean/blob/master/Common/Securities/RelativeStandardDeviationVolatilityModel.cs
        public override void Initialize()
        {
            SetStartDate(2016, 1, 1);
            SetEndDate(2016, 4, 1);
            SetCash(3000);

            SetBrokerageMessageHandler(new CustomBrokerageMessageHandler(this));

            var allInputs  = new List <double[]>();
            var allOutputs = new List <int>();
            var allWeights = new List <double>();

            foreach (var symbol in Symbols)
            {
                AddForex(symbol, _dataResolution, Market.Oanda, false, 1m);

                Securities[symbol].TransactionModel = new OandaTransactionModel();
                //Securities[symbol].SlippageModel = new ConstantSlippageModel(0m);
                SetBrokerageModel(BrokerageName.OandaBrokerage);

                /************ TRAINING ************/
                var trainingResolution = Resolution.Minute;

                /*var slowT = HMA(symbol, 28, trainingResolution, Field.Close);
                 * var slowSlopeT = new InstantTrend(symbol, 5).Of(slowT);
                 * var returnT = LOGR(symbol, 3, trainingResolution, Field.Close);
                 * var returnSlopeT = LSMA(symbol, 5, trainingResolution).Of(returnT);*/

                var consolidatorT = new QuoteBarConsolidator(TimeSpan.FromMinutes(15));
                var stochT        = new Stochastic(symbol, 14, 3, 3);
                var stochTMA      = new HullMovingAverage(symbol, 3).Of(stochT);
                var emaT          = new ExponentialMovingAverage(symbol, 40);
                RegisterIndicator(symbol, stochT, consolidatorT);
                RegisterIndicator(symbol, emaT, consolidatorT);
                SubscriptionManager.AddConsolidator(symbol, consolidatorT);

                var historyT = History <QuoteBar>(symbol, TimeSpan.FromDays(500), trainingResolution);

                var quoteBars     = new List <QuoteBar>();
                var stochs        = new List <double>();
                var rollingStochs = new RollingWindow <double>(1000);
                var stochsMA      = new List <double>();
                var emas          = new List <double>();
                var stochCount    = new List <double>();
                var stochAverage  = new List <double>();

                //consolidatorT.DataConsolidated += (sender, args) => quoteBars.Add(args);
                stochTMA.Updated += (sender, args) =>
                {
                    if (!stochTMA.IsReady || !emaT.IsReady)
                    {
                        return;
                    }

                    quoteBars.Add((QuoteBar)consolidatorT.Consolidated);
                    stochs.Add((double)stochT.Current.Value);
                    rollingStochs.Add((double)args.Value);
                    stochsMA.Add((double)args.Value);
                    emas.Add((double)emaT.Current.Value);

                    var filtered = rollingStochs.TakeWhile((s) => args.Value > 50 ? s > 50 : args.Value < 50 ? s < 50 : false);
                    stochCount.Add(filtered.Count());

                    try
                    {
                        stochAverage.Add(filtered.Average());
                    }
                    catch (Exception ex)
                    {
                        stochAverage.Add(0);
                    }
                };

                foreach (var bar in historyT)
                {
                    consolidatorT.Update(bar);
                }

                Console.WriteLine("{0} {1} {2} {3} {4}", quoteBars.Count, stochs.Count, stochCount.Count, stochAverage.Count, emas.Count);

                var inputs  = new List <double[]>();
                var outputs = new List <int>();
                var weights = new List <double>();

                for (var i = 1; i < quoteBars.Count; i++)
                {
                    var longTarget  = quoteBars[i].Close + (30m / 10000m);
                    var longStop    = quoteBars[i].Close - (10m / 10000m);
                    var shortTarget = quoteBars[i].Close - (30m / 10000m);
                    var shortStop   = quoteBars[i].Close + (10m / 10000m);

                    var longSetup  = stochs[i] >= 35 && stochsMA[i] > stochsMA[i - 1] && (double)quoteBars[i].Close > emas[i];
                    var shortSetup = stochs[i] <= 65 && stochs[i] > 0 && stochsMA[i] < stochsMA[i - 1] && (double)quoteBars[i].Close < emas[i];

                    if (!longSetup && !shortSetup)
                    {
                        continue;
                    }

                    for (var j = i + 1; j < quoteBars.Count; j++)
                    {
                        var current = quoteBars[j];
                        if (current.High >= longTarget && current.Low > longStop && longSetup)
                        {
                            inputs.Add(new double[] { stochAverage[i], stochCount[i], (double)quoteBars[i].Close / emas[i] });
                            outputs.Add(1);

                            var profit = current.High - quoteBars[i].Close;

                            /*for (var k = j + 1; k < quoteBars.Count; k++)
                             * {
                             *
                             * }*/
                            weights.Add((double)(1m - (50m / 10000m) / profit));

                            //i = j;
                            break;
                        }
                        else if (current.Low <= shortTarget && current.High < shortStop && shortSetup)
                        {
                            inputs.Add(new double[] { stochAverage[i], stochCount[i], (double)quoteBars[i].Close / emas[i] });
                            outputs.Add(0);

                            var profit = quoteBars[i].Close - current.Low;

                            /*for (var k = j + 1; k < quoteBars.Count; k++)
                             * {
                             *
                             * }*/
                            weights.Add((double)(1m - (50m / 10000m) / profit));
                            //i = j;
                            break;
                        }
                        else if ((current.Low <= longStop && longSetup) || (current.High >= shortStop && shortSetup))
                        {
                            //inputs.Add(new double[] { stochAverage[i] / stochs[i], stochCount[i], stochAverage[i] });
                            //outputs.Add(2);
                            //i = j;
                            break;
                        }

                        /*else if (j - i > 4 * 8)
                         * {
                         *  inputs.Add(new double[] { stochs[i], stochCount[i], stochAverage[i] });
                         *  outputs.Add(0);
                         *  //i = j;
                         *  break;
                         * }*/
                    }
                }

                allInputs.AddRange(inputs);
                allOutputs.AddRange(outputs);
                allWeights.AddRange(weights);

                for (var i = 0; i < inputs.Count; i++)
                {
                    //Console.WriteLine("Input: " + inputs[i][0] + " " + inputs[i][1] + " " + inputs[i][2] + " Output: " + outputs[i]);
                }

                var none = outputs.Where((o) => o == 2).Count();
                var sell = outputs.Where((o) => o == 0).Count();
                var buy  = outputs.Where((o) => o == 1).Count();

                Console.WriteLine("Total: {0} None: {1} Short: {2} Long: {3}", outputs.Count, none, sell, buy);

                /************ HMA ************/

                /*var slow = HMA(symbol, 28, trainingResolution, Field.Close);
                 * var slowSlope = new InstantTrend(symbol, 5).Of(slow);
                 * var logReturns = LOGR(symbol, 3, trainingResolution, Field.Close);
                 * var returnSlope = LSMA(symbol, 5, trainingResolution).Of(logReturns);*/

                var consolidator = new QuoteBarConsolidator(TimeSpan.FromMinutes(15));
                var stoch        = new Stochastic(symbol, 14, 3, 3);
                var stochMA      = new HullMovingAverage(symbol, 2).Of(stoch);
                var ema          = new ExponentialMovingAverage(symbol, 40);
                var rolling      = new RollingWindow <double>(1000);
                RegisterIndicator(symbol, stoch, consolidator);
                RegisterIndicator(symbol, ema, consolidator);
                SubscriptionManager.AddConsolidator(symbol, consolidator);

                _stoch[symbol] = stoch;
                _ema[symbol]   = ema;

                stochMA.Updated += (sender, args) =>
                {
                    rolling.Add((double)args.Value);

                    if (Securities[symbol].Price > 0)
                    {
                        //Plot("Plotter", "Price", Securities["EURUSD"].Price);
                        Plot("Indicator", "STO", rolling[0]);
                    }
                };

                var std = ATR(symbol, 100, MovingAverageType.DoubleExponential, _dataResolution);

                var history = History <QuoteBar>(symbol, TimeSpan.FromDays(20), trainingResolution);

                foreach (var bar in history)
                {
                    //slow.Update(bar.EndTime, bar.Close);
                    //logReturns.Update(bar.EndTime, bar.Close);
                    std.Update(bar);
                    consolidator.Update(bar);
                }

                var signal = new SVMSignal(consolidator, stoch, stochMA, rolling, ema, Portfolio[symbol], this);
                signal.TrainSVM(inputs, outputs, weights);
                //signal.TrainNN(inputs, outputs, weights);

                Securities[symbol].VolatilityModel = new AverageTrueRangeVolatilityModel(std);
                _tradingAssets.Add(symbol,
                                   new TradingAsset(Securities[symbol],
                                                    new OneShotTrigger(signal),
                                                    new ProfitTargetSignalExit(null, _targetProfitLoss),
                                                    _maximumTradeRisk,
                                                    _maximumTradeSize,
                                                    this
                                                    ));
            }

            foreach (var symbol in Symbols)
            {
                //_tradingAssets[symbol].Retrain(allInputs, allOutputs, allWeights);
            }

            //AddData<DailyFx>("DFX", Resolution.Second, TimeZones.Utc);

            Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday),
                        TimeRules.At(7, 0, TimeZones.London), () =>
            {
                var tradeableDay = TradingCalendar.GetTradingDay().BusinessDay;
                if (tradeableDay)
                {
                    foreach (var s in Symbols)
                    {
                        _tradingAssets[s].IsTradable = true;
                    }
                }
            });

            Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday),
                        TimeRules.At(18, 0, TimeZones.London), () =>
            {
                foreach (var s in Symbols)
                {
                    _tradingAssets[s].IsTradable = false;
                }
            });

            Schedule.On(DateRules.Every(DayOfWeek.Friday),
                        TimeRules.BeforeMarketClose(Symbols.First(), 60), () =>
            {
                foreach (var s in Symbols)
                {
                    _tradingAssets[s].Liquidate();
                }
            });

            Chart plotter = new Chart("Plotter");

            plotter.AddSeries(new Series("Price", SeriesType.Line, 0));
            plotter.AddSeries(new Series("EMA", SeriesType.Line, 0));
            plotter.AddSeries(new Series("Buy", SeriesType.Scatter, "", Color.Green, ScatterMarkerSymbol.Triangle));
            plotter.AddSeries(new Series("Sell", SeriesType.Scatter, "", Color.Red, ScatterMarkerSymbol.TriangleDown));
            plotter.AddSeries(new Series("Stopped", SeriesType.Scatter, "", Color.Yellow, ScatterMarkerSymbol.Diamond));
            plotter.AddSeries(new Series("Prediction", SeriesType.Bar, 1));
            plotter.AddSeries(new Series("Probability", SeriesType.Bar, 2));
            AddChart(plotter);

            Chart indicator = new Chart("Indicator");

            indicator.AddSeries(new Series("STO", SeriesType.Line, 0));
            AddChart(indicator);

            Chart prediction = new Chart("Prediction");

            prediction.AddSeries(new Series("Pred", SeriesType.Bar, 0));
            AddChart(prediction);

            Chart probability = new Chart("Probability");

            probability.AddSeries(new Series("Prob", SeriesType.Bar, 0));
            AddChart(probability);
        }
Ejemplo n.º 15
0
        // TODO: check volatilitymodel https://github.com/QuantConnect/Lean/blob/master/Common/Securities/RelativeStandardDeviationVolatilityModel.cs
        public override void Initialize()
        {
            SetStartDate(2016, 1, 1);
            SetEndDate(2017, 1, 1);
            SetCash(3000);

            SetBrokerageMessageHandler(new CustomBrokerageMessageHandler(this));

            foreach (var symbol in Symbols)
            {
                AddForex(symbol, _dataResolution, Market.Oanda, false, 1m);

                Securities[symbol].TransactionModel = new OandaTransactionModel();
                //Securities[symbol].SlippageModel = new ConstantSlippageModel(0m);
                SetBrokerageModel(BrokerageName.OandaBrokerage);

                var consolidator = new QuoteBarConsolidator(TimeSpan.FromMinutes(20));
                var stoch        = new Stochastic(symbol, 10, 3, 3);
                var stochMA      = new ExponentialMovingAverage(symbol, 25).Of(stoch);
                var stochEmaLSMA = new LeastSquaresMovingAverage(symbol, 5).Of(stochMA);
                var ema          = new ExponentialMovingAverage(symbol, 40);
                var emaMA        = new LeastSquaresMovingAverage(symbol, 5).Of(ema);

                var rollingStochMA       = HistoryTracker.Track(stochMA);
                var rollingEmaSlope      = HistoryTracker.Track(emaMA.Slope);
                var rollingStochEmaSlope = HistoryTracker.Track(stochEmaLSMA.Slope);

                var shortTermMA = EMA(symbol, 30, Resolution.Minute, Field.Close);

                RegisterIndicator(symbol, stoch, consolidator);
                RegisterIndicator(symbol, ema, consolidator);
                SubscriptionManager.AddConsolidator(symbol, consolidator);

                _stoch[symbol] = stoch;
                _ema[symbol]   = ema;

                var consolidatorDaily = new QuoteBarConsolidator(TimeSpan.FromHours(1));
                var dailyMA           = new HullMovingAverage(symbol, 7);
                var dailyEmaLSMA      = new LeastSquaresMovingAverage(symbol, 3).Of(dailyMA);

                var rollingDailyEmaSlope = HistoryTracker.Track(dailyEmaLSMA.Slope);

                RegisterIndicator(symbol, dailyMA, consolidatorDaily);
                SubscriptionManager.AddConsolidator(symbol, consolidatorDaily);

                stochMA.Updated += (sender, args) =>
                {
                    if (Securities[symbol].Price > 0)
                    {
                        Plot("Indicator", "STO", rollingStochMA[0]);
                    }
                };

                stochEmaLSMA.Updated += (sender, args) =>
                {
                    if (Securities[symbol].Price > 0)
                    {
                        Plot("IndicatorTrend", "STO", stochEmaLSMA.Slope);
                    }
                };

                /*emaMA.Updated += (sender, args) =>
                 * {
                 *  if (Securities[symbol].Price > 0)
                 *  {
                 *      Plot("Trend", "LSMA", emaMA.Slope);
                 *  }
                 * };*/

                dailyEmaLSMA.Updated += (sender, args) =>
                {
                    if (Securities[symbol].Price > 0)
                    {
                        Plot("Trend", "LSMA", dailyEmaLSMA.Slope);
                        Plot("Trend", "EMA", dailyMA);
                    }
                };

                var std = ATR(symbol, 100, MovingAverageType.DoubleExponential, _dataResolution);

                var history = History <QuoteBar>(symbol, TimeSpan.FromDays(40), _dataResolution);

                foreach (var bar in history)
                {
                    std.Update(bar);
                    consolidator.Update(bar);
                    shortTermMA.Update(bar.EndTime, bar.Close);
                    consolidatorDaily.Update(bar);
                }

                var signal = new SVMBaselineSignalWIP(consolidator, stoch, stochMA, rollingStochMA, stochEmaLSMA, rollingStochEmaSlope, ema, emaMA,
                                                      rollingEmaSlope, shortTermMA, dailyEmaLSMA, rollingDailyEmaSlope, Portfolio[symbol], Securities[symbol], this);

                Securities[symbol].VolatilityModel = new AverageTrueRangeVolatilityModel(std);
                _tradingAssets.Add(symbol,
                                   new TradingAsset(Securities[symbol],
                                                    new OneShotTrigger(signal),
                                                    new ProfitTargetSignalExit(null, _targetProfitLoss),
                                                    _maximumTradeRisk,
                                                    _maximumTradeSize,
                                                    this
                                                    ));
            }

            //AddData<DailyFx>("DFX", Resolution.Second, TimeZones.Utc);

            Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday),
                        TimeRules.At(7, 0, TimeZones.London), () =>
            {
                var tradeableDay = TradingCalendar.GetTradingDay().BusinessDay;
                if (tradeableDay)
                {
                    foreach (var s in Symbols)
                    {
                        _tradingAssets[s].IsTradable = true;
                    }
                }
            });

            Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday),
                        TimeRules.At(20, 0, TimeZones.London), () =>
            {
                foreach (var s in Symbols)
                {
                    _tradingAssets[s].IsTradable = false;
                }
            });

            Schedule.On(DateRules.Every(DayOfWeek.Friday),
                        TimeRules.BeforeMarketClose(Symbols.First(), 60), () =>
            {
                foreach (var s in Symbols)
                {
                    _tradingAssets[s].Liquidate();
                }
            });

            Chart plotter = new Chart("Plotter");

            plotter.AddSeries(new Series("Price", SeriesType.Line, 0));
            plotter.AddSeries(new Series("EMA", SeriesType.Line, 0));
            plotter.AddSeries(new Series("Buy", SeriesType.Scatter, "", Color.Green, ScatterMarkerSymbol.Triangle));
            plotter.AddSeries(new Series("Sell", SeriesType.Scatter, "", Color.Red, ScatterMarkerSymbol.TriangleDown));
            plotter.AddSeries(new Series("Stopped", SeriesType.Scatter, "", Color.Yellow, ScatterMarkerSymbol.Diamond));
            plotter.AddSeries(new Series("Prediction", SeriesType.Bar, 1));
            plotter.AddSeries(new Series("Probability", SeriesType.Bar, 2));
            AddChart(plotter);

            Chart indicator = new Chart("Indicator");

            indicator.AddSeries(new Series("STO", SeriesType.Line, 0));
            AddChart(indicator);

            Chart indicatorTrend = new Chart("IndicatorTrend");

            indicatorTrend.AddSeries(new Series("STO", SeriesType.Line, 0));
            AddChart(indicatorTrend);

            Chart trend = new Chart("Trend");

            trend.AddSeries(new Series("LSMA", SeriesType.Line, 0));
            trend.AddSeries(new Series("EMA", SeriesType.Line, 1));
            AddChart(trend);

            Chart prediction = new Chart("Prediction");

            prediction.AddSeries(new Series("Pred", SeriesType.Bar, 0));
            AddChart(prediction);

            Chart probability = new Chart("Probability");

            probability.AddSeries(new Series("Prob", SeriesType.Bar, 0));
            AddChart(probability);
        }