예제 #1
0
        public FuzzySignal(RelativeStrengthIndex rsi, SecurityHolding securityHolding)
        {
            _rsi             = rsi;
            _securityHolding = securityHolding;

            _engine = new FuzzyEngine();
        }
예제 #2
0
        public void ComputesUnrealizedProfit()
        {
            var security = GetSecurity <QuantConnect.Securities.Equity.Equity>(Symbols.SPY, Resolution.Daily);
            var holding  = new SecurityHolding(security);

            var last     = 100m;
            var bid      = 99m;
            var ask      = 101m;
            var orderFee = 1m;

            security.SetMarketPrice(new Tick(DateTime.Now, security.Symbol, last, bid, ask));

            // Long scenario: expected unrealized profit take the bid price
            var quantity = 100m;
            var expected = (bid - last) * quantity - orderFee;

            holding.SetHoldings(last, quantity);
            Assert.AreEqual(expected, holding.UnrealizedProfit);

            // Short scenario: expected unrealized profit take the ask price
            quantity = -100m;
            expected = (ask - last) * quantity - orderFee;
            holding.SetHoldings(last, quantity);
            Assert.AreEqual(expected, holding.UnrealizedProfit);
        }
예제 #3
0
 public RSISignal(RelativeStrengthIndex rsi,
                  ExponentialMovingAverage ema,
                  SecurityHolding securityHolding)
 {
     _rsi             = rsi;
     _ema             = ema;
     _securityHolding = securityHolding;
 }
예제 #4
0
        public override IEnumerable <Insight> Update(QCAlgorithm algorithm, Slice data)
        {
            if (algorithm == null)
            {
                throw new ArgumentNullException(nameof(algorithm));
            }
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            var insights = new List <Insight>();

            foreach (var kvp in algorithm.ActiveSecurities)
            {
                Symbol symbol = kvp.Key;
                if (!_symbols.Contains(symbol) ||
                    !algorithm.IsMarketOpen(symbol))
                {
                    continue;
                }

                TimeSpan now          = data.Time.TimeOfDay;
                bool     longInHours  = InHours(_openTimeLong, now, _closeTimeLong);
                bool     shortInHours = InHours(_openTimeShort, now, _closeTimeShort);

                SecurityHolding holding = algorithm.Portfolio[symbol];
                if (!holding.Invested && longInHours)
                {
                    TimeSpan duration = (_closeTimeLong - now).Subtract(TimeSpan.FromSeconds(1));
                    if (duration < TimeSpan.Zero)
                    {
                        duration = duration.Add(TimeSpan.FromHours(24));
                    }

                    insights.Add(Insight.Price(symbol, duration, InsightDirection.Up));
                    algorithm.Log($"Insight Up");
                }
                else if (!holding.Invested && shortInHours)
                {
                    TimeSpan duration = (_closeTimeShort - now).Subtract(TimeSpan.FromSeconds(1));
                    if (duration < TimeSpan.Zero)
                    {
                        duration = duration.Add(TimeSpan.FromHours(24));
                    }

                    insights.Add(Insight.Price(symbol, duration, InsightDirection.Down));
                    algorithm.Log($"Insight Down");
                }
                else if (holding.IsLong && !longInHours || holding.IsShort && !shortInHours)
                {
                    insights.Add(Insight.Price(symbol, _resolution, 1, InsightDirection.Flat));
                    algorithm.Log($"Insight Flat");
                }
            }

            return(insights);
        }
        public void ReducePositionWithExistingInsight(OrderDirection direction)
        {
            var insightGenerator = new OrderBasedInsightGenerator();

            var holding = new SecurityHolding(_security,
                                              new IdentityCurrencyConverter(_security.QuoteCurrency.Symbol));

            var insight = insightGenerator.GenerateInsightFromFill(new OrderEvent(
                                                                       1,
                                                                       Symbols.SPY,
                                                                       new DateTime(2013, 1, 1),
                                                                       OrderStatus.Filled,
                                                                       direction,
                                                                       1,
                                                                       direction == OrderDirection.Buy ? 2 : -2,
                                                                       OrderFee.Zero
                                                                       ), holding);

            Assert.AreEqual(1, insight.Confidence);
            Assert.AreEqual(direction == OrderDirection.Buy
                ? InsightDirection.Up : InsightDirection.Down, insight.Direction);

            holding.SetHoldings(1, direction == OrderDirection.Buy ? 2 : -2);
            insight = insightGenerator.GenerateInsightFromFill(new OrderEvent(
                                                                   1,
                                                                   Symbols.SPY,
                                                                   new DateTime(2013, 1, 1),
                                                                   OrderStatus.Filled,
                                                                   direction,
                                                                   1,
                                                                   direction == OrderDirection.Buy ? -1 : 1,
                                                                   OrderFee.Zero
                                                                   ), holding);

            Assert.AreEqual(0.5, insight.Confidence);
            Assert.AreEqual(direction == OrderDirection.Buy
                ? InsightDirection.Up : InsightDirection.Down, insight.Direction);

            holding.SetHoldings(1, direction == OrderDirection.Buy ? 1 : -1);
            insight = insightGenerator.GenerateInsightFromFill(new OrderEvent(
                                                                   1,
                                                                   Symbols.SPY,
                                                                   new DateTime(2013, 1, 1),
                                                                   OrderStatus.Filled,
                                                                   direction,
                                                                   1,
                                                                   direction == OrderDirection.Buy ? -0.5m: 0.5m,
                                                                   OrderFee.Zero
                                                                   ), holding);

            Assert.AreEqual(0.25, insight.Confidence);
            Assert.AreEqual(direction == OrderDirection.Buy
                ? InsightDirection.Up : InsightDirection.Down, insight.Direction);
        }
예제 #6
0
 public HMASignal(HullMovingAverage fast,
                  HullMovingAverage medium,
                  HullMovingAverage slow,
                  InstantTrend trend,
                  SecurityHolding securityHolding)
 {
     _fast            = fast;
     _medium          = medium;
     _slow            = slow;
     _trend           = trend;
     _securityHolding = securityHolding;
 }
예제 #7
0
        /// <summary>
        /// Buy this symbol
        /// </summary>
        public void Buy(string symbol)
        {
            SecurityHolding s = Securities[symbol].Holdings;

            if (macdDic[symbol] > 0m)
            {
                SetHoldings(symbol, 1);

                Debug("Purchasing: " + symbol + "   MACD: " + macdDic[symbol] + "   RSI: " + rsiDic[symbol]
                      + "   Price: " + Math.Round(Securities[symbol].Price, 2) + "   Quantity: " + s.Quantity);
            }
        }
예제 #8
0
        /// <summary>
        /// Sell this symbol
        /// </summary>
        /// <param name="symbol"></param>
        public void Sell(String symbol)
        {
            SecurityHolding s = Securities[symbol].Holdings;

            if (s.Quantity > 0 && macdDic[symbol] < 0m)
            {
                Liquidate(symbol);

                Debug("Selling: " + symbol + " at sell MACD: " + macdDic[symbol] + "   RSI: " + rsiDic[symbol]
                      + "   Price: " + Math.Round(Securities[symbol].Price, 2) + "   Profit from sale: " + s.LastTradeProfit);
            }
        }
예제 #9
0
        public override void Initialize()
        {
            SetStartDate(2019, 1, 1);
            SetEndDate(2019, 3, 1);

            var equity = AddEquity("SPY", Resolution.Hour);

            _spy      = equity.Symbol;
            _holdings = equity.Holdings;

            // Set the fill model
            equity.SetFillModel(new CustomPartialFillModel(this));
        }
예제 #10
0
 public override void OnOrderEvent(OrderEvent orderEvent)
 {
     if (orderEvent.Status == OrderStatus.Filled && orderEvent.FillQuantity < 0)
     {
         SecurityHolding s          = Securities [orderEvent.Symbol].Holdings;
         var             profit_pct = s.LastTradeProfit / Portfolio.TotalPortfolioValue;
         _tradeReturns.Add(profit_pct);
         if (_tradeReturns.Count > MAXRETURNS)
         {
             _tradeReturns.RemoveAt(0);
         }
     }
 }
예제 #11
0
 public LogReturnSignal(LogReturn logr_Fast,
                        LogReturn logr_Slow,
                        LeastSquaresMovingAverage logrFast,
                        LeastSquaresMovingAverage logrSlow,
                        TickConsolidator ticks,
                        SecurityHolding securityHolding)
 {
     _logr_Fast       = logr_Fast;
     _logr_Slow       = logr_Slow;
     _logrFast        = logrFast;
     _logrSlow        = logrSlow;
     _ticks           = ticks;
     _securityHolding = securityHolding;
 }
예제 #12
0
 public BollingerBandSignal(BollingerBands bb,
                            LeastSquaresMovingAverage lsmaUpperBand,
                            LeastSquaresMovingAverage lsmaMiddleBand,
                            LeastSquaresMovingAverage lsmaLowerBand,
                            AverageDirectionalIndex adx,
                            SecurityHolding securityHolding)
 {
     _bb              = bb;
     _lsmaUpperBand   = lsmaUpperBand;
     _lsmaMiddleBand  = lsmaMiddleBand;
     _lsmaLowerBand   = lsmaLowerBand;
     _adx             = adx;
     _securityHolding = securityHolding;
 }
예제 #13
0
        private SecurityHolding CreateHolding(Symbol symbol, int quantity)
        {
            if (symbol.SecurityType == SecurityType.Option)
            {
                _previousRight  = symbol.ID.OptionRight;
                _previousStrike = symbol.ID.StrikePrice;
            }

            var properties = SymbolProperties.GetDefault("USD");
            var cash       = new Cash("USD", 0m, 1m);
            var security   = new Security(symbol, null, cash, properties, null, null, new SecurityCache());
            var holding    = new SecurityHolding(security, new IdentityCurrencyConverter("USD"));

            holding.SetHoldings(2, quantity);
            return(holding);
        }
        /// <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(2009, 1, 1);  //Set Start Date
            SetEndDate(2015, 1, 1);    //Set End Date
            SetCash(100000);           //Set Strategy Cash
            // Find more symbols here: http://quantconnect.com/data
            var equity = AddEquity(_spy, Resolution.Minute);

            _holdings = equity.Holdings;
            _rc       = RC(_spy, 30, 2, Resolution.Daily);

            var stockPlot = new Chart("Trade Plot");

            stockPlot.AddSeries(new Series("Buy", SeriesType.Scatter, 0));
            stockPlot.AddSeries(new Series("Sell", SeriesType.Scatter, 0));
            stockPlot.AddSeries(new Series("UpperChannel", SeriesType.Line, 0));
            stockPlot.AddSeries(new Series("LowerChannel", SeriesType.Line, 0));
            stockPlot.AddSeries(new Series("Regression", SeriesType.Line, 0));
            AddChart(stockPlot);
        }
예제 #15
0
파일: Global.cs 프로젝트: tzaavi/Lean
        /// <summary>
        /// Create a simple JSON holdings from a Security holding class.
        /// </summary>
        /// <param name="holding">Holdings object we'll use to initialize the transport</param>
        public Holding(SecurityHolding holding)
            : this()
        {
            Symbol   = holding.Symbol.Value;
            Type     = holding.Type;
            Quantity = holding.Quantity;

            var rounding = 2;

            if (holding.Type == SecurityType.Forex)
            {
                rounding = 5;
                string basec, quotec;
                Forex.DecomposeCurrencyPair(holding.Symbol.Value, out basec, out quotec);
                CurrencySymbol = Forex.CurrencySymbols[quotec];
                ConversionRate = ((ForexHolding)holding).ConversionRate;
            }

            AveragePrice = Math.Round(holding.AveragePrice, rounding);
            MarketPrice  = Math.Round(holding.Price, rounding);
        }
        public void ClosePosition(OrderDirection direction)
        {
            var insightGenerator = new OrderBasedInsightGenerator();

            var holding =
                new SecurityHolding(_security, new IdentityCurrencyConverter(_security.QuoteCurrency.Symbol));

            holding.SetHoldings(1, direction == OrderDirection.Buy ? -1 : 1);

            var insight = insightGenerator.GenerateInsightFromFill(new OrderEvent(
                                                                       1,
                                                                       Symbols.SPY,
                                                                       new DateTime(2013, 1, 1),
                                                                       OrderStatus.Filled,
                                                                       direction,
                                                                       1,
                                                                       direction == OrderDirection.Buy ? 1 : -1,
                                                                       OrderFee.Zero
                                                                       ), holding);

            Assert.AreEqual(1, insight.Confidence);
            Assert.AreEqual(InsightDirection.Flat, insight.Direction);
        }
예제 #17
0
        /// <summary>
        /// Detect if this order will cross zero and needs to be split up.
        /// </summary>
        /// <param name="order">Order we're attempting to process</param>
        /// <param name="holding">Current holdings of this security</param>
        /// <returns>True when order will cross zero (e.g. long->short) and we need to split into two orders.</returns>
        private bool DetectZeroCrossing(Order order, SecurityHolding holding)
        {
            var holdings = holding.Quantity;

            //We're reducing position or flipping:
            if (holding.IsLong && order.Quantity < 0)
            {
                if ((holdings + order.Quantity) < 0)
                {
                    //We dont have enough holdings so will cross through zero:
                    return(true);
                }
            }
            else if (holding.IsShort && order.Quantity > 0)
            {
                if ((holdings + order.Quantity) > 0)
                {
                    //Crossed zero: need to split into 2 orders:
                    return(true);
                }
            }
            return(false);
        }
        public void ExistingInsightCloseTimeIsUpdated(OrderDirection direction)
        {
            var insightGenerator = new OrderBasedInsightGenerator();

            var holding = new SecurityHolding(_security,
                                              new IdentityCurrencyConverter(_security.QuoteCurrency.Symbol));

            var insight = insightGenerator.GenerateInsightFromFill(new OrderEvent(
                                                                       1,
                                                                       Symbols.SPY,
                                                                       new DateTime(2013, 1, 1),
                                                                       OrderStatus.Filled,
                                                                       direction,
                                                                       1,
                                                                       direction == OrderDirection.Buy ? 2 : -2,
                                                                       OrderFee.Zero
                                                                       ), holding);

            Assert.AreEqual(new DateTime(2013, 1, 1), insight.GeneratedTimeUtc);

            holding.SetHoldings(1, direction == OrderDirection.Buy ? 2 : -2);
            var insight2 = insightGenerator.GenerateInsightFromFill(new OrderEvent(
                                                                        1,
                                                                        Symbols.SPY,
                                                                        new DateTime(2015, 1, 1),
                                                                        OrderStatus.Filled,
                                                                        direction,
                                                                        1,
                                                                        direction == OrderDirection.Buy ? -1 : 1,
                                                                        OrderFee.Zero
                                                                        ), holding);

            Assert.AreEqual(insight2.GeneratedTimeUtc, insight.CloseTimeUtc);
            // period will not change
            Assert.AreEqual(Time.EndOfTimeTimeSpan, insight.Period);
        }
예제 #19
0
        public void ReturnsExpectedPortfolioTarget(
            TrailingStopRiskManagementModelTestParameters parameters)
        {
            var decimalPrices = System.Array.ConvertAll(parameters.Prices, x => (decimal)x);

            var security = new Mock <Security>(
                Symbols.AAPL,
                SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
                new Cash(Currencies.USD, 1000m, 1m),
                SymbolProperties.GetDefault(Currencies.USD),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null,
                new SecurityCache()
                );

            security.CallBase        = true;
            security.Object.FeeModel = new ConstantFeeModel(0);

            var holding = new SecurityHolding(security.Object, new IdentityCurrencyConverter(Currencies.USD));

            holding.SetHoldings(parameters.InitialPrice, parameters.Quantity);
            security.Object.Holdings = holding;

            var algorithm = new QCAlgorithm();

            algorithm.SetPandasConverter();
            algorithm.Securities.Add(Symbols.AAPL, security.Object);

            if (parameters.Language == Language.Python)
            {
                using (Py.GIL())
                {
                    const string name     = nameof(TrailingStopRiskManagementModel);
                    var          instance = Py.Import(name).GetAttr(name).Invoke(parameters.MaxDrawdownPercent.ToPython());
                    var          model    = new RiskManagementModelPythonWrapper(instance);
                    algorithm.SetRiskManagement(model);
                }
            }
            else
            {
                var model = new TrailingStopRiskManagementModel(parameters.MaxDrawdownPercent);
                algorithm.SetRiskManagement(model);
            }

            var quantity = parameters.Quantity;

            for (int i = 0; i < decimalPrices.Length; i++)
            {
                var price = decimalPrices[i];
                security.Object.SetMarketPrice(new Tick(DateTime.Now, security.Object.Symbol, price, price));
                security.Setup((m => m.Invested)).Returns(parameters.InvestedArray[i]);

                var targets         = algorithm.RiskManagement.ManageRisk(algorithm, null).ToList();
                var shouldLiquidate = parameters.ShouldLiquidateArray[i];

                if (shouldLiquidate)
                {
                    Assert.AreEqual(1, targets.Count);
                    Assert.AreEqual(Symbols.AAPL, targets[0].Symbol);
                    Assert.AreEqual(0, targets[0].Quantity);
                }
                else
                {
                    Assert.AreEqual(0, targets.Count);
                }

                if (shouldLiquidate || parameters.ChangePosition[i])
                {
                    // Go from long to short or viceversa
                    holding.SetHoldings(price, quantity = -quantity);
                }
            }
        }
예제 #20
0
        public SVMBaselineSignal(
            QuoteBarConsolidator dailyConsolidator,
            ExponentialMovingAverage dailyALMA,
            QuoteBarConsolidator shortTermConsolidator,
            ArnaudLegouxMovingAverage alma5,
            ArnaudLegouxMovingAverage alma8,
            ArnaudLegouxMovingAverage alma13,
            ArnaudLegouxMovingAverage alma21,
            ArnaudLegouxMovingAverage alma34,
            ArnaudLegouxMovingAverage alma55,
            ArnaudLegouxMovingAverage alma89,
            ArnaudLegouxMovingAverage alma144,
            SchaffTrendCycle schaffTrendCycle,
            AverageTrueRange atr,
            AverageDirectionalIndex adx,
            SecurityHolding securityHolding,
            Security security,
            SVMBaselineStrategy qcAlgorithm)
        {
            _dailyConsolidator = dailyConsolidator;
            _dailyALMA         = dailyALMA;
            _rollingDailyAlma  = HistoryTracker.Track(_dailyALMA);

            _shortTermConsolidator = shortTermConsolidator;
            _rollingConsolidator   = HistoryTracker.Track(_shortTermConsolidator);

            _schaffTrendCycle        = schaffTrendCycle;
            _rollingSchaffTrendCycle = HistoryTracker.Track(_schaffTrendCycle);

            _atr = atr;
            _adx = adx;

            _alma5   = alma5;
            _alma8   = alma8;
            _alma13  = alma13;
            _alma21  = alma21;
            _alma34  = alma34;
            _alma55  = alma55;
            _alma89  = alma89;
            _alma144 = alma144;

            _rollingAlma5   = HistoryTracker.Track(_alma5, 100);
            _rollingAlma8   = HistoryTracker.Track(_alma8, 100);
            _rollingAlma13  = HistoryTracker.Track(_alma13, 100);
            _rollingAlma21  = HistoryTracker.Track(_alma21, 100);
            _rollingAlma34  = HistoryTracker.Track(_alma34, 100);
            _rollingAlma55  = HistoryTracker.Track(_alma55, 100);
            _rollingAlma89  = HistoryTracker.Track(_alma89, 100);
            _rollingAlma144 = HistoryTracker.Track(_alma144, 100);

            _windows = new List <RollingWindow <IndicatorDataPoint> > {
                _rollingAlma5, _rollingAlma8, _rollingAlma13, _rollingAlma21, _rollingAlma34, _rollingAlma55, _rollingAlma89, _rollingAlma144
            };
            _windowCombinations = _windows.Combinations(3);

            _maCross = new MovingAverageCross(_rollingAlma8, _rollingAlma21, _rollingAlma144);

            _securityHolding       = securityHolding;
            _security              = security;
            _minimumPriceVariation = 10000m;

            _qcAlgorithm = qcAlgorithm;

            var eader = new string[] { "Time", "Signal" };

            Storage.CreateFile($"C:\\Users\\M\\Desktop\\{_security.Symbol.Value}_ALMA_Signal.csv", eader);

            if (_store)
            {
                var path   = @"C:\Users\M\Desktop\EURUSD.csv";
                var header = new string[] { "Time", "End Time", "Open", "High", "Low", "Close", "STC", "STC Previous", "EMA", "Slope", "Diff", "Prediction", "Signal" };
                File.WriteAllText(path, string.Join(";", header) + Environment.NewLine);

                var ohlcHeader = new string[] { "Time", "Open", "High", "Low", "Close" };
                Storage.CreateFile($"C:\\Users\\M\\Desktop\\{_security.Symbol.Value}_OHLC_1D.csv", ohlcHeader);
                Storage.CreateFile($"C:\\Users\\M\\Desktop\\{_security.Symbol.Value}_OHLC_15M.csv", ohlcHeader);
                //Storage.CreateFile($"C:\\Users\\M\\Desktop\\{_security.Symbol.Value}_OHLC_1M.csv", ohlcHeader);
            }

            shortTermConsolidator.DataConsolidated += (sender, args) =>
            {
                if (_previousBar == null)
                {
                    _previousBar = args;
                    return;
                }

                if (_dailyConsolidator.Consolidated == null)
                {
                    return;
                }

                /*var maSignals = _windowCombinations.Select((wc) =>
                 * {
                 *  var buySignal = wc[0].DoubleCrossAbove(wc[1], wc[2], 5, 0.05m / 10000m) && wc[0].Rising(3, 0.05m / 10000m) && wc[1].Rising(3, 0.05m / 10000m) && wc[2].Rising(3, 0.05m / 10000m);
                 *  var sellSignal = wc[0].DoubleCrossBelow(wc[1], wc[2], 5, 0.05m / 10000m) && wc[0].Falling(3, 0.05m / 10000m) && wc[1].Falling(3, 0.05m / 10000m) && wc[2].Falling(3, 0.05m / 10000m);
                 *  return buySignal ? SignalType.Long : sellSignal ? SignalType.Short : SignalType.NoSignal;
                 * });
                 *
                 * var longCondition = maSignals.Where((s) => s == SignalType.Long).Count() > 9 && args.Close > _alma144 + (10m / 10000m) && args.Close > _alma21 && args.Close > _alma8;
                 * var shortCondition = maSignals.Where((s) => s == SignalType.Short).Count() > 9 && args.Close < _alma144 - (10m / 10000m) && args.Close < _alma21 && args.Close < _alma8;
                 *
                 * var longExit = Signal == SignalType.Long
                 *              && (maSignals.Where((s) => s == SignalType.Short).Count() > 4);
                 * var shortExit = Signal == SignalType.Short
                 *              && (maSignals.Where((s) => s == SignalType.Long).Count() > 4);*/
                var dailyQuote = (QuoteBar)_dailyConsolidator.Consolidated;

                // If mean reverting and no slow cross within ?, close

                var longMeanReversion = _maCross.CrossAbove(6, 0.7m / 10000m) &&
                                        _rollingAlma8.InRangeExclusive(_alma21, _alma144) &&
                                        _adx >= 23
                                        //&& _atr > 7m / 10000m
                                        //&& _rollingAlma144.Diff(_rollingAlma21, 10).Average() * 10000m >= 15m
                                        && _rollingAlma8.Rising(1, 1m / 10000m) &&
                                        _rollingAlma21.Rising(1, 0.1m / 10000m)
                                        ? TradeType.Direction.MeanRevertingUp
                                        : TradeType.Direction.Flat;

                var longTrend = _maCross.DoubleCrossAbove(6, 0.4m / 10000m)
                                //&& _adx < 20
                                //&& _rollingAlma144.Diff(_rollingAlma21, 10).Sum() * 10000m > 5m
                                && _rollingAlma8.Rising(2, 1m / 10000m) &&
                                _rollingAlma21.Rising(2, 0.1m / 10000m) &&
                                _rollingAlma55.Rising(2) &&
                                args.Close > _alma144
                                ? TradeType.Direction.TrendUp
                                : TradeType.Direction.Flat;

                var longCondition = args.Close > _dailyALMA && (longMeanReversion == TradeType.Direction.MeanRevertingUp || longTrend == TradeType.Direction.TrendUp);

                var shortMeanReversion = _maCross.CrossBelow(6, 0.6m / 10000m) &&
                                         _rollingAlma8.InRangeExclusive(_alma144, _alma21) &&
                                         _adx >= 23
                                         //&& _atr > 7m / 10000m
                                         //&& _rollingAlma21.Diff(_rollingAlma144, 10).Average() * 10000m >= 15m
                                         && _rollingAlma8.Falling(1, 1m / 10000m) &&
                                         _rollingAlma21.Falling(1, 0.1m / 10000m)
                                            ? TradeType.Direction.MeanRevertingDown
                                            : TradeType.Direction.Flat;

                var shortTrend = _maCross.DoubleCrossBelow(6, 0.4m / 10000m)
                                 //&& _adx < 20
                                 //&& _rollingAlma21.Diff(_rollingAlma144, 10).Sum() * 10000m > 5m
                                 && _rollingAlma8.Falling(2, 1m / 10000m) &&
                                 _rollingAlma21.Falling(2, 0.1m / 10000m) &&
                                 _rollingAlma55.Falling(2) &&
                                 args.Close < _alma144
                                    ? TradeType.Direction.TrendDown
                                    : TradeType.Direction.Flat;

                var shortCondition = args.Close < _dailyALMA && (shortMeanReversion == TradeType.Direction.MeanRevertingDown || shortTrend == TradeType.Direction.TrendDown);

                var longExit = Signal == SignalType.Long &&
                               ((shortTrend == TradeType.Direction.TrendDown ||
                                 _rollingAlma34.CrossBelow(_rollingAlma144, 7, 0.1m / 10000m)) ||
                                (_lastTradeType == TradeType.Direction.MeanRevertingUp &&
                                 args.Time.Subtract(_triggerBar.Time).CompareTo(TimeSpan.FromMinutes(15 * 6)) > 0 &&
                                 _maCross.CrossBelow(6, 0.3m / 10000m) &&
                                 _alma144 > _alma21));
                //var longExit = Signal == SignalType.Long && (_rollingAlma21.CrossBelow(_rollingAlma144, 7, 0.1m / 10000m)); NZDUSD
                //_rollingConsolidator.Diff(_rollingAlma144, Field.Close, 8).All((d) => d < 5m)

                /*&& (((_rollingAlma8.CrossBelow(_rollingAlma21, 5, 0.1m / 10000m) && _rollingAlma21.Falling())
                || (_rollingConsolidator.CrossBelow(_alma144.Current.Value) && _rollingAlma21.Falling())));*/
                var shortExit = Signal == SignalType.Short &&
                                ((longTrend == TradeType.Direction.TrendUp ||
                                  _rollingAlma34.CrossAbove(_rollingAlma144, 7, 0.1m / 10000m)) ||
                                 (_lastTradeType == TradeType.Direction.MeanRevertingDown &&
                                  args.Time.Subtract(_triggerBar.Time).CompareTo(TimeSpan.FromMinutes(15 * 6)) > 0 &&
                                  _maCross.CrossAbove(6, 0.3m / 10000m) &&
                                  _alma144 < _alma21));
                //var shortExit = Signal == SignalType.Short && ( _rollingAlma21.CrossAbove(_rollingAlma144, 7, 0.1m / 10000m)); NZDUSD
                //_rollingConsolidator.Diff(_rollingAlma144, Field.Close, 8).All((d) => d > 5m)

                /*&& (((_rollingAlma8.CrossAbove(_rollingAlma21, 5, 0.1m / 10000m) && _rollingAlma21.Rising())
                || (_rollingConsolidator.CrossAbove(_alma144.Current.Value) && _rollingAlma21.Rising())));*/

                if (!_securityHolding.Invested && longCondition && !shortCondition && (_triggerBar == null || args.Time.Subtract(_triggerBar.Time).CompareTo(TimeSpan.FromMinutes(15 * 6)) > 0))
                {
                    Signal         = Signal != SignalType.PendingLong ? SignalType.Long : SignalType.Long;
                    _triggerBar    = args;
                    _maEntry       = _windows.Select((w) => w[0]);
                    _lastTradeType = longTrend != TradeType.Direction.Flat ? longTrend : longMeanReversion;
                }
                else if (!_securityHolding.Invested && shortCondition && !longCondition && (_triggerBar == null || args.Time.Subtract(_triggerBar.Time).CompareTo(TimeSpan.FromMinutes(15 * 6)) > 0))
                {
                    Signal         = Signal != SignalType.PendingShort ? SignalType.Short : SignalType.Short;
                    _triggerBar    = args;
                    _maEntry       = _windows.Select((w) => w[0]);
                    _lastTradeType = shortTrend != TradeType.Direction.Flat ? shortTrend : shortMeanReversion;
                }
                else if ((_securityHolding.Invested && longExit) || (_securityHolding.Invested && shortExit))
                {
                    Signal          = (Signal == SignalType.Long && shortCondition) || (Signal == SignalType.Short && longCondition) ? SignalType.Reverse : SignalType.Exit;
                    _pendingSignal  = Signal == SignalType.Reverse && shortCondition ? SignalType.Short : Signal == SignalType.Reverse && longCondition ? SignalType.Long : SignalType.NoSignal;
                    _waitingForScan = true;
                    _triggerBar     = args;
                    _maEntry        = _windows.Select((w) => w[0]);
                    _lastTradeType  = _pendingSignal == SignalType.Long
                                        ? longTrend != TradeType.Direction.Flat ? longTrend : longMeanReversion
                                        : shortTrend != TradeType.Direction.Flat ? shortTrend : shortMeanReversion;
                }
                else if (!_securityHolding.Invested)
                {
                    Signal = SignalType.NoSignal;
                    //_triggerBar = null;
                    _maEntry = null;
                }

                _previousBar = args;

                //_qcAlgorithm.PlotSignal(args, _rollingEMA[0], _rollingEmaSlope[0], _rollingSchaffTrendCycle[0], _rollingStoch[0], (int)shortTermTrend, (int) Signal);

                if (_store)
                {
                    /*var line = new object[] { Storage.ToUTCTimestamp(args.Time), Storage.ToUTCTimestamp(args.EndTime), args.Open, args.High, args.Low, args.Close, _rollingSchaffTrendCycle[0].Value, _rollingSchaffTrendCycle[1].Value,
                     *                      _rollingEMA[0].Value, _rollingEmaSlope[0].Value, (args.Close - _rollingEMA[0]) * _minimumPriceVariation, (int)shortTermTrend, (int) Signal };
                     * Storage.AppendToFile($"C:\\Users\\M\\Desktop\\{_security.Symbol.Value}.csv", line);
                     *
                     * var ohlcLine = new object[] { Storage.ToUTCTimestamp(args.Time), args.Open, args.High, args.Low, args.Close };
                     * Storage.AppendToFile($"C:\\Users\\M\\Desktop\\{_security.Symbol.Value}_OHLC_15M.csv", ohlcLine);*/
                }
            };
        }
예제 #21
0
 // TODO: Stop loss based on EMA
 // TODO: Adaptable parameters according to price
 public WFSignal(WilliamsFractals wf, SecurityHolding securityHolding)
 {
     _wf = wf;
     _securityHolding = securityHolding;
 }
        /// <summary>
        /// Generates a new insight for a given <see cref="OrderEvent"/>.
        /// </summary>
        /// <param name="orderEvent">The <see cref="OrderEvent"/> to create a new
        /// <see cref="Insight"/> from</param>
        /// <param name="securityHolding">The <see cref="SecurityHolding"/> of the
        /// related <see cref="OrderEvent.Symbol"/></param>
        /// <returns></returns>
        public Insight GenerateInsightFromFill(OrderEvent orderEvent,
                                               SecurityHolding securityHolding)
        {
            var desiredFinalQuantity = orderEvent.FillQuantity + securityHolding.Quantity;

            Insight existingInsight;

            _insights.TryGetValue(orderEvent.Symbol, out existingInsight);

            double?confidence;

            if (// new position
                securityHolding.Quantity == 0
                // closing the entire position
                || desiredFinalQuantity == 0
                // changing market sides
                || Math.Sign(desiredFinalQuantity) != Math.Sign(securityHolding.Quantity)
                // increasing the position
                || Math.Sign(orderEvent.FillQuantity) == Math.Sign(securityHolding.Quantity))
            {
                confidence = 1;
            }
            else
            {
                // we are reducing the position, so set the confidence based on the original position
                confidence = (double)(securityHolding.AbsoluteQuantity - orderEvent.AbsoluteFillQuantity)
                             / (double)securityHolding.AbsoluteQuantity;

                if (existingInsight != null)
                {
                    // we have to adjust new confidence based on previous
                    confidence = confidence * existingInsight.Confidence;
                }
            }

            var insightDirection = desiredFinalQuantity > 0
                ? InsightDirection.Up : desiredFinalQuantity == 0
                    ? InsightDirection.Flat : InsightDirection.Down;

            var insight = Insight.Price(orderEvent.Symbol,
                                        Time.EndOfTime,
                                        insightDirection,
                                        null,
                                        confidence,
                                        AutoGeneratedSourceModel);

            insight.GeneratedTimeUtc = orderEvent.UtcTime;

            // When a new insight is generated, will update the <see cref="Insight.CloseTimeUtc"/>
            // of the previous insight for the same <see cref="Symbol"/>.
            if (existingInsight != null)
            {
                // close the previous insight
                existingInsight.CloseTimeUtc = insight.GeneratedTimeUtc;
                _insights.Remove(insight.Symbol);
            }
            _insights.Add(insight.Symbol, insight);

            insight.SetPeriodAndCloseTime(null);

            return(insight);
        }
예제 #23
0
 public VwapSignal(VolumeWeightedAveragePriceIndicator vwap, SecurityHolding securityHolding)
 {
     _vwap            = vwap;
     _securityHolding = securityHolding;
 }
예제 #24
0
 public RsiSignal(RelativeStrengthIndex rsi, SecurityHolding securityHolding)
 {
     _rsi             = rsi;
     _securityHolding = securityHolding;
 }
예제 #25
0
 public CCISignal(CommodityChannelIndex cci, SecurityHolding securityHolding)
 {
     _cci             = cci;
     _securityHolding = securityHolding;
 }
예제 #26
0
        public SVMBaselineSignalWIP(
            QuoteBarConsolidator consolidator,
            Stochastic stoch,
            ExponentialMovingAverage stochMA,
            RollingWindow <IndicatorDataPoint> rollingStochMA,
            LeastSquaresMovingAverage stochEmaLSMA,
            RollingWindow <IndicatorDataPoint> rollingStochEmaSlope,
            ExponentialMovingAverage ema,
            LeastSquaresMovingAverage emaMA,
            RollingWindow <IndicatorDataPoint> rollingEmaSlope,
            ExponentialMovingAverage shortTermMA,
            LeastSquaresMovingAverage dailyEmaLSMA,
            RollingWindow <IndicatorDataPoint> rollingDailyEmaSlope,
            SecurityHolding securityHolding,
            Security security,
            SVMBaselineStrategyWIP qcAlgorithm)
        {
            _consolidator         = consolidator;
            _stoch                = stoch;
            _stochMA              = stochMA;
            _rollingStochMA       = rollingStochMA;
            _stochEmaLSMA         = stochEmaLSMA;
            _rollingStochEmaSlope = rollingStochEmaSlope;
            _ema                  = ema;
            _emaMA                = emaMA;
            _rollingEmaSlope      = rollingEmaSlope;
            _shortTermMA          = shortTermMA;
            _dailyEmaLSMA         = dailyEmaLSMA;
            _rollingDailyEmaSlope = rollingDailyEmaSlope;

            _securityHolding       = securityHolding;
            _security              = security;
            _minimumPriceVariation = (1m / _security.SymbolProperties.MinimumPriceVariation) / 10m;
            _qcAlgorithm           = qcAlgorithm;

            _stochMA.Updated += (sender, args) =>
            {
                try
                {
                    var currentQuote = (QuoteBar)_consolidator.Consolidated;

                    var aboveEma = currentQuote.Close - _ema.Current.Value > 4m / _minimumPriceVariation;
                    var belowEma = _ema.Current.Value - currentQuote.Close > 4m / _minimumPriceVariation;

                    var aboveEmaExit = (currentQuote.Close - _ema.Current.Value > 10m / _minimumPriceVariation) || _rollingDailyEmaSlope[0] > 0.0005m;
                    var belowEmaExit = (_ema.Current.Value - currentQuote.Close > 10m / _minimumPriceVariation) || _rollingDailyEmaSlope[0] < -0.0005m;

                    var longCondition = _rollingStochMA[0] > _rollingStochMA[1] &&
                                        _stochMA > 55 &&
                                        aboveEma &&
                                        //_rollingDailyEmaSlope[0] > _rollingDailyEmaSlope[1] &&
                                        _dailyEmaLSMA.Slope > 0 &&
                                        //_rollingStochEmaSlope[0] < 2 &&
                                        //_rollingStochEmaSlope[0] > _rollingStochEmaSlope[1] &&
                                        //_rollingStochMA[0] > 45 &&
                                        _rollingEmaSlope[0] > 0.00001m;
                    var shortCondition = _rollingStochMA[0] < _rollingStochMA[1] &&
                                         _stochMA < 45 &&
                                         belowEma &&
                                         //_rollingDailyEmaSlope[0] < _rollingDailyEmaSlope[1] &&
                                         _dailyEmaLSMA.Slope < 0 &&
                                         //_rollingStochEmaSlope[0] > -2 &&
                                         //_rollingStochEmaSlope[0] < _rollingStochEmaSlope[1] &&
                                         //_rollingStochMA[0] < 55 &&
                                         _rollingEmaSlope[0] < -0.00001m;

                    var prediction = longCondition ? 1 : shortCondition ? -1 : 0;

                    /*var prediction = _rollingStochMA[0] > _rollingStochMA[1] && aboveEma && _stochEmaLSMA.Slope > 0.5 && _rollingEmaSlope[0] > 0
                     *  ? 1
                     *  : _rollingStochMA[0] < _rollingStochMA[1] && belowEma && _stochEmaLSMA.Slope < -0.5 && _rollingEmaSlope[0] < 0
                     *      ? -1
                     *      : 0;*/
                    var probability   = 1d;
                    var logLikelihood = 1d;

                    _qcAlgorithm.PlotSignal((QuoteBar)_consolidator.Consolidated, prediction, logLikelihood);

                    var longExit  = Signal == SignalType.Long && belowEmaExit && _rollingEmaSlope[0] < 0;
                    var shortExit = Signal == SignalType.Short && aboveEmaExit && _rollingEmaSlope[0] > 0;

                    /*var longExit = Signal == SignalType.Long && _stochEmaLSMA.Slope < -0.5;
                     * var shortExit = Signal == SignalType.Short && _stochEmaLSMA.Slope > 0.5;*/

                    if (!_securityHolding.Invested && prediction == 1)
                    {
                        if (true)//if (!_shortOnly.Contains(_securityHolding.Symbol))
                        {
                            Signal = Signal != SignalType.PendingLong ? SignalType.Long : SignalType.Long;
                        }
                        else
                        {
                            Signal = SignalType.NoSignal;
                        }
                        //Signal = Signal != SignalType.PendingLong ? SignalType.Long : SignalType.Long;
                        //Signal = SignalType.NoSignal;

                        if (_debug)
                        {
                            Console.WriteLine("Long Signal: {0} Probability: {1} Log Likelihood: {2}", Signal, probability, logLikelihood);
                            Console.WriteLine("Long STO: {0} STO MA: {1}", _stoch.Current.Value, args.Value);
                            Console.WriteLine("Long Time: {0} Price: {1}", _consolidator.Consolidated.Time, _consolidator.Consolidated.Value);
                        }
                    }
                    else if (!_securityHolding.Invested && prediction == -1)
                    {
                        if (true) //if (_shortable.Contains(_securityHolding.Symbol))
                        {
                            Signal = Signal != SignalType.PendingShort ? SignalType.Short : SignalType.Short;
                        }
                        else
                        {
                            Signal = SignalType.NoSignal;
                        }
                        //Signal = Signal != SignalType.PendingShort ? SignalType.Short : SignalType.Short;
                        //Signal = SignalType.NoSignal;

                        if (_debug)
                        {
                            Console.WriteLine("Short Signal: {0} Probability: {1} Log Likelihood: {2}", Signal, probability, logLikelihood);
                            Console.WriteLine("Short STO: {0} STO MA: {1}", _stoch.Current.Value, args.Value);
                            Console.WriteLine("Short Time: {0} Price: {1}", _consolidator.Consolidated.Time, _consolidator.Consolidated.Value);
                        }
                    }
                    else if ((_securityHolding.Invested && longExit) || (_securityHolding.Invested && shortExit))
                    {
                        if (_debug)
                        {
                            Console.WriteLine("Exit Signal: {0} Probability: {1} Log Likelihood: {2}", Signal, probability, logLikelihood);
                            Console.WriteLine("Exit STO: {0} STO MA: {1}", _stoch.Current.Value, args.Value);
                            Console.WriteLine("Exit Time: {0} Price: {1}", _consolidator.Consolidated.Time, _consolidator.Consolidated.Value);
                        }

                        Signal = SignalType.Exit;
                    }
                    else if (!_securityHolding.Invested && (Signal == SignalType.PendingLong || Signal == SignalType.PendingShort))
                    {
                        Signal = SignalType.NoSignal;
                    }
                    else
                    {
                        //Signal = SignalType.NoSignal;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Signal = SignalType.NoSignal;
                }
            };
        }
예제 #27
0
파일: SVMSignal.cs 프로젝트: godtopus/Lean
        public SVMSignal(QuoteBarConsolidator consolidator, Stochastic stoch, HullMovingAverage stochMA, RollingWindow <double> rolling, ExponentialMovingAverage ema, SecurityHolding securityHolding, SVMStrategy qcAlgorithm)
        {
            _consolidator    = consolidator;
            _stoch           = stoch;
            _StochMA         = stochMA;
            _rolling         = rolling;
            _ema             = ema;
            _securityHolding = securityHolding;
            _qcAlgorithm     = qcAlgorithm;

            stochMA.Updated += (sender, args) =>
            {
                try
                {
                    var filtered = _rolling.TakeWhile((s) => args.Value > 50 ? s > 50 : args.Value < 50 ? s < 50 : false);

                    var currentQuote = (QuoteBar)_consolidator.Consolidated;

                    //Console.WriteLine("{0}, {1}, {2}", filtered.Count(), _rolling.Count(), _stoch.Current.Value);
                    var inputs = new double[] { filtered.Average(), filtered.Count(), (double)(currentQuote.Close / _ema.Current.Value) };
                    _inputs.Add(inputs);
                    inputs = Accord.Statistics.Tools.ZScores(_inputs.ToArray()).Last();
                    _inputs.RemoveAt(_inputs.Count - 1);

                    if (_pcaTransform)
                    {
                        inputs = _pca.Transform(inputs);
                    }

                    var prediction    = _svm.Decide(inputs);
                    var probability   = _svm.Probability(inputs);
                    var logLikelihood = _svm.LogLikelihood(inputs);

                    _qcAlgorithm.PlotSignal((QuoteBar)_consolidator.Consolidated, prediction == 0 ? -1 : prediction, logLikelihood);

                    /*var dbnPredictions = _dbn.Compute(inputs);
                     * var shortPrediction = dbnPredictions.First();
                     * var longPrediction = dbnPredictions.Last();*/

                    if (_securityHolding.Invested && Signal == SignalType.Long && prediction == 0)
                    {
                        //Console.WriteLine("Long Exit Time: {0} Prediction: {1} Probability: {2}", args.EndTime, prediction, probability);
                    }
                    else if (_securityHolding.Invested && Signal == SignalType.Short && prediction == 1)
                    {
                        //Console.WriteLine("Short Exit Time: {0} Prediction: {1} Probability: {2}", args.EndTime, prediction, probability);
                    }

                    if (prediction != 2)
                    {
                        //Console.WriteLine("Time: {0} Prediction: {1} Probability: {2}, Log Likelihood: {3} Score: {4}", args.EndTime, prediction, probability, logLikelihood);
                    }

                    // EURUSD 0.9999
                    var probabilityFilter = logLikelihood >= 9;//probability >= 0.999999;// && _previousPredictions.IsReady && _previousPredictions.All((p) => p == prediction);

                    var aboveEma = currentQuote.Close > _ema.Current.Value;
                    var belowEma = currentQuote.Close < _ema.Current.Value;

                    var longExit  = Signal == SignalType.Long && belowEma;  //prediction == 0;
                    var shortExit = Signal == SignalType.Short && aboveEma; //prediction == 1;

                    if (!_securityHolding.Invested && probabilityFilter && prediction == 1 && _rolling[0] > rolling[1] && aboveEma)
                    {
                        Signal = Signal != SignalType.PendingLong ? SignalType.PendingLong : SignalType.Long;

                        if (_debug)
                        {
                            Console.WriteLine("Long Signal: {0} Probability: {1} Log Likelihood: {2}", Signal, probability, logLikelihood);
                            Console.WriteLine("Long STO: {0} STO MA: {1} Count: {2}", _stoch.Current.Value, args.Value, filtered.Count());
                            Console.WriteLine("Long Time: {0} Price: {1}", _consolidator.Consolidated.Time, _consolidator.Consolidated.Value);
                        }
                    }
                    else if (!_securityHolding.Invested && probabilityFilter && prediction == 0 && _rolling[0] < rolling[1] && belowEma)
                    {
                        Signal = Signal != SignalType.PendingShort ? SignalType.PendingShort : SignalType.Short;

                        if (_debug)
                        {
                            Console.WriteLine("Short Signal: {0} Probability: {1} Log Likelihood: {2}", Signal, probability, logLikelihood);
                            Console.WriteLine("Short STO: {0} STO MA: {1} Count: {2}", _stoch.Current.Value, args.Value, filtered.Count());
                            Console.WriteLine("Short Time: {0} Price: {1}", _consolidator.Consolidated.Time, _consolidator.Consolidated.Value);
                        }
                    }
                    else if ((_securityHolding.Invested && longExit) || (_securityHolding.Invested && shortExit))
                    {
                        if (_debug)
                        {
                            Console.WriteLine("Exit Signal: {0} Probability: {1} Log Likelihood: {2}", Signal, probability, logLikelihood);
                            Console.WriteLine("Exit STO: {0} STO MA: {1} Count: {2}", _stoch.Current.Value, args.Value, filtered.Count());
                            Console.WriteLine("Exit Time: {0} Price: {1}", _consolidator.Consolidated.Time, _consolidator.Consolidated.Value);
                        }

                        Signal = SignalType.Exit;
                    }
                    else if (!_securityHolding.Invested && (Signal == SignalType.PendingLong || Signal == SignalType.PendingShort))
                    {
                        Signal = SignalType.NoSignal;
                    }
                    else
                    {
                        //Signal = SignalType.NoSignal;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Signal = SignalType.NoSignal;
                }
            };
        }