using System; using System.Collections.Generic; using System.Text; using System.Drawing; using WealthLab; using WealthLab.Indicators;namespace WealthLab.Strategies { public class ModifiedTrueRange : WealthScript { private StrategyParameter paramPeriod; public ModifiedTrueRange() { paramPeriod = CreateParameter("Period", 20, 1, 100, 1); } protected override void Execute() { int period = paramPeriod.ValueInt; double Goal = 9.99; //Calcluate modified true range (MTR) DataSeries MTR = new DataSeries( Bars,"MTR" ); DataSeries RangeLow = DataSeries.Abs( (Close>>1)-Lowest.Series(Low,1) ); DataSeries RangeHigh = DataSeries.Abs( (Close>>1)-Highest.Series(High,1) ); DataSeries Range1 = new DataSeries( Bars,"Range" ); DataSeries HitGoal = new DataSeries( Bars,"HitGoal" ); DataSeries GoalCount = new DataSeries( Bars,"GoalCount" ); DataSeries GoalPct = new DataSeries( Bars,"GoalPct" ); DataSeries AvgMTR = new DataSeries( Bars,"AvgMTR" ); for(int bar = 1; bar < Bars.Count; bar++) { double mtr = Math.Max(RangeLow[bar],RangeHigh[bar]); MTR[bar] = mtr; } //MTR Standard Deviation DataSeries RangeLow1=( (Close>>1) - Lowest.Series(Low,1) ); DataSeries RangeHigh1=( (Close>>1) - Highest.Series(High,1) ); for(int bar = 1; bar < Bars.Count; bar++) { double range = ( Math.Abs(RangeLow1[bar]) >= Math.Abs(RangeHigh1[bar]) ) ? RangeLow1[bar] : RangeHigh1[bar]; Range1[bar] = range; } DataSeries MTRStdDev = StdDev.Series(Range1,period,StdDevCalculation.Sample); for(int bar = 1; bar < Bars.Count; bar++) { HitGoal[bar] = MTR[bar] >= Goal ? 1 : 0; GoalCount[bar] = Sum.Series( HitGoal,period )[bar]; double goalPct = Math.Round( GoalCount[bar]/period, 2) * 100; double avgMTR = Math.Round( SMA.Series(MTR,period)[bar], 2 ); GoalPct[bar] = goalPct; AvgMTR[bar] = avgMTR; } StdDev MTRSD = StdDev.Series(MTR,period,StdDevCalculation.Sample); ChartPane mtrPane = CreatePane( 40, true, true ); PlotSeries( mtrPane, MTR, Color.Red, LineStyle.Histogram, 1 ); PlotSeries( mtrPane, AvgMTR, Color.Blue, LineStyle.Solid, 2 ); PlotStops(); for(int bar = GetTradingLoopStartBar(period); bar < Bars.Count; bar++) { if (IsLastPositionActive) { Position p = LastPosition; if( p.PositionType == PositionType.Long ) SellAtStop( bar+1, p, Lowest.Series( Low,3 )[bar] ); else CoverAtStop( bar+1, p, Highest.Series( High,3 )[bar] ); } else { //MTR spike bool spike = MTR[bar] > (AvgMTR[bar] + 3 * MTRSD[bar]); if( spike ) { SetBackgroundColor( bar, Color.FromArgb( 20, Color.Green ) ); if( ROC.Value( bar, Close, 1 ) > 0 ) ShortAtMarket(bar+1 ); else BuyAtMarket(bar+1 ); } } } } } }