Example #1
0
        public void GetYearExists()
        {
            var mockRepository = new MockRepository(MockBehavior.Strict);

            var tradingCalendar = new TradingCalendar(Guid.NewGuid());

            tradingCalendar.SetNonTradingDays(2000, new[] { new NonTradingDay(new Date(2000, 01, 01), "New Year's Day") });
            var repository = mockRepository.Create <IRepository <TradingCalendar> >();

            repository.Setup(x => x.Get(tradingCalendar.Id)).Returns(tradingCalendar);

            var service = new TradingCalendarService(repository.Object, tradingCalendar.Id);

            var result   = service.Get(2000);
            var response = result.Result;

            response.Should().BeEquivalentTo(new
            {
                Year           = 2000,
                NonTradingDays = new []
                {
                    new RestApi.TradingCalendars.TradingCalendar.NonTradingDay()
                    {
                        Date = new Date(2000, 01, 01), Description = "New Year's Day"
                    }
                },
            });
        }
Example #2
0
        public void SetNonTradingDays()
        {
            var mockRepository = new MockRepository(MockBehavior.Strict);

            var tradingCalendar = new TradingCalendar(Guid.NewGuid());

            tradingCalendar.SetNonTradingDays(2001, new[] { new NonTradingDay(new Date(2001, 01, 01), "New Year's Day") });
            var repository = mockRepository.Create <IRepository <TradingCalendar> >();

            repository.Setup(x => x.Get(tradingCalendar.Id)).Returns(tradingCalendar);
            repository.Setup(x => x.Update(tradingCalendar));

            var service = new TradingCalendarService(repository.Object, tradingCalendar.Id);

            var calendarReference = service.TradingCalendar;

            using (new AssertionScope())
            {
                calendarReference.IsTradingDay(new Date(2001, 01, 01)).Should().BeFalse();
                calendarReference.IsTradingDay(new Date(2001, 12, 25)).Should().BeTrue();
            }

            service.SetNonTradingDays(2001, new[] { new NonTradingDay(new Date(2001, 12, 25), "Christmas Day") });

            using (new AssertionScope())
            {
                calendarReference.IsTradingDay(new Date(2001, 01, 01)).Should().BeTrue();
                calendarReference.IsTradingDay(new Date(2001, 12, 25)).Should().BeFalse();
            }

            mockRepository.Verify();
        }
        public void TestBasicFeaturesWithOptionsFutures()
        {
            var securities          = new SecurityManager(TimeKeeper);
            var marketHoursDatabase = MarketHoursDatabase.FromDataFolder();

            securities.Add(Symbols.SPY, new Security(SecurityExchangeHours, CreateTradeBarDataConfig(SecurityType.Equity, Symbols.SPY), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency)));
            securities[Symbols.SPY].SetMarketPrice(new TradeBar {
                Time = securities.UtcTime, Symbol = Symbols.SPY, Close = 195
            });

            var option1 = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 192m, new DateTime(2016, 02, 16));

            securities.Add(option1, new Option(SecurityExchangeHours, CreateTradeBarDataConfig(SecurityType.Option, option1), new Cash(CashBook.AccountCurrency, 0, 1m), new OptionSymbolProperties(SymbolProperties.GetDefault(CashBook.AccountCurrency))));

            var option2 = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 193m, new DateTime(2016, 03, 19));

            securities.Add(option2, new Option(SecurityExchangeHours, CreateTradeBarDataConfig(SecurityType.Option, option2), new Cash(CashBook.AccountCurrency, 0, 1m), new OptionSymbolProperties(SymbolProperties.GetDefault(CashBook.AccountCurrency))));

            var future1 = Symbol.CreateFuture("ES", Market.USA, new DateTime(2016, 02, 16));

            securities.Add(future1, new Future(SecurityExchangeHours, CreateTradeBarDataConfig(SecurityType.Future, future1), new Cash(CashBook.AccountCurrency, 0, 1m), new OptionSymbolProperties(SymbolProperties.GetDefault(CashBook.AccountCurrency))));

            var future2 = Symbol.CreateFuture("ES", Market.USA, new DateTime(2016, 02, 19));

            securities.Add(future2, new Future(SecurityExchangeHours, CreateTradeBarDataConfig(SecurityType.Future, future2), new Cash(CashBook.AccountCurrency, 0, 1m), new OptionSymbolProperties(SymbolProperties.GetDefault(CashBook.AccountCurrency))));

            var cal = new TradingCalendar(securities, marketHoursDatabase);

            var optionDays = cal.GetDaysByType(TradingDayType.OptionExpiration, new DateTime(2016, 02, 16), new DateTime(2016, 03, 19)).Count();

            Assert.AreEqual(2, optionDays);

            var futureDays = cal.GetDaysByType(TradingDayType.OptionExpiration, new DateTime(2016, 02, 16), new DateTime(2016, 03, 19)).Count();

            Assert.AreEqual(2, futureDays);

            var days = cal.GetTradingDays(new DateTime(2016, 02, 16), new DateTime(2016, 03, 19));

            var optionAndfutureDays = days.Where(x => x.FutureExpirations.Any() || x.OptionExpirations.Any()).Count();

            Assert.AreEqual(3, optionAndfutureDays);

            // why? because option1 and future1 expire in one day 2016-02-16. Lets have a look.
            var day = cal.GetTradingDay(new DateTime(2016, 02, 16));

            Assert.AreEqual(1, day.OptionExpirations.Count());
            Assert.AreEqual(1, day.FutureExpirations.Count());

            var businessDays = days.Where(x => x.BusinessDay).Count();

            Assert.AreEqual(24, businessDays);

            var weekends = days.Where(x => x.Weekend).Count();

            Assert.AreEqual(9, weekends);

            Assert.AreEqual(24 + 9, (new DateTime(2016, 03, 19) - new DateTime(2016, 02, 16)).TotalDays + 1 /*inclusive*/);
        }
Example #4
0
        public void ReversedDateRequestThrows()
        {
            var securities          = new SecurityManager(TimeKeeper);
            var marketHoursDatabase = MarketHoursDatabase.FromDataFolder();
            var calendar            = new TradingCalendar(securities, marketHoursDatabase);

            Assert.Throws <ArgumentException>(() =>
                                              calendar.GetTradingDays(new DateTime(2010, 2, 28), new DateTime(2010, 2, 10)).ToList());
        }
        public TradingCalendarService(IRepository <TradingCalendar> repository, Guid calendarId)
        {
            _Repository = repository;

            try
            {
                _TradingCalendar = _Repository.Get(calendarId);
            }
            catch
            {
                _TradingCalendar = new TradingCalendar(calendarId);
            }
        }
        public void SetNewTradingDaysForInvalidYear()
        {
            var tradingCalendar = new TradingCalendar(Guid.NewGuid());

            var nonTradingDays = new NonTradingDay[] {
                new NonTradingDay(new Date(2019, 01, 01), "New Years Day"),
                new NonTradingDay(new Date(2020, 12, 25), "Christmas Day")
            };

            Action a = () => tradingCalendar.SetNonTradingDays(2019, nonTradingDays);

            a.Should().Throw <ArgumentException>();
        }
        public void RetriveNonTradingDaysForYear()
        {
            var tradingCalendar = new TradingCalendar(Guid.NewGuid());

            var nonTradingDays = new NonTradingDay[] {
                new NonTradingDay(new Date(2019, 01, 01), "New Years Day"),
                new NonTradingDay(new Date(2019, 12, 25), "Christmas Day")
            };

            tradingCalendar.SetNonTradingDays(2019, nonTradingDays);

            tradingCalendar.NonTradingDays(2019).Should().HaveCount(2);
        }
        public void RetriveNonTradingDaysForYearWithNoData()
        {
            var tradingCalendar = new TradingCalendar(Guid.NewGuid());

            var nonTradingDays = new NonTradingDay[] {
                new NonTradingDay(new Date(2019, 01, 01), "New Years Day"),
                new NonTradingDay(new Date(2019, 12, 25), "Christmas Day")
            };

            tradingCalendar.SetNonTradingDays(2019, nonTradingDays);

            tradingCalendar.NonTradingDays(2020).Should().BeEmpty();
        }
        public void PreviousTradingDayForWeekEnd()
        {
            var tradingCalendar = new TradingCalendar(Guid.NewGuid());

            var nonTradingDays = new NonTradingDay[] {
                new NonTradingDay(new Date(2019, 01, 01), "New Years Day"),
                new NonTradingDay(new Date(2019, 12, 25), "Christmas Day")
            };
            var @event = new NonTradingDaysSetEvent(tradingCalendar.Id, 0, 2019, nonTradingDays);

            tradingCalendar.ApplyEvents(new Event[] { @event });

            tradingCalendar.PreviousTradingDay(new Date(2019, 11, 10)).Should().Be(new Date(2019, 11, 08));
        }
        public void CheckIfDateIsAtradingDayReturnFalse()
        {
            var tradingCalendar = new TradingCalendar(Guid.NewGuid());

            var nonTradingDays = new NonTradingDay[] {
                new NonTradingDay(new Date(2019, 01, 01), "New Years Day"),
                new NonTradingDay(new Date(2019, 12, 25), "Christmas Day")
            };
            var @event = new NonTradingDaysSetEvent(tradingCalendar.Id, 0, 2019, nonTradingDays);

            tradingCalendar.ApplyEvents(new Event[] { @event });

            tradingCalendar.IsTradingDay(new Date(2019, 01, 01)).Should().BeFalse();
        }
        public void EnumerateTradingDays()
        {
            var tradingCalendar = new TradingCalendar(Guid.NewGuid());

            var nonTradingDays = new NonTradingDay[] {
                new NonTradingDay(new Date(2019, 01, 01), "New Years Day"),
                new NonTradingDay(new Date(2019, 12, 25), "Christmas Day")
            };

            tradingCalendar.SetNonTradingDays(2019, nonTradingDays);

            var tradingDays = tradingCalendar.TradingDays(new DateRange(new Date(2019, 01, 01), new Date(2019, 01, 10))).ToList();

            tradingDays.Should().HaveCount(7).And.BeInAscendingOrder().And.OnlyHaveUniqueItems();
        }
Example #12
0
        public void CreateServiceForExistingCalendar()
        {
            var mockRepository = new MockRepository(MockBehavior.Strict);

            var tradingCalendar = new TradingCalendar(Guid.NewGuid());

            tradingCalendar.SetNonTradingDays(2000, new[] { new NonTradingDay(new Date(2000, 01, 01), "New Year's Day") });
            var repository = mockRepository.Create <IRepository <TradingCalendar> >();

            repository.Setup(x => x.Get(tradingCalendar.Id)).Returns(tradingCalendar);

            var service = new TradingCalendarService(repository.Object, tradingCalendar.Id);

            service.TradingCalendar.Should().Be(tradingCalendar);

            mockRepository.Verify();
        }
        public void ApplyNonTradingDaysSetEvent()
        {
            var tradingCalendar = new TradingCalendar(Guid.NewGuid());

            var nonTradingDays = new NonTradingDay[] {
                new NonTradingDay(new Date(2019, 01, 01), "New Years Day"),
                new NonTradingDay(new Date(2019, 12, 25), "Christmas Day")
            };
            var @event = new NonTradingDaysSetEvent(tradingCalendar.Id, 0, 2019, nonTradingDays);

            tradingCalendar.ApplyEvents(new Event[] { @event });

            using (new AssertionScope())
            {
                tradingCalendar.IsTradingDay(new Date(2019, 01, 01)).Should().BeFalse();
                tradingCalendar.IsTradingDay(new Date(2019, 12, 25)).Should().BeFalse();
                tradingCalendar.IsTradingDay(new Date(2019, 01, 02)).Should().BeTrue();
            }
        }
Example #14
0
        public void Update()
        {
            var mockRepository = new MockRepository(MockBehavior.Strict);

            var tradingCalendar = new TradingCalendar(Guid.NewGuid());

            tradingCalendar.SetNonTradingDays(2001, new[] { new NonTradingDay(new Date(2001, 01, 01), "New Year's Day") });
            var repository = mockRepository.Create <IRepository <TradingCalendar> >();

            repository.Setup(x => x.Get(tradingCalendar.Id)).Returns(tradingCalendar);
            repository.Setup(x => x.Update(tradingCalendar));

            var service = new TradingCalendarService(repository.Object, tradingCalendar.Id);

            var calendarReference = service.TradingCalendar;

            using (new AssertionScope())
            {
                calendarReference.IsTradingDay(new Date(2001, 01, 01)).Should().BeFalse();
                calendarReference.IsTradingDay(new Date(2001, 12, 25)).Should().BeTrue();
            }

            var updatedTradingCalendar = new RestApi.TradingCalendars.TradingCalendar();

            updatedTradingCalendar.Year = 2001;
            updatedTradingCalendar.NonTradingDays.Add(new RestApi.TradingCalendars.TradingCalendar.NonTradingDay()
            {
                Date = new Date(2001, 12, 25), Description = "Christmas Day"
            });

            var result = service.Update(updatedTradingCalendar);

            using (new AssertionScope())
            {
                result.Should().HaveOkStatus();

                calendarReference.IsTradingDay(new Date(2001, 01, 01)).Should().BeTrue();
                calendarReference.IsTradingDay(new Date(2001, 12, 25)).Should().BeFalse();
            }

            mockRepository.Verify();
        }
        public void SerializeTradingCalander()
        {
            var serializer = new RestClientSerializer();

            var request = new TradingCalendar()
            {
                Year = 2013
            };

            request.AddNonTradingDay(new Date(2013, 01, 01), "New Year's Day");
            request.AddNonTradingDay(new Date(2013, 12, 25), "Christmas Day");

            var json = JToken.Parse(serializer.Serialize(request));

            var expectedJson = JToken.Parse("{\"year\":2013,\"nonTradingDays\":["
                                            + "{\"date\":\"2013-01-01\",\"description\":\"New Year's Day\"},"
                                            + "{\"date\":\"2013-12-25\",\"description\":\"Christmas Day\"}]}");

            json.Should().BeEquivalentTo(expectedJson);
        }
        public void SetNewTradingDays()
        {
            var tradingCalendar = new TradingCalendar(Guid.NewGuid());

            var nonTradingDays = new NonTradingDay[] {
                new NonTradingDay(new Date(2019, 01, 01), "New Years Day"),
                new NonTradingDay(new Date(2019, 12, 25), "Christmas Day")
            };

            tradingCalendar.SetNonTradingDays(2019, nonTradingDays);

            var events = tradingCalendar.FetchEvents().ToList();

            events.Should().SatisfyRespectively(

                first => first.Should().BeOfType <NonTradingDaysSetEvent>().Which.NonTradingDays.Should().SatisfyRespectively(
                    day1 => day1.Should().BeEquivalentTo(new { Date = new Date(2019, 01, 01), Description = "New Years Day" }),
                    day2 => day2.Should().BeEquivalentTo(new { Date = new Date(2019, 12, 25), Description = "Christmas Day" })
                    )
                );
        }
        public async Task UpdateTradingCalendar()
        {
            var mockRepository = new MockRepository(MockBehavior.Strict);

            var messageHandler = mockRepository.Create <IRestClientMessageHandler>();

            messageHandler.Setup(x => x.PostAsync <TradingCalendar>(
                                     It.Is <string>(x => x == "tradingcalendars/" + 2013),
                                     It.Is <TradingCalendar>(x => x.Year == 2013)))
            .Returns(Task.CompletedTask)
            .Verifiable();

            var resource = new TradingCalandarResource(messageHandler.Object);

            var tradingCalander = new TradingCalendar()
            {
                Year = 2013
            };
            await resource.Update(tradingCalander);

            mockRepository.Verify();
        }
Example #18
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);
        }
Example #19
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);
        }
Example #20
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);
        }
 public async Task Update(TradingCalendar calendar)
 {
     await _MessageHandler.PostAsync <TradingCalendar>("tradingcalendars/" + calendar.Year.ToString(), calendar);
 }
        public ActionResult Update([FromRoute] int year, [FromBody] TradingCalendar tradingCalendar)
        {
            var result = _Service.Update(tradingCalendar);

            return(result.ToActionResult());
        }