Ejemplo n.º 1
0
 /// <summary>
 /// Resets this indicator to its initial state
 /// </summary>
 public override void Reset()
 {
     base.Reset();
     MiddleBand.Reset();
     LowerBand.Reset();
     UpperBand.Reset();
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {
            Dexp.Set(dexp[0]);
            var devs = dexp.StdDev * stdDevs;

            LowerBand.Set(Dexp[0] - devs);
            UpperBand.Set(Dexp[0] + devs);
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Resets this indicator to its initial state
 /// </summary>
 public override void Reset()
 {
     AverageTrueRange.Reset();
     MiddleBand.Reset();
     UpperBand.Reset();
     LowerBand.Reset();
     base.Reset();
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Computes the next value of the following sub-indicators from the given state:
 /// StandardDeviation, MiddleBand, UpperBand, LowerBand
 /// </summary>
 /// <param name="input">The input given to the indicator</param>
 /// <returns>The input is returned unmodified.</returns>
 protected override decimal ComputeNextValue(IndicatorDataPoint input)
 {
     StandardDeviation.Update(input);
     MiddleBand.Update(input);
     UpperBand.Update(input);
     LowerBand.Update(input);
     return(input);
 }
Ejemplo n.º 5
0
 /// <summary>
 /// Resets this indicator and all sub-indicators (StandardDeviation, LowerBand, MiddleBand, UpperBand)
 /// </summary>
 public override void Reset()
 {
     StandardDeviation.Reset();
     MiddleBand.Reset();
     UpperBand.Reset();
     LowerBand.Reset();
     base.Reset();
 }
Ejemplo n.º 6
0
 /// <summary>
 ///      Resets this indicator to its initial state
 /// </summary>
 public override void Reset()
 {
     UpperBand.Reset();
     LowerBand.Reset();
     _previousInput = null;
     _previousTime  = 0;
     base.Reset();
 }
Ejemplo n.º 7
0
 /// <summary>
 /// Resets this indicator and all sub-indicators (StandardDeviation, LowerBand, MiddleBand, UpperBand, BandWidth, %B)
 /// </summary>
 public override void Reset()
 {
     StandardDeviation.Reset();
     MiddleBand.Reset();
     UpperBand.Reset();
     LowerBand.Reset();
     BandWidth.Reset();
     PercentB.Reset();
     base.Reset();
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Computes the next value of this indicator from the given state
        /// </summary>
        /// <param name="input">The input given to the indicator</param>
        /// <returns>
        /// A new value for this indicator
        /// </returns>
        protected override decimal ComputeNextValue(IBaseDataBar input)
        {
            var coeff = _width * (input.High - input.Low) / (input.High + input.Low);

            LowerBand.Update(input.Time, input.Low * (1 - coeff));
            UpperBand.Update(input.Time, input.High * (1 + coeff));
            MiddleBand.Update(input.Time, input.Close);

            return(MiddleBand);
        }
Ejemplo n.º 9
0
        /// <summary>
        ///      Computes the next value of this indicator from the given state
        /// </summary>
        /// <param name="time"></param>
        /// <param name="input">The input given to the indicator</param>
        /// <returns>
        ///      A new value for this indicator
        /// </returns>
        protected override DoubleArray Forward(long time, DoubleArray input)
        {
            var coeff = _width * (input[HighIdx] - input[LowIdx]) / (input[HighIdx] + input[LowIdx]);

            LowerBand.Update(time, input[LowIdx] * (1 - coeff));
            UpperBand.Update(time, input[HighIdx] * (1 + coeff));
            MiddleBand.Update(time, input[CloseIdx]);

            return(MiddleBand);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Computes the next value of this indicator from the given state
        /// </summary>
        /// <param name="input">The input given to the indicator</param>
        /// <returns>A new value for this indicator, which by convention is the mean value of the upper band and lower band.</returns>
        protected override decimal ComputeNextValue(IBaseDataBar input)
        {
            if (_previousInput != null)
            {
                UpperBand.Update(_previousInput.Time, _previousInput.High);
                LowerBand.Update(_previousInput.Time, _previousInput.Low);
            }

            _previousInput = input;
            return((UpperBand + LowerBand) / 2);
        }
        /// <summary>
        /// Computes the next value of this indicator from the given state
        /// </summary>
        /// <param name="input">The input given to the indicator</param>
        /// <returns>A new value for this indicator, which by convention is the mean value of the upper band and lower band.</returns>
        protected override decimal ComputeNextValue(IBaseDataBar input)
        {
            if (_previousInput != null)
            {
                UpperBand.Update(new IndicatorDataPoint(_previousInput.Time, _previousInput.High));
                LowerBand.Update(new IndicatorDataPoint(_previousInput.Time, _previousInput.Low));
            }

            _previousInput = input;
            return((UpperBand.Current.Value + LowerBand.Current.Value) / 2);
        }
Ejemplo n.º 12
0
        /// <summary>
        ///      Computes the next value of this indicator from the given state
        /// </summary>
        /// <param name="time"></param>
        /// <param name="input">The input given to the indicator</param>
        /// <returns>A new value for this indicator, which by convention is the mean value of the upper band and lower band.</returns>
        protected override DoubleArray Forward(long time, DoubleArray input)
        {
            if (_previousInput != null)
            {
                UpperBand.Update(_previousTime, _previousInput.High);
                LowerBand.Update(_previousTime, _previousInput.Low);
            }

            _previousInput = input.Clone();
            _previousTime  = time;
            return((UpperBand + LowerBand) / 2);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Computes the next value for this indicator from the given state.
        /// </summary>
        /// <param name="input">The TradeBar to this indicator on this time step</param>
        /// <returns>A new value for this indicator</returns>
        protected override decimal ComputeNextValue(IBaseDataBar input)
        {
            AverageTrueRange.Update(input);

            var typicalPrice = (input.High + input.Low + input.Close) / 3m;

            MiddleBand.Update(input.Time, typicalPrice);

            // poke the upper/lower bands, they actually don't use the input, they compute
            // based on the ATR and the middle band
            LowerBand.Update(input);
            UpperBand.Update(input);
            return(MiddleBand);
        }
Ejemplo n.º 14
0
        public void Update(Prices prices)
        {
            var closes = prices[Price.Close];

            if (closes.Count >= Period)
            {
                int start      = closes.Count - Period;
                var lastCloses = closes.GetRange(start, Period);
                var avg        = lastCloses.Average();
                var meanChange = closes.Last() * MEAN_CHANGE;
                UpperBand.Add(avg + meanChange);
                LowerBand.Add(avg - meanChange);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        ///      Computes the next value for this indicator from the given state.
        /// </summary>
        /// <param name="time"></param>
        /// <param name="input">The TradeBar to this indicator on this time step</param>
        /// <returns>A new value for this indicator</returns>
        protected override DoubleArray Forward(long time, DoubleArray input)
        {
            AverageTrueRange.Update(time, input);

            var typicalPrice = (input[HighIdx] + input[LowIdx] + input[CloseIdx]) / 3d;

            MiddleBand.Update(time, typicalPrice);

            // poke the upper/lower bands, they actually don't use the input, they compute
            // based on the ATR and the middle band
            LowerBand.Update(time, input);
            UpperBand.Update(time, input);
            return(MiddleBand);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Computes the next value for this indicator from the given state.
        /// </summary>
        /// <param name="input">The TradeBar to this indicator on this time step</param>
        /// <returns>A new value for this indicator</returns>
        protected override decimal ComputeNextValue(TradeBar input)
        {
            AverageTrueRange.Update(input);

            var typicalPrice = (input.High + input.Low + input.Close) / 3m;

            MiddleBand.Update(input.Time, typicalPrice);
            Console.WriteLine(input.Time.ToString("yyyymmdd") + "\t" + typicalPrice.SmartRounding() + "\t" + MiddleBand.Current.Value.SmartRounding());
            // poke the upper/lower bands, they actually don't use the input, they compute
            // based on the ATR and the middle band
            LowerBand.Update(input);
            UpperBand.Update(input);
            return(MiddleBand);
        }
Ejemplo n.º 17
0
        public void Update(Prices prices)
        {
            var closes = prices[Price.Close];

            if (closes.Count >= Period)
            {
                int start      = closes.Count - Period;
                var lastCloses = closes.GetRange(start, Period);
                var avg        = lastCloses.Average();
                var variance   = lastCloses.Sum(p => p * p) / Period - avg * avg;
                var stdev      = Math.Sqrt(variance);
                UpperBand.Add(avg + Width * stdev);
                LowerBand.Add(avg - Width * stdev);
            }
        }
Ejemplo n.º 18
0
 protected override void OnBarUpdate()
 {
     #region Indicator formula
     PriceSeries.Set((High[0] + Low[0] + Close[0]) / 3);
     JMA.Set(JurikJMA(PriceSeries, 7, -25)[0]);
     TR = High[0] - Low[0];
     if (CurrentBar > 0)
     {
         TR = Math.Max(TR, Math.Max(High[0] - Close[1], Close[1] - Low[0]));
     }
     trueRange.Set(TR);
     bandSize = Band_width * SMA(trueRange, 200)[Math.Min(CurrentBar, Band_delay)];
     DWMA     = WMA(WMA(PriceSeries, Band_len), Band_len)[Math.Min(CurrentBar, Band_delay)];
     UpperBand.Set(DWMA + bandSize);
     LowerBand.Set(DWMA - bandSize);
     #endregion
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Initializes a new instance of the BollingerBands class
        /// </summary>
        /// <param name="name">The name of this indicator</param>
        /// <param name="period">The period of the standard deviation and moving average (middle band)</param>
        /// <param name="k">The number of standard deviations specifying the distance between the middle band and upper or lower bands</param>
        /// <param name="movingAverageType">The type of moving average to be used</param>
        public BollingerBands(string name, int period, decimal k, MovingAverageType movingAverageType = MovingAverageType.Simple)
            : base(name)
        {
            WarmUpPeriod      = period;
            MovingAverageType = movingAverageType;
            StandardDeviation = new StandardDeviation(name + "_StandardDeviation", period);
            MiddleBand        = movingAverageType.AsIndicator(name + "_MiddleBand", period);
            LowerBand         = MiddleBand.Minus(StandardDeviation.Times(k), name + "_LowerBand");
            UpperBand         = MiddleBand.Plus(StandardDeviation.Times(k), name + "_UpperBand");

            var UpperMinusLower = UpperBand.Minus(LowerBand);

            BandWidth = UpperMinusLower
                        .Over(MiddleBand)
                        .Times(new ConstantIndicator <IndicatorDataPoint>("ct", 100m), name + "_BandWidth");

            Price    = new Identity(name + "_Close");
            PercentB = IndicatorExtensions.Over(
                Price.Minus(LowerBand),
                UpperMinusLower,
                name + "_%B");
        }
Ejemplo n.º 20
0
        public void Update(Prices prices)
        {
            var closes = prices[Price.Close];

            if (closes.Count >= Period + 1)
            {
                int start      = closes.Count - Period - 1;
                var lastLows   = prices[Price.Low].GetRange(start, Period + 1);
                var lastHighs  = prices[Price.High].GetRange(start, Period + 1);
                var lastCloses = closes.GetRange(start, Period + 1);
                var avg        = lastCloses.Skip(1).Average();
                var ranges     = new List <double>();
                for (int i = 0; i < lastCloses.Count; i++)
                {
                    var lowRange  = Math.Abs(lastCloses[i] - lastLows[i]);
                    var highRange = Math.Abs(lastCloses[i] - lastHighs[i]);
                    var range     = Math.Max(lowRange, highRange);
                    ranges.Add(range);
                }
                var atr = ranges.Average();
                UpperBand.Add(avg + Width * atr);
                LowerBand.Add(avg - Width * atr);
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        ///     Computes the next value of this indicator from the given state
        /// </summary>
        /// <param name="input">The input given to the indicator</param>
        /// <returns>
        ///     A new value for this indicator
        /// </returns>
        protected override decimal ComputeNextValue(IBaseDataBar input)
        {
            MiddleBand.Update(new IndicatorDataPoint
            {
                Time  = input.Time,
                Value = input.Close
            });

            var coeff = _width * (input.High - input.Low) / (input.High + input.Low);

            LowerBand.Update(new IndicatorDataPoint
            {
                Time  = input.Time,
                Value = input.Low * (1 - coeff)
            });

            UpperBand.Update(new IndicatorDataPoint
            {
                Time  = input.Time,
                Value = input.High * (1 + coeff)
            });

            return(MiddleBand);
        }
Ejemplo n.º 22
0
        public SimulationResult Simulate(DateTime start, DateTime end, int interval, StrategyParameters parameters)
        {
            //Read the OHLC from database
            var connectionName   = ConfigurationManager.AppSettings["ConnectionName"];
            var connectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;

            List <OHLC> ohlcList = new List <OHLC>();

            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    using (SqlCommand command = new SqlCommand("", connection))
                    {
                        command.CommandType = System.Data.CommandType.Text;
                        command.CommandText = "SELECT o.Id, o.[Open], o.High, o.Low, o.[Close], Start, Volume FROM dbo.OHLC o " +
                                              "WHERE o.[Start] >= @start AND o.[End] < @end ORDER BY o.Id ASC";
                        command.Parameters.Add(new SqlParameter("start", start));
                        command.Parameters.Add(new SqlParameter("end", end));

                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                var ohlc = new OHLC();

                                ohlc.Open  = reader.GetDecimal(1);
                                ohlc.High  = reader.GetDecimal(2);
                                ohlc.Low   = reader.GetDecimal(3);
                                ohlc.Close = reader.GetDecimal(4);
                                ohlc.Start = reader.GetDateTime(5);
                                var volume = reader.GetDecimal(6);
                                ohlc.Volume = (volume * 1000);

                                ohlcList.Add(ohlc);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            //Set the trading state
            State   = TradingState.Initial;
            Orders  = new List <Order>();
            Account = new Account()
            {
                Euro = 10000
            };

            //l h o c

            //Find the first trade
            //Find all trades within the next 5 minutes
            //If there are any trade
            //Calculate low, high, open, close
            if (ohlcList.Any())
            {
                start = ohlcList.First().Start > start?ohlcList.First().Start : start;

                for (DateTime i = start; i < end; i = i.AddMinutes(interval))
                {
                    var windowStart = i;
                    var windowEnd   = windowStart.AddMinutes(interval);

                    var ohlcInTheSameWindow = ohlcList.Where(o => o.Start >= windowStart && o.Start < windowEnd).ToList();

                    if (ohlcInTheSameWindow.Any())
                    {
                        var low    = ohlcInTheSameWindow.Select(t => t.Low).Min();
                        var high   = ohlcInTheSameWindow.Select(t => t.High).Max();
                        var open   = ohlcInTheSameWindow.First().Open;
                        var close  = ohlcInTheSameWindow.Last().Close;
                        var volume = ohlcInTheSameWindow.Sum(t => t.Volume);

                        var ohlc = new OHLC {
                            Open = open, High = high, Low = low, Close = close, Volume = volume, Start = windowStart, End = windowEnd
                        };

                        DataPoints.Insert(0, ohlc);

                        //Check for indicators and make trading decisions
                        DonchienBreakoutStrategy(ohlc, windowEnd, parameters);

                        //Add Donchian Channels
                        var dca = CalculateDonchianChannel(55);

                        UpperBand.Add((double)dca.UpperBand);
                        LowerBand.Add((double)dca.LowerBand);
                    }
                }
            }

            //Stats after simulation
            var stats = new Stats(Orders, Account, DataPoints)
            {
                Market = DataPoints.First().Close - DataPoints.Last().Close,
                MarketRiskAdjustedReturn = (double)((DataPoints.First().Close - DataPoints.Last().Close) / DataPoints.Last().Close) * 100,
                Target = (end - start).Days * 80, //80 EUR profit per day
            };

            return(new SimulationResult()
            {
                Dates = DataPoints.OrderBy(dp => dp.Start).Select(dp => dp.End).ToList(),
                Values = DataPoints.OrderBy(dp => dp.Start).Select(dp => dp.Close).ToList(),
                Volumes = DataPoints.OrderBy(dp => dp.Start).Select(dp => dp.Volume).ToList(),
                Upper = UpperBand,
                Lower = LowerBand,
                Orders = Orders,
                Events = Events,
                Stats = stats
            });
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {
            if (CurrentBar > prevBar)
            {
                prevBar = CurrentBar;

                if (CurrentBar == 0)
                {
                    cema1   = Median[0];
                    cema2   = cema1;
                    cema3   = cema1;
                    cubema1 = cema1;
                    cubema2 = cema1;
                    cubema3 = cema1;
                    clbema1 = cema1;
                    clbema2 = cema1;
                    clbema3 = cema1;
                    cnewVal = 0.0;
                    cdevSum = 0.0;
                }

                // midline
                ema1       = cema1;
                ema2       = cema2;
                ema3       = cema3;
                prevMedian = -1;

                // runerr
                devSum       = cdevSum;
                devs[curIdx] = cnewVal;
                if (++curIdx >= devLen)
                {
                    curIdx = 0;
                }

                // smooth bands
                ubema1 = cubema1;
                ubema2 = cubema2;
                ubema3 = cubema3;
                lbema1 = clbema1;
                lbema2 = clbema2;
                lbema3 = clbema3;
            }

            if (prevMedian != Median[0])
            {
                prevMedian = Median[0];
                // midline...
                cema1 = ema1 + alpha1 * (prevMedian - ema1);
                cema2 = ema2 + alpha2 * (prevMedian - ema2);
                cema3 = ema3 + alpha3 * (cema2 + cema2 - cema1 - ema3);

                // runerr...
                cnewVal = prevMedian - cema3;
                cnewVal = cnewVal * cnewVal;
                cdevSum = devSum - devs[curIdx] + cnewVal;
                var stdDev = numDevs * Math.Sqrt(Math.Max(cdevSum / devLen, 1e-10));

                // smooth bands...
                cubema1 = ubema1 + balpha1 * (cema3 + stdDev - ubema1);
                cubema2 = ubema2 + balpha2 * (cema3 + stdDev - ubema2);
                cubema3 = ubema3 + balpha3 * (cubema2 + cubema2 - cubema1 - ubema3);

                clbema1 = lbema1 + balpha1 * (cema3 - stdDev - lbema1);
                clbema2 = lbema2 + balpha2 * (cema3 - stdDev - lbema2);
                clbema3 = lbema3 + balpha3 * (clbema2 + clbema2 - clbema1 - lbema3);

                UpperBand.Set(cubema3);
                LowerBand.Set(clbema3);
                MidLine.Set(cema3);
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {
            if (CurrentBar > prevBar)
            {
                // NEW BAR PROCESSING
                prevBar = CurrentBar;
                if (barsToDisplay > 0 && prevBar > barsToDisplay)
                {
                    UpperBand.Reset(barsToDisplay);
                    LowerBand.Reset(barsToDisplay);
                    MidLine.Reset(barsToDisplay);
                }

                // midline
                var gv = newGaussVal(prevMedian, avgTotal);
                if (++curGaussIdx > poles)
                {
                    curGaussIdx = 0;
                }
                avg[curGaussIdx] = gv;
                avgTotal         = calcAvgTotal();
                prevMedian       = -1;

                // runerr
                devSum       = cdevSum;
                devs[curIdx] = cnewVal;
                if (++curIdx >= devLen)
                {
                    curIdx = 0;
                }

                // smooth bands
                ubema1 = cubema1;
                ubema2 = cubema2;
                ubema3 = cubema3;
                lbema1 = clbema1;
                lbema2 = clbema2;
                lbema3 = clbema3;
            }

            if (prevMedian != Median[0])
            {
                prevMedian = Median[0];
                // midline...
                var ngv = newGaussVal(prevMedian, avgTotal);

                // runerr...
                cnewVal = prevMedian - ngv;
                cnewVal = cnewVal * cnewVal;
                cdevSum = devSum - devs[curIdx] + cnewVal;
                var stdDev = numDevs * Math.Sqrt(Math.Max(cdevSum / devLen, 1e-10));

                // smooth bands...
                cubema1 = ubema1 + balpha1 * (ngv + stdDev - ubema1);
                cubema2 = ubema2 + balpha2 * (ngv + stdDev - ubema2);
                cubema3 = ubema3 + balpha3 * (cubema2 + cubema2 - cubema1 - ubema3);

                clbema1 = lbema1 + balpha1 * (ngv - stdDev - lbema1);
                clbema2 = lbema2 + balpha2 * (ngv - stdDev - lbema2);
                clbema3 = lbema3 + balpha3 * (clbema2 + clbema2 - clbema1 - lbema3);

                UpperBand.Set(cubema3);
                LowerBand.Set(clbema3);
                MidLine.Set(ngv);
            }
        }