// Regime switching ///////////////////
#include <profile.c>
#define USE_PREDICT
function run()
{
//StartDate = 20150101;
EndDate = 20171231; // fixed simulation period
Verbose = 2;
BarPeriod = 1440;
LookBack = 300; // needed for MMI
asset("SPY");
set(LOGFILE,PLOTNOW); // log all trades
vars Prices = series(priceClose());
// get the trend series
vars Osc = series(StochEhlers(series(price()),10,20,10));
// get the RSI series
vars RSI12 = series(RSI(Prices,12));
// Regime decision ////////////////////
// Calc indicator - percentrank(MA(percentrank(Stdev(close,21),252),21),250)
vars std = series(StdDev(Prices,20));
vars pcr_std = series(PercentRank(std, 252,std[0])); // returns a value
vars sma_pcr = series(SMA(pcr_std,21));
vars pcr_sma = series(PercentRank(sma_pcr, 252,sma_pcr[0]));
// Trend following - Ehler's
if(pcr_sma[0] < 50)
{
#ifndef USE_PREDICT
if(crossOver(Osc,0.8))
enterShort();
if(crossUnder(Osc,0.2))
enterLong();
#else
if(predict(CROSSOVER,series(Osc[0]-0.8),10,0.01) > -5)
enterShort();
if(predict(CROSSOVER,series(0.2-Osc[0]),10,0.01) > -5)
enterLong();
}
// MR - RSI 2
else
{
// set up stop / profit levels
Stop = 200*PIP;
TakeProfit = 200*PIP;
// if rsi crosses over buy level, exit short and enter long
if(crossOver(RSI12,75))
enterLong();
// if rsi crosses below sell level, exit long and enter short
if(crossUnder(RSI12,25))
enterShort();
}
// Plotting
//plotTradeProfile(-50);
plot("StochEhlers",Osc,NEW,RED);
plot("Threshold1",.2,0,BLACK);
plot("Threshold2",.8,0,BLACK);
}