// Workshop 5: Counter trend trading, optimized ////////////////
function reverseShort(int MaxTrades)
{
// update the stops and profit targets of open trades
if(Stop > 0)
exitShort(0,priceClose()+Stop);
if(TakeProfit > 0)
exitShort(0,(priceClose()+TakeProfit));
// if MaxTrades is not reached, open a new trade
if(NumOpenShort < MaxTrades)
enterShort();
// otherwise, close all opposite trades
else if(!mode(HEDGING))
exitLong();
return 0;
}
function reverseLong(int MaxTrades)
{
// update the stops and profit targets of open trades
if(Stop > 0)
exitLong(0,priceClose()-Stop);
if(TakeProfit > 0)
exitLong(0,-(priceClose()+TakeProfit));
// if MaxTrades is not reached, open a new trade
if(NumOpenLong < MaxTrades)
enterLong();
// otherwise, close all opposite trades
else if(!mode(HEDGING))
exitShort();
return 0;
}
function run()
{
set(PARAMETERS+NFA); // generate and use optimized parameters
BarPeriod = 240; // 4 hour bars
LookBack = 500;
StartDate = 2002;
NumWFOCycles = 5; // activate WFO
if(ReTrain) {
UpdateDays = -1; // update price data from the server
SelectWFO = -1; // select the last cycle for re-optimization
}
// calculate the buy/sell signal
vars Price = series(price());
vars DomPeriod = series(DominantPeriod(Price,30));
var LowPeriod = LowPass(DomPeriod,500);
vars HP = series(HighPass(Price,LowPeriod*optimize(1,0.5,2)));
vars Signal = series(Fisher(HP,500));
var Threshold = optimize(1,0.5,2,0.1);
// buy and sell
Stop = optimize(4,2,8) * ATR(100);
Trail = 4*ATR(100);
if(crossUnder(Signal,-Threshold))
reverseLong(1); //max 1 trade, update stops
//enterLong();
else if(crossOver(Signal,Threshold))
reverseShort(1); //max 1 trade, update stops
//enterShort();
PlotWidth = 800;
PlotHeight1 = 300;
}