using System; using System.Collections.Generic; using System.Text; using System.Drawing; using WealthLab; using WealthLab.Indicators; using Community.Indicators;namespace WealthLab.Strategies { public class MeanReversion : WealthScript { private StrategyParameter paramPeriod; public MeanReversion() { paramPeriod = CreateParameter("Period", 10, 5, 30, 5); } protected override void Execute() { int period = paramPeriod.ValueInt; int lmaPeriod = period * 10; SMA sma = SMA.Series( Close, period ); SMA lma = SMA.Series( Close, lmaPeriod ); DataSeries zscore = ZScore.Series( Close, period, StdDevCalculation.Sample ); PlotSeries( PricePane, sma, Color.Red, LineStyle.Solid, 1 ); PlotSeries( PricePane, lma, Color.Blue, LineStyle.Solid, 2 ); ChartPane zPane = CreatePane( 30, true, true ); PlotSeries( zPane, zscore, Color.DarkViolet, LineStyle.Histogram, 3 ); DrawHorzLine( zPane, 1.0, Color.Red, LineStyle.Dashed, 1 ); DrawHorzLine( zPane, -1.0, Color.Blue, LineStyle.Dashed, 1 ); //The trigger is a move up or down by more than one standard deviation from the 10-day average price: //a z-score of over +1 triggers a sell and a z-score of less than -1 triggers a buy. for(int bar = GetTradingLoopStartBar(1); bar < Bars.Count; bar++) { if (IsLastPositionActive) { // exit all positions if zscore flips from positive to negative or vice versa // without going through the neutral zone if( (zscorebar - 1 > 0.5 && zscorebar < -0.5) || (zscorebar - 1 < -0.5 && zscorebar > 0.5) || // Clear positions if the z-score between -.5 and .5 Math.Abs(zscorebar) < 0.5 ) SellAtMarket(bar+1, LastPosition); } else { // Buy long if the z-score is < -2 and the longer term trend is positive if( zscorebar < -2 && smabar > lmabar) BuyAtMarket(bar+1); } } } } }