public void Indicators_Make_ATR_values() { List <Bar> bars = new List <Bar>(); bars.Add(new Bar(new DateTime(2013, 10, 11, 0, 0, 0), 148630, 149220, 148600, 149140, 35)); bars.Add(new Bar(new DateTime(2013, 10, 11, 11, 0, 0), 149170, 149310, 148380, 148800, 38)); bars.Add(new Bar(new DateTime(2013, 10, 11, 12, 0, 0), 148800, 148810, 147470, 147900, 38)); bars.Add(new Bar(new DateTime(2013, 10, 11, 13, 0, 0), 147910, 148370, 147800, 148250, 38)); bars.Add(new Bar(new DateTime(2013, 10, 11, 14, 0, 0), 148240, 148340, 147920, 148130, 38)); bars.Add(new Bar(new DateTime(2013, 10, 11, 15, 0, 0), 148110, 148290, 148000, 148260, 38)); bars.Add(new Bar(new DateTime(2013, 10, 11, 16, 0, 0), 148260, 148260, 147940, 147980, 38)); bars.Add(new Bar(new DateTime(2013, 10, 11, 17, 0, 0), 147990, 148110, 147670, 147680, 38)); bars.Add(new Bar(new DateTime(2013, 10, 11, 18, 0, 0), 147680, 147940, 147110, 147920, 38)); bars.Add(new Bar(new DateTime(2013, 10, 11, 19, 0, 0), 147920, 148030, 147550, 147810, 38)); IEnumerable <double> result = ATR.Values(bars, 5); Assert.AreEqual(0, result.ElementAt(0)); Assert.AreEqual(0, result.ElementAt(1)); Assert.AreEqual(0, result.ElementAt(2)); Assert.AreEqual(0, result.ElementAt(3)); Assert.AreEqual(776, result.ElementAt(4)); Assert.AreEqual(710, result.ElementAt(5)); Assert.AreEqual(588, result.ElementAt(6)); Assert.AreEqual(408, result.ElementAt(7)); Assert.AreEqual(460, result.ElementAt(8)); Assert.AreEqual(472, result.ElementAt(9)); }
public async Task<IndSingleValueEntity[]> GetATR(string code, int period, int? start = 0, int? end = 0, string type = "day") { TickerEntity[] tickers = await base.getTickerEntityArray(code, start, end, type); List<IndSingleValueEntity> outList = new List<IndSingleValueEntity>(); int len = tickers.Length; double[] close = tickers.Select(t => (double)t.C).ToArray(); double[] high = tickers.Select(t => (double)t.H).ToArray(); double[] low = tickers.Select(t => (double)t.L).ToArray(); double?[] outATR = new double?[len]; ATR.Calculate(high, low, close, period, outATR); for (int i = 0; i < len; i++) { outList.Add(new IndSingleValueEntity { T = tickers[i].T, P = tickers[i].P, V = outATR[i] }); } return outList.Where(r => (start == 0 || r.P >= start) && (end == 0 || r.P <= end)).ToArray(); }
public CMCSuperTrend(Bars bars, double ATRMultiple, int ATRPeriod, string description) : base(bars, description) { base.FirstValidValue = ATRPeriod * 3; int state = 1; for (int bar = FirstValidValue; bar < bars.Count; bar++) { double Value = 0; if (state == 1) { if (bars.Close[bar] < base[bar - 1]) { state = -1; Value = bars.High[bar] + ATRMultiple * ATR.Series(bars, ATRPeriod)[bar]; } else Value = Math.Max(this[bar - 1], bars.Low[bar] - ATRMultiple * ATR.Series(bars, ATRPeriod)[bar]); } else { if (bars.Close[bar] > base[bar - 1]) { state = 1; Value = bars.Low[bar] - ATRMultiple * ATR.Series(bars, ATRPeriod)[bar]; } else Value = Math.Min(this[bar - 1], bars.High[bar] + ATRMultiple * ATR.Series(bars, ATRPeriod)[bar]); } base[bar] = Value; } }
//populate public override void Populate() { BarHistory source = Parameters[0].AsBarHistory; Int32 period = Parameters[1].AsInt; Double factor = Parameters[2].AsDouble; DateTimes = source.DateTimes; //ATR ATR atr = new ATR(source, period); //calculate ATR Trailing Stop for (int n = period; n < source.Count; n++) { double loss = factor * atr[n]; if (source.Close[n] > Values[n - 1] && source.Close[n - 1] > Values[n - 1]) { Values[n] = Math.Max(Values[n - 1], source.Close[n] - loss); } else if (source.Close[n] < Values[n - 1] && source.Close[n - 1] < Values[n - 1]) { Values[n] = Math.Min(Values[n - 1], source.Close[n] + loss); } else { Values[n] = source.Close[n] > Values[n - 1] ? source.Close[n] - loss : source.Close[n] + loss; } } }
public override void GetAll(IIndicatorValues Ind) { int period = (int)this.IndicatorParameters.List[0]; if (!Ind.ATR(period).IsPopulated) { int oldCurrentBar = Ind.Bar.CurrentBar; for (int i = 1; i <= Ind.Bar.MaxBar; i++) { Ind.Bar.CurrentBar = i; object prototype = null; if (i == 1) { prototype = new ATR(); } else { prototype = (ATR)Ind.ATR(period)[1].Clone(); } Get(ref prototype, Ind); Ind.ATR(period)[0] = (ATR)prototype; Ind.ATR(period).IsPopulated = true; // set here so instance is guaranteed to exits } Ind.Bar.CurrentBar = oldCurrentBar; } }
// Описание: // За основу взята стратегия Черепах - http://www.benvanvliet.net/Downloads/turtlerules.pdf // Описание модификации - https://support.softalgotrade.com/forums/topic/turtle-system-revisited // Исходные данные: свечки или тики. Рассмотрены оба варианта. // Свечки используются для расчета индикаторов. // Для более точного входа в позицию и расчета стоп заявок можем использовать тики. // Алгоритм: // Строится два канала Дончиана - ChannelOne и ChannelTwo. Канал Дончиана - это пара индикаторов Highest и Lowest. // Период внутреннего канала ChannelTwo устанавливаем в процентах относительно внешнего канала ChannelOne. // Входим в позицию: // - Покупаем, когда цена касается канала UpperChannelOne. // - Продаем, когда цена касается канала LowerChannelOne. // Закрываем позицию: // - Покупаем, когда цена касается канала UpperChannelTwo. // - Продаем, когда цена касается канала LowerChannelTwo. // Дополнительно: // 1) Стратегия интрадей. Торгуем с 10:05, в конце торговой сессии (23:40) закрываем все открытые позиции - метод CheckIntraDayTime(). // 2) При входе/выходе ориентируемся на риск, который рассчитываем по формуле: risk = k * atr, // Где к - коэффициент риска, atr - текущее значение индикатора ATR. // 3) Для расчета стоп заявок используем соответствующие методы MarkуtToMarket для тиков и свечек. // 4) Объем входа в позицию рассчитываем по формуле: // Volume = Math.Min(currentFunds * riskPerTrade / risk, currentFunds / initialMargin), // Где currentFunds - текущие доступные денежные средства, initialMargin - гарантийное обеспечение // riskPerTrade - процент риска, risk - риск (см. выше). // 5) Все лимитные заявки выставляем "глубоко в рынок" для мгновенного исполнения как маркет. // Индикаторы: // Две пары индикаторов Highest и Lowest - два канала Дончиана. // Индикатор ATR (Average True Range) - для расчета риска. public override void Initialization() { try { //Создаем индикаторы для торговой стратегии //Период первого канала var periodDonchianChannelOne = (int)Parameter(1); _upperChannelOne = new Highest(periodDonchianChannelOne); _lowerChannelOne = new Lowest(periodDonchianChannelOne); //Период второго канала - процент от периода от первого канала var periodDonchianChannelTwo = (int)(periodDonchianChannelOne * Parameter(2) * 0.01m); _upperChannelTwo = new Highest(periodDonchianChannelTwo); _lowerChannelTwo = new Lowest(periodDonchianChannelTwo); //Для расчета риска и объема позиции _atr = new ATR((int)Parameter(3)); _k = (int)Parameter(4); _riskPerTrade = Parameter(5) * 0.01m; //Для выставления лимитных заявок в рынок для гарантированного исполнения _offset = GetSecurity().Tick * 10; //Подписываемся на события при инициализации стратегии Subscribe(); } catch (Exception ex) { ExceptionMessage(ex, "Strategy"); } }
public override void Initialization() { try { //Создаем индикаторы для торговой стратегии _upperChannelOne = new Highest((int)Parameter(1)); _lowerChannelOne = new Lowest((int)Parameter(1)); _upperChannelTwo = new Highest((int)Parameter(1) / 2); //50% от P1 _lowerChannelTwo = new Lowest((int)Parameter(1) / 2); //50% от P1 _adxLookBack = new ADX((int)Parameter(2)); _adxThreshold = new ADX((int)Parameter(3)); _atr = new ATR((int)Parameter(4)); _atrStop = (int)Parameter(5); _volume = (int)Parameter(6); //Для выставления лимитных заявок в рынок для гарантированного исполнения _offset = GetSecurity().Tick *10; //Инициализируем алгоритмические заявки InitializationAlgoOrders(); //Подписываемся на события при инициализации стратегии Subscribe(); } catch (Exception ex) { ExceptionMessage(ex, "Strategy"); } }
public void Indicators_Make_ATR_for_one_bar_test() { List <Bar> bars = new List <Bar>(); bars.Add(new Bar(new DateTime(2013, 10, 1), 50, 55, 49, 51, 35)); Assert.AreEqual(6, ATR.Value(bars)); }
protected override void OnStateChange() { if (State == State.SetDefaults) { Description = @"Buy when Fast EMA > Med EMA > Slow EMA, sell when Price < Prev-ATR(10)"; Name = "EMACrosswithSL"; Calculate = Calculate.OnBarClose; EntriesPerDirection = 1; EntryHandling = EntryHandling.AllEntries; IsExitOnSessionCloseStrategy = true; ExitOnSessionCloseSeconds = 30; IsFillLimitOnTouch = false; MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix; OrderFillResolution = OrderFillResolution.Standard; Slippage = 0; StartBehavior = StartBehavior.WaitUntilFlat; TimeInForce = TimeInForce.Gtc; TraceOrders = true; RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose; StopTargetHandling = StopTargetHandling.PerEntryExecution; BarsRequiredToTrade = 20; // Disable this property for performance gains in Strategy Analyzer optimizations // See the Help Guide for additional information IsInstantiatedOnEachOptimizationIteration = true; FastEma = 5; MedEma = 20; SlowEma = 50; ATRPeriod = 10; ATRMultipleSL = 2; ATRMultipleLimit = 0.5; InitialCapital = 100000; AddLine(Brushes.Blue, 1, "ATR"); AddPlot(Brushes.LimeGreen, "FastEmaLine"); AddPlot(Brushes.Orange, "MedEmaLine"); AddPlot(Brushes.Salmon, "SlowEmaLine"); PrintTo = PrintTo.OutputTab2; Print("set default"); } else if (State == State.Configure) { //AddDataSeries("ADANIPORTS", Data.BarsPeriodType.Day, 1, Data.MarketDataType.Last); _atr = ATR(this.ATRPeriod); _atr.Lines = Lines.Where(l => l.Name == "ATR").ToArray(); _fast = EMA(FastEma); _fast.Plots = Plots.Where(p => p.Name == "FastEmaLine").ToArray(); _med = EMA(MedEma); _med.Plots = Plots.Where(p => p.Name == "MedEmaLine").ToArray(); _slow = EMA(SlowEma); _slow.Plots = Plots.Where(p => p.Name == "SlowEmaLine").ToArray(); base.AddChartIndicator(_atr); base.AddChartIndicator(_fast); base.AddChartIndicator(_med); base.AddChartIndicator(_slow); Print("configured"); } }
public void Indicators_Make_TrueRange_for_two_bars_test() { List <Bar> bars = new List <Bar>(); bars.Add(new Bar(new DateTime(2013, 10, 1), 50, 55, 49, 51, 35)); bars.Add(new Bar(new DateTime(2013, 10, 2), 51, 56, 48, 52, 38)); Assert.AreEqual(7, ATR.Value(bars)); }
public ATRSeries(C1FlexChart chart, string plotAreaName) : base() { Chart = chart; Chart.BeginUpdate(); Axis axisY = new Axis(); axisY.TitleStyle = new ChartStyle(); axisY.TitleStyle.FontWeight = FontWeights.Bold; axisY.Position = C1.Chart.Position.Right; axisY.PlotAreaName = plotAreaName; axisY.Title = "ATR"; axisY.Labels = false; axisY.MajorTickMarks = axisY.MinorTickMarks = C1.Chart.TickMark.None; ATR series = new ATR(); series.ChartType = C1.Chart.Finance.FinancialChartType.Line; series.Style = new ChartStyle(); series.Style.Stroke = new SolidColorBrush(Color.FromArgb(255, 51, 103, 214)); series.Style.Fill = new SolidColorBrush(Color.FromArgb(128, 66, 133, 244)); series.Style.StrokeThickness = 1; series.BindingX = "Date"; series.Binding = "High,Low,Close"; series.AxisY = axisY; Chart.Series.Add(series); Utilities.Helper.BindingSettingsParams(chart, series, typeof(ATR), "Average True Range (ATR)", new Data.PropertyParam[] { new Data.PropertyParam("Period", typeof(int)), new Data.PropertyParam("Style.Stroke", typeof(Brush)), }, () => { this.OnSettingParamsChanged(); } ); //binding series color to axis title. Binding binding = new Binding(); binding.Path = new Windows.UI.Xaml.PropertyPath("Stroke"); binding.Source = series.Style; BindingOperations.SetBinding(axisY.TitleStyle, ChartStyle.StrokeProperty, binding); Chart.EndUpdate(); this.Series = new FinancialSeries[] { series }; }
public void Indicators_Make_ATR_for_collection() { List <Bar> bars = new List <Bar>(); bars.Add(new Bar(new DateTime(2013, 10, 1), 50, 55, 49, 51, 35)); bars.Add(new Bar(new DateTime(2013, 10, 2), 51, 56, 48, 52, 38)); bars.Add(new Bar(new DateTime(2013, 10, 3), 49, 53, 44, 50, 41)); Assert.AreEqual(7.6667, ATR.Value(bars)); }
public override void OnInit() { if (HasPosition) { //60天日线 DateTime curDate = Clock.Now.Date; ISeriesObject[] dailyBars = Util.GetNDailiesBeforeDate(this.instrument, curDate, 60); Util.AdjustDailys(dailyBars); //向前复权 foreach (Daily dBar in dailyBars) { this.Bar.Add(dBar); } if (this.DailyBar.Count > this.lengthATR) { this.moveStopATR = ATR.Value(this.DailyBar, this.DailyBar.LastIndex, lengthATR, EIndicatorStyle.MetaStock); //昨日ATR } int n = this.DailyBar.Count; int i; for (i = n - 1; i >= 0; i--) { if (this.DailyBar[i].DateTime <= Position.EntryDate.Date) { break; } } if (this.DailyBar[i].DateTime < Position.EntryDate.Date) { i++; } if (i < 0) { i = 0; } this.positionCycle = n - i + 1; for (int j = i; j < n; j++) { if (this.DailyBar[j].High > this.positionMaxPrice) { this.positionMaxPrice = this.DailyBar[j].High; //入场后的最高价格,不包括入场那一天 } } this.calcMoveStopPrice(); int length = i > this.lengthATR?this.lengthATR:i - 1; if (length > 0) { this.stopLossATR = ATR.Value(this.DailyBar, i - 1, length, EIndicatorStyle.MetaStock); //入场前一天的ATR } this.calcStopLossPrice(); //this.judgeStagnant(); Console.WriteLine("投资组合中的证券 {0} :", Position.Instrument.Symbol); Console.WriteLine("持仓周期是 {0},绝对止损价格是 {1},持仓后最大价格是 {2}", this.positionCycle, this.stopLossPrice, this.positionMaxPrice); } }
public AverageDistance(Bars bars, int period, string description) : base(bars, description) { base.FirstValidValue = period * 3; DataSeries sma = Community.Indicators.FastSMA.Series(bars.Close, period); ATR atr = ATR.Series(bars, period); for (int bar = FirstValidValue; bar < bars.Count; bar++) { base[bar] = (bars.Close[bar] - sma[bar]) / atr[bar]; } }
protected override void OnStateChange() { if (State == State.SetDefaults) { Description = @"Enter the description for your new custom Strategy here."; Name = "CesarSalad"; Calculate = Calculate.OnBarClose; EntriesPerDirection = 1; EntryHandling = EntryHandling.AllEntries; IsExitOnSessionCloseStrategy = true; ExitOnSessionCloseSeconds = 30; IsFillLimitOnTouch = false; MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix; OrderFillResolution = OrderFillResolution.Standard; Slippage = 0; StartBehavior = StartBehavior.WaitUntilFlat; TimeInForce = TimeInForce.Gtc; TraceOrders = false; RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose; StopTargetHandling = StopTargetHandling.PerEntryExecution; BarsRequiredToTrade = 20; // Disable this property for performance gains in Strategy Analyzer optimizations // See the Help Guide for additional information IsInstantiatedOnEachOptimizationIteration = true; RangeHighLow = 7; RangeMA = 100; RSIEntryLevel = 15; RSIExitLevel = 30; RSIPeriod = 5; ATRPeriod = 10; ATRMultiple = 0.5; InitialCapital = 100000; } else if (State == State.Configure) { _rsi = RSI(this.RSIPeriod, 3); _rsi.Plots[1].Brush = Brushes.Brown; _rsi.Lines[0].Value = this.RSIEntryLevel; _rsi.Lines[1].Value = this.RSIExitLevel; base.AddChartIndicator(_rsi); _regime = SMA(this.RangeMA); _regime.Plots[0].Width = 3; _regime.Plots[0].Brush = Brushes.AliceBlue; base.AddChartIndicator(_regime); _atr = ATR(this.ATRPeriod); base.AddChartIndicator(_atr); base.ClearOutputWindow(); } }
public void ATR() { ATR atr = new ATR(); atr.Load(OhlcList); ATRSerie serie = atr.Calculate(); Assert.IsNotNull(serie); Assert.IsTrue(serie.ATR.Count > 0); Assert.IsTrue(serie.TrueHigh.Count > 0); Assert.IsTrue(serie.TrueLow.Count > 0); Assert.IsTrue(serie.TrueRange.Count > 0); }
public void ATR() { ATR atr = new ATR(); atr.Load(Directory.GetCurrentDirectory() + "\\table.csv"); ATRSerie serie = atr.Calculate(); Assert.IsNotNull(serie); Assert.IsTrue(serie.ATR.Count > 0); Assert.IsTrue(serie.TrueHigh.Count > 0); Assert.IsTrue(serie.TrueLow.Count > 0); Assert.IsTrue(serie.TrueRange.Count > 0); }
protected override string GetPresentDetail(IOutputInstant Instant, IIndicatorValues Data, IndicatorParameters IndicatorParameters) { ATR atr = Data.ATR(IndicatorParameters)[Instant.ExposureDate]; if (atr != null) { return(String.Format("{0}|", atr.Value)); } else { return(String.Format("{0}|", "")); } }
/// <summary> /// This method is used to configure the strategy and is called once before any strategy method is called. /// /// E-Mini Scalper: Trying to simulate trade2live.com or eminiTradingStrategy.com autotrader /// /// Puts on positions on a pull back of a strong trend. /// /// Ref: /// http://trade2live.com/ /// http://scalpingemini.com/ /// /// </summary> protected override void Initialize() { // Secondary bar which will be used when entering trades // this will be the bar which contains the buy/sell orders Add("ES 03-15", PeriodType.Minute, 5); // Indicator Setup // --------------- hma = HMARick(Period1, 100); hma.PaintPriceMarkers = false; Add(hma); Add(PitColor(Color.Black, 83000, 25, 161500)); atr = ATR(Period2); Add(atr); atrTrailing = ATRTrailing(atrTimes, Period2, Ratched); //Add(atrTrailing); kc = KeltnerChannel(offsetMultiplier, Period3); //Add(kc); Add(FiveBarPattern()); // dc = DonchianChannel(donchianPeriod); // dc.Displacement = 2; // dc.PaintPriceMarkers = false; // Add(dc); Unmanaged = true; // Use unmanaged order methods // Methods BarsSinceEntry() and BarsSinceExit() are usuable in Unmanaged orders // Managed Properties // -------------------- //EntriesPerDirection = 2; //EntryHandling = EntryHandling.UniqueEntries; //SetProfitTarget("", CalculationMode.Percent, dparm2); //SetStopLoss("", CalculationMode.Percent, dparm2, false); //SetTrailStop("", CalculationMode.Percent, dparm2, false); //Slippage = 2; BarsRequired = 22; CalculateOnBarClose = true; // Onbar update happens only on the start of a new bar vrs each tick ExitOnClose = true; // Closes open positions at the end of the session IncludeCommission = true; // Commissions are used in the calculation of the profit/loss TraceOrders = false; // Trace orders in the output window, used for debugging, normally false }
public void Indicators_Make_ATR_value() { List <Bar> bars = new List <Bar>(); bars.Add(new Bar(new DateTime(2013, 10, 11, 0, 0, 0), 148630, 149220, 148600, 149140, 35)); bars.Add(new Bar(new DateTime(2013, 10, 11, 11, 0, 0), 149170, 149310, 148380, 148800, 38)); bars.Add(new Bar(new DateTime(2013, 10, 11, 12, 0, 0), 148800, 148810, 147470, 147900, 38)); bars.Add(new Bar(new DateTime(2013, 10, 11, 13, 0, 0), 147910, 148370, 147800, 148250, 38)); bars.Add(new Bar(new DateTime(2013, 10, 11, 14, 0, 0), 148240, 148340, 147920, 148130, 38)); bars.Add(new Bar(new DateTime(2013, 10, 11, 15, 0, 0), 148110, 148290, 148000, 148260, 38)); bars.Add(new Bar(new DateTime(2013, 10, 11, 16, 0, 0), 148260, 148260, 147940, 147980, 38)); bars.Add(new Bar(new DateTime(2013, 10, 11, 17, 0, 0), 147990, 148110, 147670, 147680, 38)); bars.Add(new Bar(new DateTime(2013, 10, 11, 18, 0, 0), 147680, 147940, 147110, 147920, 38)); bars.Add(new Bar(new DateTime(2013, 10, 11, 19, 0, 0), 147920, 148030, 147550, 147810, 38)); Assert.AreEqual(624, ATR.Value(bars)); }
public override void OnInit() { DateTime curDate = Clock.Now.Date; if (!HasPosition) { int length = this.DailyBar.Count > this.lengthATR?this.lengthATR:this.DailyBar.Count - 1; if (length > 0) { this.lastATR = ATR.Value(this.DailyBar, this.DailyBar.LastIndex, length, EIndicatorStyle.MetaStock); } else { this.lastATR = 1; } this.canOrder = true; } this.openTime = curDate.Add(new TimeSpan(9, 30, 0)); this.portfolioRisk = this.portfolioRisk * this.strategy.PositionLevel; }
public double[] CalculateATR(IEnumerable <Quote> quotes, int period) { var listOhlc = quotes.Select( x => new Ohlc { Date = x.Date, Close = x.Close, AdjClose = x.Close, High = x.High, Low = x.Low, Open = x.Open, Volume = x.Volume }).ToList(); var atr = new ATR(period); atr.Load(listOhlc); var result = atr.Calculate(); return(result.ATR.Select(x => x.GetValueOrDefault()).ToArray()); }
public MTSuperTrendSeries(Bars bars, int CCIPeriod, double ATRMultiple, int ATRPeriod, string description) : base(bars, description) { base.FirstValidValue = Math.Max(CCIPeriod, ATRPeriod * 3); for (int bar = FirstValidValue; bar < bars.Count; bar++) { double Value = 0; if (CCI.Series(bars, CCIPeriod)[bar] >= 0) { Value = Math.Max(base[bar - 1], bars.Low[bar] - ATRMultiple * ATR.Series(bars, ATRPeriod)[bar]); } else { Value = Math.Min(base[bar - 1], bars.High[bar] + ATRMultiple * ATR.Series(bars, ATRPeriod)[bar]); } base[bar] = Value; } }
public KaseCD(Bars bars, int fastPeriod, int slowPeriod, string description) : base(bars, description) { base.FirstValidValue = Math.Max(fastPeriod, slowPeriod); DataSeries RWH = new DataSeries(bars, "RWH"); DataSeries RWL = new DataSeries(bars, "RWL"); for (int bar = FirstValidValue; bar < bars.Count; bar++) { RWH[bar] = (((bars.High[bar] - bars.Low[bar - slowPeriod])) / ((ATR.Series(bars, slowPeriod)[bar] * Math.Sqrt(slowPeriod)))); RWL[bar] = (((bars.High[bar - slowPeriod] - bars.Low[bar])) / ((ATR.Series(bars, slowPeriod)[bar] * Math.Sqrt(slowPeriod)))); } DataSeries Pk = Community.Indicators.FastSMA.Series(WMA.Series((RWH - RWL), fastPeriod), fastPeriod); DataSeries KCD = Pk - Community.Indicators.FastSMA.Series(Pk, slowPeriod); for (int bar = FirstValidValue; bar < bars.Count; bar++) { base[bar] = KCD[bar]; } }
public void TestATR() { double[] high = new double[] { 48.70, 48.72, 48.90, 48.87, 48.82, 49.05, 49.20, 49.35, 49.92, 50.19, 50.12, 49.66, 49.88, 50.19, 50.36, 50.57, 50.65, 50.43, 49.63, 50.33, 50.29, 50.17, 49.32, 48.50, 48.32, 46.80, 47.80, 48.39, 48.66, 48.79 }; double[] low = new double[] { 47.79, 48.14, 48.39, 48.37, 48.24, 48.64, 48.94, 48.86, 49.50, 49.87, 49.20, 48.90, 49.43, 49.73, 49.26, 50.09, 50.30, 49.21, 48.98, 49.61, 49.20, 49.43, 48.08, 47.64, 41.55, 44.28, 47.31, 47.20, 47.90, 47.73 }; double[] close = new double[] { 48.16, 48.61, 48.75, 48.63, 48.74, 49.03, 49.07, 49.32, 49.91, 50.13, 49.53, 49.50, 49.75, 50.03, 50.31, 50.52, 50.41, 49.34, 49.37, 50.23, 49.24, 49.93, 48.43, 48.18, 46.57, 45.41, 47.77, 47.72, 48.62, 47.85 }; int len = close.Length; double?[] outATR = new double?[len]; ATR.Calculate(high, low, close, 14, outATR); Console.WriteLine("di plus: " + ObjectHelper.ToJson(outATR)); }
public HasslerTSI(Bars bars, DataSeries ds, int period1, int period2, string description) : base(ds, description) { base.FirstValidValue = Math.Max(period2, period1); if (FirstValidValue > ds.Count || FirstValidValue < 0) { FirstValidValue = ds.Count; } if (ds.Count < period1 || ds.Count < period2) { return; } ATR atr = ATR.Series(bars, period1); DataSeries Ratio = DataSeries.Abs(ds - (ds >> period1)) / atr; DataSeries HasslerTSI = Community.Indicators.FastSMA.Series(Community.Indicators.FastSMA.Series(Ratio, period1), period2); for (int i = FirstValidValue; i < ds.Count; i++) { base[i] = HasslerTSI[i]; } }
/// <summary> /// This method is used to configure the strategy and is called once before any strategy method is called. /// /// </summary> protected override void Initialize() { atr = ATR(14); Add(atr); dc = DonchianChannel(DonchianPeriod); dc.Displacement = 1; dc.PaintPriceMarkers = false; Add(dc); // // CL settings CST // Add(PitColor(Color.Blue, 80000, 15, 143000)); SetProfitTarget(CalculationMode.Ticks, ProfitTarget); SetStopLoss(CalculationMode.Ticks, StopLoss); //SetTrailStop(CalculationMode.Ticks, Iparm2); Unmanaged = false; BarsRequired = 10; CalculateOnBarClose = true; ExitOnClose = false; IncludeCommission = true; }
public ATRBandLower(Bars bars, DataSeries ds, int atrPeriod, double atrMult, string description) : base(bars, description) { base.FirstValidValue = Math.Max(ds.FirstValidValue, atrPeriod * 3); if (FirstValidValue > ds.Count || FirstValidValue < 0) { FirstValidValue = ds.Count; } if (ds.Count < atrPeriod) { return; } var rangePartitioner = Partitioner.Create(FirstValidValue, ds.Count); Parallel.ForEach(rangePartitioner, (range, loopState) => { for (int bar = range.Item1; bar < range.Item2; bar++) { base[bar] = ds[bar] - atrMult * ATR.Series(bars, atrPeriod)[bar]; } }); }
protected SingleOrder AddPosition(Position position) { if (position != null) { string text = "买进最佳持仓"; Instrument instrument = position.Instrument; BarSeries dailyBars = this.strategy.Bars[instrument, BarType.Time, 86400]; double lastATR = 1.0; if (dailyBars.Count > 5) { lastATR = ATR.Value(dailyBars, dailyBars.LastIndex, 5, EIndicatorStyle.MetaStock); //昨日ATR } int expectQty = (int)(this.strategy.Portfolio.GetTotalEquity() * this.strategy.PositionLevel * 0.01 / lastATR); expectQty = expectQty / 100 * 100; Signal signal; switch (position.Side) { case PositionSide.Long: signal = new Signal(Clock.Now, SignalType.Market, SignalSide.Buy, expectQty, 0, instrument, text); signal.TimeInForce = TimeInForce.Day; return(this.strategy.EmitSignal(signal)); case PositionSide.Short: signal = new Signal(Clock.Now, SignalType.Market, SignalSide.SellShort, expectQty, 0, instrument, text); signal.TimeInForce = TimeInForce.Day; return(this.strategy.EmitSignal(signal)); default: return(null); } } else { return(null); } }
/// <summary> /// keltner constructor. /// </summary> /// <param name="initialNextUpdateDateTime"></param> /// <param name="keltnerTradingVariables"></param> /// <param name="marketOpens"></param> /// <param name="marketCloses"></param> public KeltnerIndicatorManager(DateTime initialNextUpdateDateTime, KeltnerTradingVariables keltnerTradingVariables, List <DateTime> marketOpens, List <DateTime> marketCloses) : base() { // Load keltner trading parameters. m_KeltnerTradingVariables = keltnerTradingVariables; m_EMALength = keltnerTradingVariables.EMALength; m_ATRLength = keltnerTradingVariables.ATRLength; m_MOMLength = keltnerTradingVariables.MomentumLength; m_BarUpdateIntervalSecond = keltnerTradingVariables.BarIntervalInSeconds; // Create indicators. m_EMA = new EMA(m_EMASeriesID, m_EMASeriesName, m_EMALength); m_ATR = new ATR(m_ATRSeriesID, m_ATRSeriesName, m_ATRLength); m_MOM = new MOM(m_MOMSeriesID, m_MOMSeriesName, m_MOMLength); this.AddIndicator(m_EMA, m_EMASeriesName); this.AddIndicator(m_ATR, m_ATRSeriesName); this.AddIndicator(m_MOM, m_MOMSeriesName); // Initial setup for the trading indicators. initialNextUpdateDateTime = Functions.GetNextBarUpdateDateTime(initialNextUpdateDateTime, m_BarUpdateIntervalSecond); m_EMA.SetupIndicator(m_BarUpdateIntervalSecond, initialNextUpdateDateTime, marketOpens, marketCloses); m_ATR.SetupIndicator(m_BarUpdateIntervalSecond, initialNextUpdateDateTime, marketOpens, marketCloses); m_MOM.SetupIndicator(m_BarUpdateIntervalSecond, initialNextUpdateDateTime, marketOpens, marketCloses); }