// Workshop 6: Portfolio trading ///////////////////
function tradeTrend()
{
vars Price = series(price());
vars Trend = series(LowPass(Price,optimize(250,100,1000)));
Stop = optimize(4,2,8) * ATR(100);
Trail = 0;
if(valley(Trend) && OptimalFLong > 0) //long setup, known profitable
{
// reinvest the square root of profits
var MarginLong = sqrt(WinLong-LossLong)*OptimalFLong;
Margin = clamp(MarginLong, 5, 100); //max $1000 per trade
enterLong();
}
else if(peak(Trend) && OptimalFShort > 0) //short setup, known profitable
{
// reinvest the square root of profits
var MarginShort = sqrt(WinShort-LossShort)*OptimalFShort;
Margin = clamp(MarginShort, 5, 100); //max $1000 per trade
enterShort();
}
}
function tradeCounterTrend()
{
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);
Stop = optimize(4,2,8) * ATR(100);
Trail = 4*ATR(100);
if(crossUnder(Signal,-Threshold) && OptimalFLong > 0) //long setup, known profitable
{
// reinvest the square root of profits
var MarginLong = sqrt(WinLong-LossLong)*OptimalFLong;
Margin = clamp(MarginLong, 5, 100); //max $1000 per trade
enterLong();
}
else if(crossOver(Signal,Threshold) && OptimalFShort > 0) //short setup, known profitable
{
// reinvest the square root of profits
var MarginShort = sqrt(WinShort-LossShort)*OptimalFShort;
Margin = clamp(MarginShort, 5, 100); //max $1000 per trade
enterShort();
}
}
function run()
{
set(PARAMETERS+FACTORS+NFA); // generate and use optimized parameters
BarPeriod = 240; // 4 hour bars
StartDate = 2002;
LookBack = 500; // needed for Fisher()
NumWFOCycles = 8; // activate WFO
//if(ReTrain) {
// UpdateDays = -1; // update price data from the server
// SelectWFO = -1; // select the last cycle for re-optimization
//}
// portfolio loop
while(asset(loop("EURUSD","USDJPY","AUDUSD","EURCHF","GBPUSD","NZDUSD","USDCAD","USDCHF")))
while(algo(loop("TRND","CNTR")))
{
// initiate trade if known profitable track record
if(OptimalFLong > 0 or OptimalFShort > 0)
{
if(strstr(Algo,"TRND"))
tradeTrend();
else if(strstr(Algo,"CNTR"))
tradeCounterTrend();
}
}
PlotWidth = 800;
PlotHeight1 = 320;
}