// Alice3a: Portfolio trading ///////////////////
function tradeCounterTrend()
{
TimeFrame = frameSync(4);
vars Prices = series(price());
vars Cycles = series(BandPass(Prices,30,2));
vars Signals = series(FisherN(Cycles,500));
var Threshold = optimize(1,0.8,1.2,0.1);
LifeTime = 4*optimize(100,50,150,10);
Trail = Stop = optimize(10,4,20,2)*ATR(100);
MaxLong = MaxShort = -1;
var Regime = FractalDimension(Prices,100);
var RegimeThreshold = optimize(1.5,1.3,1.7,0.1);
if(okToTrade == true){
if(Regime > RegimeThreshold)
{
if(crossUnder(Signals,-Threshold))
enterLong();
else if(crossOver(Signals,Threshold))
enterShort();
}
}
}
function tradeTrend()
{
TimeFrame = 1;
vars Prices = series(price());
vars Trends = series(Laguerre(Prices,optimize(0.05,0.02,0.15,0.01)));
vars EMA20 = series(EMA(Prices,20));
Stop = optimize(10,4,20,2)*ATR(100);
Trail = 0;
LifeTime = 0;
MaxLong = MaxShort = -1;
var MMI_Period = optimize(300,100,400,100);
vars MMI_Raws = series(MMI(Prices,MMI_Period));
vars MMI_Avgs = series(SMA(MMI_Raws,MMI_Period));
if(okToTrade == true){
if(falling(MMI_Avgs)) {
if(valley(Trends))
enterLong();
else if(peak(Trends))
enterShort();
}
}
}
function run()
{
if(is(INITRUN)) {
bool okToTrade = false;
watch("!okToTradeINITRUN:",okToTrade);
}
set(PARAMETERS+LOGFILE+TESTNOW+PLOTNOW);
StartDate = 20240501; // further back due to WFO
//EndDate = 2018; // fixed simulation period
BarPeriod = 5; // 1 hour bars
LookBack = 5*400; // needed for FisherN()
if(Train) Detrend = TRADES;
StartMarket = 1330;
EndMarket = 2001;
BarMode = BR_MARKET;
// close all position at 16:15 local time
if(at(2000)) {
printf("\nClosin g all positions");
exitLong("**");
exitShort("**");
}
NumWFOCycles = 10; // activate WFO
NumCores = -1; // multicore training (Zorro S only)
ReTrainDays = 147;
if(ReTrain) {
UpdateDays = -1; // update price data from the server
SelectWFO = -1; // select the last cycle for re-optimization
}
if(at(1330 + BarPeriod)){
//THIS SAYS UNDECLARED IDENTIFIER EVEN THOUGH IT IS DECLARED IN INIT ABOVE
okToTrade = false;
watch("!okToTradeFIRSTBAR:",okToTrade);
}
// portfolio loop
while(asset(loop("MES","MYM"))){
vars Prices = series(price());
//ONCE THIS IS EMA TOUCHED FOR THE DAY
//I WANT TO RETAIN THIS FLAG VALUE AND ONLY TRADE
//AFTER IT IS SET TO TRUE
//THEN RESET IT AT ONLY AT FIRST BAR OF DAY ABOVE
vars EMA20 = series(EMA(Prices,20));
if(touch(Prices,EMA20))
okToTrade = true; //UNDECLARED ERROR
while(algo(loop("TRND","CNTR")))
watch("!okToTradeALGO:",okToTrade);
// WANT TO TRADE ONLY AFTER PRICE TOUCHES EMA(20)
//if(okToTrade == true)
{
if(Algo == "TRND")
tradeTrend(okToTrade);
else if(Algo == "CNTR")
tradeCounterTrend(okToTrade);
}
}
}