Too much code leads to confusion, was: Flow control

Hi everyone, I'm new to Amibroker and AFL. I'm not a dev but a self taught guy and I'm starting to code all my strategies. I started with pinescript and want to move all my scripts to AFL because I got a new job where I am asked for a robust backtest.

Amibroker ver 6.40.4
TimeFrame m5
Ticker MNQ1!

This is the idea I'm trying to code:
I've two Buy conditions and two Short conditions.
BuyCond1 and ShortCond1 are my main signals with fixed SL & TP, these are typical channel BO. If prev trade was also a main signal MUST be a bar between the prev and the new signal. In other words, once a trade finishes (SL or TP) for ex in the 11:55 bar the 12:00 bar must meet the condition for a new signal and the new trade will start at 12:05 Open. If 11:55 bar meet signal criteria it should not trigger a trade because is the same bar previous trade finished.

BuyCond2 and ShortCond2 are secondary signals and triggers ONLY if prev trade was a main signal. There's must NOT be two secondary trades in a row. The pattern that triggers a secondary signal must NOT be inside the prev trade but if the last bar of a sec signal also triggers a main this new signal IS VALID.

Unfortunately I don't have a (correctly) working code from which to present example images so I will share
with you what I studied and did so far..

I started with this code which I follow from this YT video.

_SECTION_BEGIN("DCH intraday trading System");

//realtime signals 0,0,0,0(immediate execution)
SetTradeDelays(0,0,0,0); 

//Inputs controls
lenght = Param("Lenght",20,1,100,1);
stops  = Param("Stoploss",50,1,1000,1);
target = Param("Target",100,1,1000,1);
displayline = ParamToggle("Show Target & Stoploss","HIDE|SHOW",1);

//Intraday controls
starttime = ParamTime("signalStartTime","10:30");
endtime   = ParamTime("signalEndTime","17:00");
sqofftime = ParamTime("SquareoffTime","17:05");

//Build Donchinal Channel
upper = HHV(High,lenght);
lower = LLV(Low,lenght);

//One bar delay to the channel
upper = Ref(upper,-1);
lower = Ref(lower,-1);

//Plotting Donchian Channel
Plot(upper,"DCH upper",colorBlue,styleThick);
Plot(lower,"DCH lower",colorBlue,styleThick);

//Plot Candles
SetChartOptions(0,chartShowArrows | chartShowDates); //enable X - axis
Plot(Close,"Candles",colorDefault,styleCandle);

//Trading logic Buy & Sell
//Condicion de entrada para Longs
Buy = Cross(High,upper) AND TimeNum() >= starttime AND TimeNum() <= endtime;

//Condicion de salida
isell = Cross(lower,Low) OR TimeNum() == sqofftime;

Buy  = ExRem(Buy,isell);
Sell = ExRem(isell,Buy);

//Calculating Long entry price - Gap UP considered
BuyPrice = ValueWhen(Buy,Max(Open,upper)); //Calculating Long entry price - Gap UP considered

//Calculo de SL y TP
BuyStop   = BuyPrice - stops;
BuyTarget = BuyPrice + target;

//Condicion final de salida para Longs - Long Exits
Sell = isell OR Cross(High,BuyTarget) OR Cross(BuyStop,Low);

//Remove excessive signals
Buy  = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);

//Calculating sell price - Gap considered
SellPrice = ValueWhen(Sell,Min(Open,IIf(TimeNum()==sqofftime,Close,IIf(Cross(lower,Low),lower,
					IIf(Cross(High,BuyTarget),BuyTarget,IIf(Cross(BuyStop,Low),BuyStop,Close))))));

//Trading logic Short & Cover
//Condicion de entrada para Shorts
Short = Cross(lower,Low) AND TimeNum() >= starttime AND TimeNum() <= endtime;

//Condicion de salida
icover = Cross(High,upper) OR TimeNum() == sqofftime;

Short = ExRem(Short,icover);
Cover = ExRem(icover,Short);

//Calculating Short entry price - Gap Down considered
ShortPrice = ValueWhen(Short,Min(Open,lower));

//Calculo de SL y TP
ShortStop   = ShortPrice + stops;
ShortTarget = ShortPrice - target;

//Condicion final de salida para Shorts - Short Exits
Cover = icover OR Cross(ShortTarget,Low) OR Cross(High,ShortStop);

//Remove excessive signals
Short = ExRem(Short,Cover);
Cover = ExRem(Cover,Short);

//Calculating cover price - Gap considered
CoverPrice = ValueWhen(Cover,Max(Open,IIf(TimeNum()==sqofftime,Close,IIf(Cross(High,upper),upper,
				IIf(Cross(ShortTarget,Low),ShortTarget,IIf(Cross(High,ShortStop),ShortStop,Close))))));

//Plotting StopLoss and Target
if(displayline)
{
buycontinue   = Flip(Buy,Sell); //nos permite graficar SL/TP mientras la posicion este activa
shortcontinue = Flip(Short,Cover);

Plot(IIf(buycontinue,BuyStop,Null),"BuyStop",colorRed,styleDashed);
Plot(IIf(buycontinue,BuyTarget,Null),"BuyTarget",colorGreen,styleDashed);
Plot(IIf(buycontinue,BuyPrice,Null),"BuyEntry",colorYellow,styleDashed);

Plot(IIf(shortcontinue,ShortStop,Null),"ShortStop",colorRed,styleDashed);
Plot(IIf(shortcontinue,ShortTarget,Null),"ShortTarget",colorGreen,styleDashed);
Plot(IIf(shortcontinue,ShortPrice,Null),"ShortEntry",colorYellow,styleDashed);
}

//Plotting Signals on chart
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);                      
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45); 
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);                      
PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);

PlotShapes(Sell * shapestar, colorBrightGreen, 0, High, 12);
PlotShapes(Cover * shapestar, colorRed, 0, Low, -12);

_SECTION_END();

Then I started adding my own conditions.
For Main signals I want Close breaking the channels and added an EMA to filter.
For secondary signal the EMA filter reverse and finally sum up all signals:

isUP = Close > EMA(Close,200);
isDOWN = Close < EMA(Close,200);

oppBuy = Close > Ref(upper,-1) AND isUP; //Main Buy signal
oppShort = Close < Ref(lower,-1) AND isDOWN; //Main Short signal
oprBuy = Ref(Close,-1) > Ref(Open,-1) AND Close > Open AND isDOWN; //Sec Buy signal
oprShort = Ref(Close,-1) < Ref(Open,-1) AND Close < Open AND isUP; //Sec Short signal

BuyCond1 = Ref(oppBuy,-1);
BuyCond2 = Ref(oprBuy,-1);
iBuy = BuyCond1 OR BuyCond2;
Buy = iBuy AND TimeNum() >= starttime AND TimeNum() <= endtime;

ShortCond1 = Ref(oppShort,-1);
ShortCond2 = Ref(oprShort,-1);
iShort = ShortCond1 OR ShortCond2;
Short = iShort AND TimeNum() >= starttime AND TimeNum() <= endtime;

As I said I use fixed SL and TP for mains but for secs I use the same SL but for my target I choose VWAP, so I add it to the code. Also tried my best to sum up all my exit conditions inside the Sell and Cover expressions, also for SellPrice and CoverPrice. My final version was:

_SECTION_BEGIN("Intraday test");

//realtime signals 0,0,0,0(immediate execution)
SetTradeDelays(0,0,0,0); 

//Inputs controls
lenght = Param("Lenght",20,1,100,1);
stops  = Param("Stoploss",50,1,1000,1);
target = Param("Target",50,1,1000,1);
displayline = ParamToggle("Show Target & Stoploss","HIDE|SHOW",1);

//Intraday controls
starttime = ParamTime("signalStartTime","10:30");
endtime   = ParamTime("signalEndTime","17:00");
sqofftime = ParamTime("SquareoffTime","17:05");

//Build Donchinal Channel
upper = HHV(High,lenght);
lower = LLV(Low,lenght);
mid   = (upper + lower) / 2;

//VWAP
Bars_so_far_today = 1 + BarsSince( Day() != Ref(Day(), -1));
StartBar = ValueWhen(TimeNum() == 093000, BarIndex());
TodayVolume = Sum(V,Bars_so_far_today);
VWAP = IIf (BarIndex() >= StartBar, Sum (C * V, Bars_so_far_today  ) / TodayVolume,0);

//Plot Candles
SetChartOptions(0,chartShowArrows | chartShowDates); //enable X - axis
Plot(Close,"Candles",colorDefault,styleCandle);

isUP = Close > EMA(Close,200);
isDOWN = Close < EMA(Close,200);

//Trading logic Buy & Sell
oppBuy = Close > Ref(upper,-1) AND isUP; //Main Buy signal
oprBuy = Ref(Close,-1) > Ref(Open,-1) AND Close > Open AND isDOWN; //Sec Buy signal
BuyCond1 = Ref(oppBuy,-1);
BuyCond2 = Ref(oprBuy,-1);
iBuy = BuyCond1 OR BuyCond2;

Buy = iBuy AND TimeNum() >= starttime AND TimeNum() <= endtime;

//Calculating Long entry price
BuyPrice = ValueWhen(Buy,Open); //Calculating Long entry price - Gap UP considered

//Calculo de SL y TP
BuyStop   = BuyPrice - stops;
BuyTarget = BuyPrice + target;

//Condicion final de salida para Longs - Long Exits
Sell = IIf(BuyCond1, Cross(High,BuyTarget) OR Cross(BuyStop,Low),IIf(BuyCond2, Cross(High,VWAP) OR Cross(BuyStop,Low),Null));

//Remove excessive signals
Buy  = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);

//Calculating sell price
SellPrice = ValueWhen(Sell,IIf(TimeNum()==sqofftime,Close,IIf(Cross(High,BuyTarget),BuyTarget,
					IIf(Cross(BuyStop,Low),BuyStop,IIf(Cross(High,VWAP),VWAP,Close)))));

//Trading logic Short & Cover
oppShort = Close < Ref(lower,-1) AND isDOWN; //Main Short signal
oprShort = Ref(Close,-1) < Ref(Open,-1) AND Close < Open AND isUP; //Sec Short signal
ShortCond1 = Ref(oppShort,-1);
ShortCond2 = Ref(oprShort,-1);
iShort = ShortCond1 OR ShortCond2;

Short = iShort AND TimeNum() >= starttime AND TimeNum() <= endtime;

//Calculating Short entry price - Gap Down considered
ShortPrice = ValueWhen(Short,Open);

//Calculo de SL y TP
ShortStop   = ShortPrice + stops;
ShortTarget = ShortPrice - target;

//Condicion final de salida para Shorts - Short Exits
Cover = IIf(ShortCond1, Cross(BuyTarget,Low) OR Cross(High,ShortStop),IIf(ShortCond2, Cross(VWAP,Low) OR Cross(High,ShortStop),Null));

//Remove excessive signals
Short = ExRem(Short,Cover);
Cover = ExRem(Cover,Short);

//Calculating cover price - Gap considered
CoverPrice = ValueWhen(Cover,IIf(TimeNum()==sqofftime,Close,IIf(Cross(BuyTarget,Low),BuyTarget,
				IIf(Cross(High,ShortStop),ShortStop,IIf(Cross(VWAP,Low),VWAP,Close)))));


//Plotting Donchian Channel
Plot(upper,"DCH upper",colorBlue,styleThick);
Plot(lower,"DCH lower",colorBlue,styleThick);
Plot(mid,"DCH lower",colorOrange,styleThick);

//Plotting VWAP & EMA
Plot (VWAP,"VWAP",colorYellow, styleLine);
Plot(EMA(Close,200),"EMA",colorRed,styleThick);

//Plotting StopLoss and Target
if(displayline)
{
buycontinue   = Flip(Buy,Sell); //this let me plot while condition is true
shortcontinue = Flip(Short,Cover);

Plot(IIf(buycontinue,BuyStop,Null),"BuyStop",colorRed,styleDashed);
Plot(IIf(buycontinue,BuyTarget,Null),"BuyTarget",colorGreen,styleDashed);
Plot(IIf(buycontinue,BuyPrice,Null),"BuyEntry",colorYellow,styleDashed);

Plot(IIf(shortcontinue,ShortStop,Null),"ShortStop",colorRed,styleDashed);
Plot(IIf(shortcontinue,ShortTarget,Null),"ShortTarget",colorGreen,styleDashed);
Plot(IIf(shortcontinue,ShortPrice,Null),"ShortEntry",colorYellow,styleDashed);
}

//Plotting Signals on chart
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);                      
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45); 
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);                      
PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);

PlotShapes(Sell * shapestar, colorBrightGreen, 0, High, 12);
PlotShapes(Cover * shapestar, colorRed, 0, Low, -12);

_SECTION_END();

The final result was a plot mess

Looking for around I stumbled upon this thread and tried this out with the intention of resolving the SL and TP levels but leaving aside details of the logic such as the intermediate candle and the restrictions for secondary signals:

_SECTION_BEGIN("stopTest");

SetTradeDelays(0,0,0,0); 
SetOption("MaxOpenPositions", 1);
SetOption("ActivateStopsImmediately", True);

//**************************************************************************************************************
//Inputs controls
//**************************************************************************************************************
lenght  = Param("DCH Lenght",20,1,100,1);
oppStop = Param("OPP SL Ticks",50,1,1000,1);
oprStop = Param("OPR SL Ticks",50,1,1000,1);
target  = Param("Target Ticks",100,1,1000,1);
displayline = ParamToggle("Show Target & Stoploss","HIDE|SHOW",1);

//Intraday controls
starttime = ParamTime("signalStartTime","10:30");
endtime   = ParamTime("signalEndTime","17:00");
sqofftime = ParamTime("SquareoffTime","17:05");

TickSize = 0.25;

//**************************************************************************************************************
//Indicadores
//**************************************************************************************************************
//Build Donchinal Channel
upper = HHV(High,lenght);
lower = LLV(Low,lenght);
mid   = (upper + lower) / 2;

//**************************************************************************************************************
//VWAP
Bars_so_far_today = 1 + BarsSince( Day() != Ref(Day(), -1));
StartBar = ValueWhen(TimeNum() == 093000, BarIndex());
TodayVolume = Sum(V,Bars_so_far_today);
VWAP = IIf (BarIndex() >= StartBar, Sum (C * V, Bars_so_far_today  ) / TodayVolume,0);

//**************************************************************************************************************
//Plot Candles
SetChartOptions(0,chartShowArrows | chartShowDates); //enable X - axis
Plot(Close,"Close",colorDefault,styleCandle);

//**************************************************************************************************************
//Filter
inTime = TimeNum() >= starttime AND TimeNum() <= endtime;
isUP = Close > EMA(Close,200);
isDOWN = Close < EMA(Close,200);

//**************************************************************************************************************
//Condicion de entrada para OPP Longs
//**************************************************************************************************************
oppBuy = Close > Ref(upper,-1) AND isUP AND inTime;
oprBuy = Ref(Close,-1) > Ref(Open,-1) AND Close > Open AND isDOWN AND inTime;
isLong = oppBuy OR oprBuy;

//**************************************************************************************************************
//Condicion de entrada para OPP Shorts
oppShort = Close < Ref(lower,-1) AND isDOWN AND inTime;
oprShort = Ref(Close,-1) < Ref(Open,-1) AND Close < Open AND isUP AND inTime;
isShort = oppShort OR oprShort;

//**************************************************************************************************************
BuyCond1 = Ref(oppBuy,-1);
BuyCond2 = Ref(oprBuy,-1);
ShortCond1 = Ref(oppShort,-1);
ShortCond2 = Ref(oprShort,-1);
timeOut = TimeNum() == sqofftime;

Buy = BuyCond1 OR BuyCond2;
Short = ShortCond1 OR ShortCond2;
Sell = Cover = 0;

//ExRem(Buy, Sell);
//ExRem(Short, Cover);

//Levels
entryBuy = ValueWhen(Buy, Open);
entryShort = ValueWhen(Short, Open);
BuyStop = entryBuy - oppStop;
BuyTarget = entryBuy + target;
ShortStop = entryShort + oppStop;
ShortTarget = entryShort - target;

stopLine = IIf(isLong,BuyStop,IIf(isShort,ShortStop,Null));
targetLine = IIf(isLong,IIf(oppBuy,BuyTarget,VWAP),IIf(oppShort,ShortTarget,VWAP));

ApplyStop(stopTypeLoss, stopModePoint, stopLine, 1, False);
ApplyStop(stopTypeProfit, stopModePoint, targetLine, 1, False);

Equity(1,0);

//**************************************************************************************************************
//Plotting EMA
Plot(EMA(Close,200),"EMA",colorRed,styleThick);

//Plotting Donchian Channel
Plot(upper,"DCH upper",colorBlue,styleThick);
Plot(lower,"DCH lower",colorBlue,styleThick);
Plot(mid,"DCH mid",colorOrange,styleLine);

//Plotting VWAP
//Plot (VWAP,"VWAP",colorYellow, styleLine);

//Plotting levels and signals
buycontinue   = Flip(Buy,Sell);
shortcontinue = Flip(Short,Cover);

Plot(IIf(buycontinue,BuyStop,Null),"BuyStop",colorRed,styleDashed);
Plot(IIf(buycontinue,BuyTarget,Null),"BuyTarget",colorGreen,styleDashed);
Plot(IIf(buycontinue,entryBuy,Null),"BuyEntry",colorYellow,styleDashed);

Plot(IIf(shortcontinue,ShortStop,Null),"ShortStop",colorRed,styleDashed);
Plot(IIf(shortcontinue,ShortTarget,Null),"ShortTarget",colorGreen,styleDashed);
Plot(IIf(shortcontinue,entryShort,Null),"ShortEntry",colorYellow,styleDashed);

PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorRed, 0, H, Offset=-40);

_SECTION_END();

No luck and started to desperate

Then tried to wet my feet with flow control with IF-ELSE and made this attempt to assign each type of
signal their own stop and target (without trying the intermediate bar between main signals and sec trigger restriccion) I used this thread as base:

_SECTION_BEGIN("DCH WIP5");

SetTradeDelays(0,0,0,0); 
SetOption("MaxOpenPositions", 1);

//**************************************************************************************************************
//Inputs controls
//**************************************************************************************************************
lenght  = Param("DCH Lenght",20,1,100,1);
oppStop = Param("SL Pts",50,1,1000,1);
//oprStop = Param("OPR SL Ticks",200,1,1000,1);
target  = Param("TP Pts",100,1,1000,1);
displayline = ParamToggle("Show Target & Stoploss","HIDE|SHOW",1);

//Intraday controls
starttime = ParamTime("signalStartTime","10:30");
endtime   = ParamTime("signalEndTime","17:00");
sqofftime = ParamTime("SquareoffTime","17:05");

TickSize = 0.25;

//**************************************************************************************************************
//Indicadores
//**************************************************************************************************************
//Build Donchinal Channel
upper = HHV(High,lenght);
lower = LLV(Low,lenght);
mid   = (upper + lower) / 2;

//**************************************************************************************************************
//VWAP
Bars_so_far_today = 1 + BarsSince( Day() != Ref(Day(), -1));
StartBar = ValueWhen(TimeNum() == 093000, BarIndex());
TodayVolume = Sum(V,Bars_so_far_today);
VWAP = IIf (BarIndex() >= StartBar, Sum (C * V, Bars_so_far_today  ) / TodayVolume,0);

//**************************************************************************************************************
//Plot Candles
SetChartOptions(0,chartShowArrows | chartShowDates); //enable X - axis
Plot(Close,"Candles",colorDefault,styleCandle);

//**************************************************************************************************************
//Filters
inTime = TimeNum() >= starttime AND TimeNum() <= endtime;
isUP = Close > EMA(Close,200);
isDOWN = Close < EMA(Close,200);

//**************************************************************************************************************
//Condicion de entrada para OPP Longs
oppBuy = Close > Ref(upper,-1) AND isUP AND inTime;
oprBuy = Ref(Close,-1) > Ref(Open,-1) AND Close > Open AND isDOWN AND inTime;
//isLong = oppBuy OR oprBuy;
//**************************************************************************************************************
//Condicion de entrada para OPP Shorts
oppShort = Close < Ref(lower,-1) AND isDOWN AND inTime;
oprShort = Ref(Close,-1) < Ref(Open,-1) AND Close < Open AND isUP AND inTime;
//isShort = oppShort OR oprShort;
//**************************************************************************************************************
BuyCond1 = Ref(oppBuy,-1);
BuyCond2 = Ref(oprBuy,-1);
ShortCond1 = Ref(oppShort,-1);
ShortCond2 = Ref(oprShort,-1);
timeOut = TimeNum() == sqofftime;

Buy = BuyCond1 OR BuyCond2;
Short = ShortCond1 OR ShortCond2;
Sell = Cover = 0;
inTrade = False;
entryPrice = 0;
BuyStop = 0;
BuyTarget = 0;
ShortStop =0;
ShortTarget = 0;
isell = 0;
icover = 0;
Buy  = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);

for (i = 0; i < BarCount; i++)
{
	if (inTrade)
	{		
		if (BuyCond1[i])
		{
			BuyPrice[i] = Open[i];
			entryPrice = BuyPrice [i];
			BuyStop = entryPrice - oppStop;
			BuyTarget = entryPrice + target;
			//isell = Cross(BuyStop,Low) OR Cross(High,BuyTarget) OR TimeNum() == sqofftime;
			
			if(BuyStop > Low[i])
				Sell[i] = True;
				SellPrice[i] = Low[i];
				inTrade = False;
				entryPrice = 0;
			if(High[i] > BuyTarget)
				Sell[i] = True;
				SellPrice[i] = High[i];
				inTrade = False;
				entryPrice = 0;
		}
		else
		{ 
			if (BuyCond2[i])
				BuyPrice[i] = Open[i];
				entryPrice = BuyPrice [i];
				BuyStop = entryPrice - oppStop;
				BuyTarget = VWAP;
				//isell = Cross(BuyStop,Low) OR Cross(High,BuyTarget) OR TimeNum() == sqofftime;
				
				if(BuyStop > Low[i])
					Sell[i] = True;
					SellPrice[i] = Low[i];
					inTrade = False;
					entryPrice = 0;
				if(High[i] > BuyTarget)
					Sell[i] = True;
					SellPrice[i] = High[i];
					inTrade = False;
					entryPrice = 0;
		}
		 if (ShortCond1[i])
			ShortPrice[i] = Open[i];
			entryPrice = ShortPrice [i];
			ShortStop = entryPrice + oppStop;
			ShortTarget = entryPrice - target;
			//icover = Cross(High,ShortStop) OR Cross(ShortTarget,Low) OR TimeNum() == sqofftime;
			
			if(High[i] > ShortStop)
				Sell[i] = True;
				SellPrice[i] = High[i];
				inTrade = False;
				entryPrice = 0;
			if(ShortTarget > Low[i])
				Sell[i] = True;
				SellPrice[i] = Low[i];
				inTrade = False;
				entryPrice = 0;
		}		
		else 
		{
			if (ShortCond2[i])
				ShortPrice[i] = Open[i];
				entryPrice = ShortPrice [i];
				ShortStop = entryPrice + oppStop;
				ShortTarget = VWAP;
				icover = Cross(High,ShortStop) OR Cross(ShortTarget,Low) OR TimeNum() == sqofftime;
				
				if(High[i] > ShortStop)
					Sell[i] = True;
					SellPrice[i] = High[i];
					inTrade = False;
					entryPrice = 0;
				if(ShortTarget[i] > Low[i])
					Sell[i] = True;
					SellPrice[i] = Low[i];
					inTrade = False;
					entryPrice = 0;

		}		
		if (timeOut[i])
		{
			Sell [i] = True;
			Cover [i] = True;
			SellPrice [i] = Close;
			CoverPrice [i] = Close;
			inTrade = False;
			entryPrice = 0;
		}
		
		Buy [i] = 0;
		Short [i] = 0;
		
		if (Buy [i] OR Short [i])
		{
			inTrade = True;			
		}
}

//Remove excessive signals
Short = ExRem(Short,Cover);
Cover = ExRem(Cover,Short);

 /*
AddColumn(oppBuy,"oppBuy",1.0,colorDefault,colorDefault,-1,Null);
AddColumn(oppShort,"oppShort",1.0,colorDefault,colorDefault,-1,Null);
AddColumn(oprBuy,"oprBuy",1.0,colorDefault,colorDefault,-1,Null);
AddColumn(oprShort,"oprShort",1.0,colorDefault,colorDefault,-1,Null);
*/

//**************************************************************************************************************
//Plotting
//**************************************************************************************************************
//Plotting Donchian Channel
Plot(upper,"DCH upper",colorBlue,styleThick);
Plot(lower,"DCH lower",colorBlue,styleThick);
Plot(mid,"DCH mid",colorOrange,styleLine);

//Plotting VWAP
Plot (VWAP,"VWAP",colorYellow, styleLine);
Plot(EMA(Close,200),"EMA",colorRed,styleThick);

//Plotting StopLoss and Target

if(displayline)
{
buycontinue = Flip(Buy,Sell);
shortcontinue = Flip(Short,Cover);

Plot(IIf(buycontinue,BuyStop,Null),"BuyStop",colorRed,styleDashed);
Plot(IIf(buycontinue,BuyTarget,Null),"BuyTarget",colorGreen,styleDashed);
Plot(IIf(buycontinue,entryPrice,Null),"BuyEntry",colorYellow,styleDashed);

Plot(IIf(shortcontinue,ShortStop,Null),"ShortStop",colorRed,styleDashed);
Plot(IIf(shortcontinue,ShortTarget,Null),"ShortTarget",colorGreen,styleDashed);
Plot(IIf(shortcontinue,entryPrice,Null),"ShortEntry",colorYellow,styleDashed);
}

//Plotting Signals on chart
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);                      
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45); 

PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);                      
PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);

PlotShapes(Sell * shapestar, colorBrightGreen, 0, High, 12);
PlotShapes(Cover * shapestar, colorRed, 0, Low, -12);

_SECTION_END();

This Doesn't work either. The first I noticed was it took several minutes to load the chart, may be my wonky code made it more difficult to calculate the whole thing. While coding I faced various errors produced by my wrong undertending using IF-ELSE statement, but also errors that I don't fully understand.
For ex why it flag an error in a sentence that in logic is exactly the same as a previous one and in that one I had no errors, obviously I missing something..

I must admint that other thing confuses me is read so many examples about IF-ELSE where some users writed very organized indented code while other doesn't indent at all or the statement is right next to the IF() condition.
Tell me if I need to document more about something also I can add tradingview images of this idea working for visual reference if anyone think it helps.

Thanks in advance!

@Nerv, Amibroker uses the same syntax of the C language for the braces { }

AFL Reference Manual (near 3/4th down)

Compound statements (Blocks)
 
A compound statement consists of zero or more statements enclosed in curly braces ({ }). A compound statement can be used anywhere a statement is expected. Compound statements are commonly called “blocks.”
 
{
 
    statement1;

    ....

    statementN;
 
}
 
(this is 'borrowed' from C language, users of other programming languages are used to use BEGIN for { and END for } )
 
In your posted code you are missing a lot of opening and closing braces. This is not Python. Indenting code makes it more clear to understand but what matter here are the opening and closing braces

Ignoring what you are actually trying to do, for example (this maybe not what you want to achieve...) a snippet from your code could be changed to:

if( inTrade )
    {
        if( BuyCond1[i] )
        {
            BuyPrice[i] = Open[i];
            entryPrice = BuyPrice [i];
            BuyStop = entryPrice - oppStop;
            BuyTarget = entryPrice + target;
            //isell = Cross(BuyStop,Low) OR Cross(High,BuyTarget) OR TimeNum() == sqofftime;

            if( BuyStop > Low[i] )
            {  // the following 4 lines are logically a single block
                Sell[i] = True;
                SellPrice[i] = Low[i];
                inTrade = False;
                entryPrice = 0;
            }

            if( High[i] > BuyTarget )
            {  // again as above
                Sell[i] = True;
                SellPrice[i] = High[i];
                inTrade = False;
                entryPrice = 0;
            }
        }
        else
        {
             .....

If you do not delimit the "blocks" with the correct braces only the 1st line after the conditional is executed based on the IF condition and the following lines are executed anyway (the indent does not matter at all!).

The Ambroker editor has a very useful feature to properly format the code: you'll find it under the "Edit" menu: "Prettify Selection".
The same piece of code, reformatted by this tool looks like this:

for( i = 0; i < BarCount; i++ )
{
    if( inTrade )
    {
        if( BuyCond1[i] )
        {
            BuyPrice[i] = Open[i];
            entryPrice = BuyPrice [i];
            BuyStop = entryPrice - oppStop;
            BuyTarget = entryPrice + target;
            //isell = Cross(BuyStop,Low) OR Cross(High,BuyTarget) OR TimeNum() == sqofftime;

            if( BuyStop > Low[i] )
                Sell[i] = True;

            SellPrice[i] = Low[i];
            inTrade = False;
            entryPrice = 0;

            if( High[i] > BuyTarget )
                Sell[i] = True;

            SellPrice[i] = High[i];
            inTrade = False;
            entryPrice = 0;
        }
        else
        {
            .....

Here you can clearly see that code with the missing braces after the conditional IFs probably is not doing what you want to achieve!

3 Likes

@Nerv , the C rules for braces can be confusing since there are situations in which you can omit them.

I suggest reading this discussion in StackOverflow to understand them better.

The discussion is specific to C but essentially the same rules applies to AFL.
In any case, I suggest studying carefully the examples you'll find in the forum, and using the "Prettify Selection Tool" to verify your code: sometimes I employ it also as a debug tool (see point .5) to find unwanted missing braces (or double-typed ones).

In general, especially as a beginner, it is always better to be verbose enclosing also single statements in braces.

Btw, a related problem was discussed in this old thread.

2 Likes

Thanks for your reply and you guide about this. I'll rewrite my If-else code, definitely will check "Prettify" and the StackOverflow thread.
I will update my situation!

@beppe
I decided to go baby steps to understand the basics right so I take the Basic idea and made a new code.
Only 1 buy and 1 short conditions. Fixed TP and SL implementing ApplyStop() and plot it.
Also tried to set up the trading parameters from the beginning.
I'm trading futures, 2 contracts per trade, 1 trade open MAX... Any advise about this section or how should I define this kind of things is welcome!
(used this post as reference)

_SECTION_BEGIN("DCH intraday trading System");

//realtime signals 0,0,0,0(immediate execution)
//SetTradeDelays(1,0,1,0);
SetOption("InitialEquity",100000);
SetOption("AllowSameBarExit",True);
SetOption("ActivateStopsImmediately",True);
SetOption("MaxOpenPositions", 1);
SetOption("CommissionMode",2);
SetOption("CommissionAmount",0.5);
SetOption("AllowPositionShrinking", True);
SetPositionSize(2,spsShares);
//TickSize = 0.25;

//Inputs controls
lenght = Param("Lenght",20,1,100,1);
stop = Param("Stoploss",25,1,1000,1);
target = Param("Target",50,1,1000,1);
displayline = ParamToggle("Show Target & Stoploss","HIDE|SHOW",1);

//Intraday controls
starttime = ParamTime("signalStartTime","10:30");
endtime   = ParamTime("signalEndTime","17:00");
sqofftime = ParamTime("SquareoffTime","17:05");

//Build Donchinal Channel
upper = HHV(High,lenght);
lower = LLV(Low,lenght);

//Plotting Donchian Channel
Plot(upper,"DCH upper",colorBlue,styleThick);
Plot(lower,"DCH lower",colorBlue,styleThick);

//Plot Candles
SetChartOptions(0,chartShowArrows | chartShowDates); //enable X - axis
Plot(Close,"Candles",colorDefault,styleCandle);

//Trading logic Buy & Sell
//Condicion de entrada para Longs
BuyCond1 = Close > Ref(upper,-1) AND Close > EMA(Close,200);
ShortCond1 = Close < Ref(lower,-1) AND Close < EMA(Close,200);

Buy = Ref(BuyCond1,-1);
Short = Ref(ShortCond1,-1);
Sell = Cover = 0;
BuyPrice = ShortPrice = Open;

InTrade_Long = Flip( Buy, Sell );
InTrade_Short = Flip( Short, Cover );

//Longs
EP_Long = ValueWhen( Buy, BuyPrice );
StopLevel_Long = stop;
Stopline_Long = IIf( InTrade_Long, EP_Long - StopLevel_Long, Null );
Plot( Stopline_Long, "BuyStop", colorRed );

TgtLevel_Long = target;// points ($)
TgtLine_Long  = IIf( InTrade_Long, EP_Long + TgtLevel_Long, Null );
Plot( TgtLine_Long, "BuyTarget", colorGreen );

//Shorts
EP_Short = ValueWhen( Short, ShortPrice );
StopLevel_Short = stop; // points ($)
Stopline_Short = IIf( InTrade_Short, EP_Long - StopLevel_Long, Null );
Plot( Stopline_Short, "ShortStop", colorRed );

TgtLevel_Short = target;// points ($)
TgtLine_Short  = IIf( InTrade_Short, EP_Long + TgtLevel_Long, Null );
Plot( TgtLine_Short, "ShortTarget", colorGreen );

//stops
ApplyStop( stopTypeLoss, stopModePoint, stop, 1, True );
ApplyStop( stopTypeProfit, stopModePoint, target, 1, True );

Equity(1); // THIS EVALUATES STOPS

//Plotting StopLoss and Target
Plot(EMA(Close,200),"EMA",colorRed,styleThick);

//Plotting Signals on chart
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);                      
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45); 
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);                      
PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);

PlotShapes(Sell * shapestar, colorBrightGreen, 0, High, 12);
PlotShapes(Cover * shapestar, colorRed, 0, Low, -12);

_SECTION_END();

I encountered 2 Issues with this code:
1- SL/TP lines plotted are continuous
2- Trades in report doesn't exit at SL or TP.

Can you guide me in the right direction?

@Nerv, pretty wide baby steps!

Anyway, try moving up these lines:

//stops
ApplyStop( stopTypeLoss, stopModePoint, stop, 1, True );
ApplyStop( stopTypeProfit, stopModePoint, target, 1, True );

Equity(1); // THIS EVALUATES STOPS

directly below this line:

BuyPrice = ShortPrice = Open;

The Equity() function is the one that evaluates the Stops and, as well explained in the last post the thread you referenced, generates the Sell signals!

2 Likes

@beppe Thanks for your reply!
With these changes it seems to plot a bit better but exit levels doesn't change.
Here a chart pic with the trade list for just the last trades in the chart:


The white circles highlight what seems to be sell and cover indications.

Here a capture BEFORE the change so you can see how plots looked like (same timestamp):

Small UPDATE:
Managed to plot it almost correctly.. SL & TP lines extends over opposite trades, like this:

So i tried adding one more Flip() for each InTreade

_SECTION_BEGIN("DCH intraday trading System");

SetOption("InitialEquity",100000);
SetOption("AllowSameBarExit",True);
SetOption("ActivateStopsImmediately",True);
SetOption("MaxOpenPositions", 1);
SetOption("CommissionMode",2);
SetOption("CommissionAmount",0.5);
SetOption("AllowPositionShrinking", True);
SetPositionSize(2,spsShares);

//Inputs controls
lenght = Param("Lenght",20,1,100,1);
stop = Param("Stoploss",25,1,1000,1);
target = Param("Target",50,1,1000,1);
displayline = ParamToggle("Show Target & Stoploss","HIDE|SHOW",1);

//Intraday controls
starttime = ParamTime("signalStartTime","10:30");
endtime   = ParamTime("signalEndTime","17:00");
sqofftime = ParamTime("SquareoffTime","17:05");

//Build Donchinal Channel
upper = HHV(High,lenght);
lower = LLV(Low,lenght);

//Plotting Donchian Channel
Plot(upper,"DCH upper",colorBlue,styleThick);
Plot(lower,"DCH lower",colorBlue,styleThick);

//Plot Candles
SetChartOptions(0,chartShowArrows | chartShowDates); //enable X - axis
Plot(Close,"Candles",colorDefault,styleCandle);

//Trading logic Buy & Sell
BuyCond1 = Close > Ref(upper,-1) AND Close > EMA(Close,200);
ShortCond1 = Close < Ref(lower,-1) AND Close < EMA(Close,200);

Buy = Ref(BuyCond1,-1);
Short = Ref(ShortCond1,-1);
Sell = Cover = 0;
BuyPrice = ShortPrice = Open;

//stops
ApplyStop( stopTypeLoss, stopModePoint, stop, 1, True );
ApplyStop( stopTypeProfit, stopModePoint, target, 1, True );

Equity(1); // THIS EVALUATES STOPS

InTrade_Long = Flip( Buy, Sell ) AND Flip( Buy, Short );
InTrade_Short = Flip( Short, Cover ) AND Flip( Short, Buy );

//Longs
EP_Long = ValueWhen( Buy, BuyPrice );
StopLevel_Long = stop;
Stopline_Long = IIf( InTrade_Long, EP_Long - StopLevel_Long, Null );
Plot( Stopline_Long, "BuyStop", colorRed );

TgtLevel_Long = target;
TgtLine_Long  = IIf( InTrade_Long, EP_Long + TgtLevel_Long, Null );
Plot( TgtLine_Long, "BuyTarget", colorGreen );

//Shorts
EP_Short = ValueWhen( Short, ShortPrice );
StopLevel_Short = stop; 
Stopline_Short = IIf( InTrade_Short, EP_Short + StopLevel_Short, Null );
Plot( Stopline_Short, "ShortStop", colorRed );

TgtLevel_Short = target;
TgtLine_Short  = IIf( InTrade_Short, EP_Short - TgtLevel_Short, Null );
Plot( TgtLine_Short, "ShortTarget", colorGreen );

//Plotting StopLoss and Target
Plot(EMA(Close,200),"EMA",colorRed,styleThick);

//Plotting Signals on chart
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);                      
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45); 
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);                      
PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);

PlotShapes(Sell * shapestar, colorBrightGreen, 0, High, 12);
PlotShapes(Cover * shapestar, colorRed, 0, Low, -12);

_SECTION_END();

And plotting looks like right now:

Working in exits prices now

UPDATE on backtest results:
All signals are OK exiting at SL or TP except those trades that doesn't reach them before a new signal appear, in that case trade reverses.
I would like to avoid this, in other worlds I want trades to stay open until reach SL or TP.
Here's is the updated code so far:

_SECTION_BEGIN("DCH Basico");

SetOption("InitialEquity",100000);
SetOption("AllowSameBarExit",True);
SetOption("ActivateStopsImmediately",True);
SetOption("MaxOpenPositions", 1);
SetOption("CommissionMode",2);
SetOption("CommissionAmount",0.5);
SetOption("AllowPositionShrinking", True);
SetPositionSize(2,spsShares);

TickSize = 0.25;
PointValue = 2;

//Inputs controls
lenght = Param("Lenght",20,1,100,1);
stop = Param("Stoploss",25,1,1000,1);
target = Param("Target",50,1,1000,1);
displayline = ParamToggle("Show Target & Stoploss","HIDE|SHOW",1);

//Intraday controls
starttime = ParamTime("signalStartTime","10:30");
endtime   = ParamTime("signalEndTime","17:00");
sqofftime = ParamTime("SquareoffTime","17:05");

//Build Donchinal Channel
upper = HHV(High,lenght);
lower = LLV(Low,lenght);

//Plotting Donchian Channel
Plot(upper,"DCH upper",colorBlue,styleThick);
Plot(lower,"DCH lower",colorBlue,styleThick);

//Plot Candles
SetChartOptions(0,chartShowArrows | chartShowDates); //enable X - axis
Plot(Close,"Candles",colorDefault,styleCandle);

//Trading logic Buy & Sell
BuyCond1 = Close > Ref(upper,-1) AND Close > EMA(Close,200);
ShortCond1 = Close < Ref(lower,-1) AND Close < EMA(Close,200);

Buy = Ref(BuyCond1,-1);
Short = Ref(ShortCond1,-1);
Sell = 0;
Cover = 0;
BuyPrice = ShortPrice = Open;

//stops
ApplyStop( stopTypeLoss, stopModePoint, stop, 1, True );
ApplyStop( stopTypeProfit, stopModePoint, target, 1, True );

Equity(1); // THIS EVALUATES STOPS

InTrade_Long = Flip( Buy, Sell ) AND Flip( Buy, Short );
InTrade_Short = Flip( Short, Cover ) AND Flip( Short, Buy );

//Longs
EP_Long = ValueWhen( Buy, BuyPrice );
StopLevel_Long = stop;
Stopline_Long = IIf( InTrade_Long, EP_Long - StopLevel_Long, Null );
Plot( Stopline_Long, "BuyStop", colorRed );
check_BSL = IIf(Low < Stopline_Long, 1, 0);

TgtLevel_Long = target;
TgtLine_Long  = IIf( InTrade_Long, EP_Long + TgtLevel_Long, Null );
Plot( TgtLine_Long, "BuyTarget", colorGreen );
check_BTP = IIf(High > TgtLine_Long, 1, 0);

//Shorts
EP_Short = ValueWhen( Short, ShortPrice );
StopLevel_Short = stop; 
Stopline_Short = IIf( InTrade_Short, EP_Short + StopLevel_Short, Null );
Plot( Stopline_Short, "ShortStop", colorRed );
check_SSL = IIf(High > Stopline_Short, 1, 0);

TgtLevel_Short = target;
TgtLine_Short  = IIf( InTrade_Short, EP_Short - TgtLevel_Short, Null );
Plot( TgtLine_Short, "ShortTarget", colorGreen );
check_STP = IIf(Low < TgtLine_Short, 1, 0);

//Plotting StopLoss and Target
Plot(EMA(Close,200),"EMA",colorRed,styleThick);

//Plotting Signals on chart
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);                      
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45); 
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);                      
PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);

PlotShapes(Sell * shapestar, colorBrightGreen, 0, High, 12);
PlotShapes(Cover * shapestar, colorRed, 0, Low, -12);

//Exploration
filter = 1;

AddColumn( Close, "Close" );
AddColumn( Open, "Open" );

AddColumn( Buy, "Buy", 1, colorDefault, IIf(Buy == 1, colorYellow, colorDefault ));
AddColumn( BuyPrice, "BuyPrice" );
AddColumn( EP_Long, "EP_Long" );
AddColumn( check_BSL, "check_BSL", 1, colorDefault, IIf(check_BSL == 1, colorRed, colorDefault ));
AddColumn( check_BTP, "check_BTP", 1, colorDefault, IIf(check_BTP == 1, colorGreen, colorDefault ));
AddColumn( Stopline_Long, "BuyStop" );
AddColumn( TgtLine_Long, "BuyTarget" );
AddColumn( Sell, "Sell", 1, colorDefault, IIf(Sell != 0, colorOrange, colorDefault ));
AddColumn( SellPrice, "SellPrice" );

AddColumn( Short, "Short", 1, colorDefault, IIf(Short == 1, colorYellow, colorDefault ));
AddColumn( ShortPrice, "ShortPrice" );
AddColumn( EP_Short, "EP_Short" );
AddColumn( check_SSL, "check_SSL", 1, colorDefault, IIf(check_SSL == 1, colorRed, colorDefault ));
AddColumn( check_STP, "check_STP", 1, colorDefault, IIf(check_STP == 1, colorGreen, colorDefault ));
AddColumn( Stopline_Short, "ShortStop" );
AddColumn( TgtLine_Short, "ShortTarget" );
AddColumn( Cover, "Cover", 1, colorDefault, IIf(Cover != 0, colorOrange, colorDefault ));
AddColumn( CoverPrice, "CoverPrice" );

_SECTION_END();

Here the Backtest Setting I'm using:



Side Question:
Is PointValue the dollar amount $$ for the current ticker when a full point changed?
In my case MNQ has a tick size = 0.25 and tick value = $0.5
Is in this example PointValue = $2. Am I understanding this right?

Thank in advance!

Try turning this option off:

2 Likes

Thanks man! I feel kinda stupid tbh but now I've a working code to build up my original Logic.
I will work on the conditional flow and keep this thread updated.

Update
After an hiatus I could back to work with this strat and manage to achieve a working code using IF-ESLE using braces as suggested in @beppe link.
I used my main conditions to start.

for( i = 0; i < BarCount; i++ )
{
    if( EP_Long == 0 && Buy[ i ] ) //LONGS
		if( BuyCond1[ i ] )
		{
		EP_Long = BuyPrice[ i ];
		BuyTarget = EP_Long + target;
		BuyStop = EP_Long - stop;
		}
		if( EP_Long > 0 && High[ i ] > BuyTarget )
		{
		Sell[ i ] = 1;
		SellPrice[ i ] = BuyTarget;
		EP_Long = 0;
		}
		if( EP_Long > 0 && low[ i ] < BuyStop )
		{
		Sell[ i ] = 1;
		SellPrice[ i ] = BuyStop;
		EP_Long = 0;
		}
	if( EP_Short == 0 && Short[ i ] ) //SHORTS
		if( ShortCond1[ i ] )
		{
		EP_Short = ShortPrice[ i ];
		ShortTarget = EP_Short - target;
		ShortStop = EP_Short + stop;
		}
		if( EP_Short > 0 && Low[ i ] < ShortTarget )
		{
		Cover[ i ] = 1;
		CoverPrice[ i ] = ShortTarget;
		EP_Short = 0;
		}
			
		if( EP_Short > 0 && High[ i ] > ShortStop )
		{
		Cover[ i ] = 1;
		CoverPrice[ i ] = ShortStop;
		EP_Short = 0;
		}

	if( EP_Long > 0 && sqoff[ i ] ) //Exit all positions if time session ends
	{
	Sell[ i ] = 1;
	SellPrice[ i ] = Open[i];
	EP_Long = 0;
	}
	if( EP_Short > 0 && sqoff[ i ] )
	{
	Cover[ i ] = 1;
	CoverPrice[ i ] = Open[i];
	EP_Short = 0;
	}
}

I'm having a hard time to identify what kind of trade closed to allow or not the following trade.

1 Like

I was testing different methods to identify what type of operation was closed to allow or not to open the next operation.
I stuck to the simplest things to avoid complicating things.
In the following loop I only managed the Primary Conditions (OPPs) and want to avoid a new trade when the prev trade closed in the signal bar for a new trade.
To clarify this criteria here is a pic:

To tackle this I declared FALSE a variable named wasOPP:

Buy = BuyCond1; // OR BuyCond2;
Short = ShortCond1; // OR ShortCond2;
Sell = 0;
Cover = 0;
BuyPrice = Open;
ShortPrice = Open;
SellPrice = 0;
CoverPrice = 0;
EP_Long = 0;
BuyStop = 0;
BuyTarget = 0;
EP_Short = 0;
ShortStop = 0;
ShortTarget = 0;

wasOPP = False; //Test Var

for( i = 200; i < BarCount; i++ )
{
	
    if( EP_Long == 0 AND Buy[ i ] AND NOT wasOPP[ i-1 ] ) //LONGS
		
		if( BuyCond1[ i ] )
		{
		EP_Long = BuyPrice[ i ];
		BuyTarget = EP_Long + target;
		BuyStop = EP_Long - stop;
		}
		
		if( EP_Long > 0 AND High[ i ] > BuyTarget ) //Long TP?
		{
		Sell[ i ] = 1;
		SellPrice[ i ] = BuyTarget;
		EP_Long = 0;
                //wasOPP[i] = True;
		}
		
		if( EP_Long > 0 AND low[ i ] < BuyStop ) //Long SL?
		{
		Sell[ i ] = 1;
		SellPrice[ i ] = BuyStop;
		EP_Long = 0;
                //wasOPP[i] = True;
		}
		
		if( Sell[ i ] )
		wasOPP[i] = True;

		
	if( EP_Short == 0 AND Short[ i ] AND NOT wasOPP[ i-1 ] ) //SHORTS
			
		if( ShortCond1[ i ] )
		{
		EP_Short = ShortPrice[ i ];
		ShortTarget = EP_Short - target;
		ShortStop = EP_Short + stop;
		}
		
		if( EP_Short > 0 AND Low[ i ] < ShortTarget ) //Short TP?
		{
		Cover[ i ] = 1;
		CoverPrice[ i ] = ShortTarget;
		EP_Short = 0;
                //wasOPP[i] = True;
		}
			
		if( EP_Short > 0 AND High[ i ] > ShortStop ) //Short SL?
		{
		Cover[ i ] = 1;
		CoverPrice[ i ] = ShortStop;
		EP_Short = 0;
                //wasOPP[i] = True;
		}
		
		if( Cover[ i ] )
		wasOPP[i] = True;

	if( EP_Long > 0 AND sqoff[ i ] ) //Exit all positions if time session ends
	{
	Sell[ i ] = 1;
	SellPrice[ i ] = Open[i];
	EP_Long = 0;
        //wasOPP[i] = True;
	}
	
	if( EP_Short > 0 AND sqoff[ i ] )
	{
	Cover[ i ] = 1;
	CoverPrice[ i ] = Open[i];
	EP_Short = 0;
        //wasOPP[i] = True;
	}
	
	if( Cover[ i ] OR Sell [ i ] )
	wasOPP[i] = True;

}

I commented wasOPP[i] = True inside the TPs/SLs Check to ensures its only TRUE when Sell or Cover are true and added the lookback condition [i-1] to verify its status.
I didn't work.. In explorer it shows TRUE in bars where Sell/Cover are Zero.

-Am I using the lookback [i-1] wrong?
-Am I not undertending the status of Sell and Cover?

This is key because my next step is add Secondary Buy/Short Condition and those are restricted as well

Thanks in advance for your help!

I did not check your logic, but only because of your identation, I believe you missed some {}

Buy = BuyCond1; // OR BuyCond2;
Short = ShortCond1; // OR ShortCond2;
Sell = 0;
Cover = 0;
BuyPrice = Open;
ShortPrice = Open;
SellPrice = 0;
CoverPrice = 0;
EP_Long = 0;
BuyStop = 0;
BuyTarget = 0;
EP_Short = 0;
ShortStop = 0;
ShortTarget = 0;

wasOPP = False; //Test Var

for( i = 200; i < BarCount; i++ )
{
	
    if( EP_Long == 0 AND Buy[ i ] AND NOT wasOPP[ i-1 ] ) //LONGS
   { //missed	
		if( BuyCond1[ i ] )
		{
		EP_Long = BuyPrice[ i ];
		BuyTarget = EP_Long + target;
		BuyStop = EP_Long - stop;
		}
		
		if( EP_Long > 0 AND High[ i ] > BuyTarget ) //Long TP?
		{
		Sell[ i ] = 1;
		SellPrice[ i ] = BuyTarget;
		EP_Long = 0;
                //wasOPP[i] = True;
		}
		
		if( EP_Long > 0 AND low[ i ] < BuyStop ) //Long SL?
		{
		Sell[ i ] = 1;
		SellPrice[ i ] = BuyStop;
		EP_Long = 0;
                //wasOPP[i] = True;
		}
		
		if( Sell[ i ] )
		wasOPP[i] = True;

        } //missed	
		
	if( EP_Short == 0 AND Short[ i ] AND NOT wasOPP[ i-1 ] ) //SHORTS
       { //missed	
			
		if( ShortCond1[ i ] )
		{
		EP_Short = ShortPrice[ i ];
		ShortTarget = EP_Short - target;
		ShortStop = EP_Short + stop;
		}
		
		if( EP_Short > 0 AND Low[ i ] < ShortTarget ) //Short TP?
		{
		Cover[ i ] = 1;
		CoverPrice[ i ] = ShortTarget;
		EP_Short = 0;
                //wasOPP[i] = True;
		}
			
		if( EP_Short > 0 AND High[ i ] > ShortStop ) //Short SL?
		{
		Cover[ i ] = 1;
		CoverPrice[ i ] = ShortStop;
		EP_Short = 0;
                //wasOPP[i] = True;
		}
		
		if( Cover[ i ] )
		wasOPP[i] = True;
         } //missed	

	if( EP_Long > 0 AND sqoff[ i ] ) //Exit all positions if time session ends
	{
	Sell[ i ] = 1;
	SellPrice[ i ] = Open[i];
	EP_Long = 0;
        //wasOPP[i] = True;
	}
	
	if( EP_Short > 0 AND sqoff[ i ] )
	{
	Cover[ i ] = 1;
	CoverPrice[ i ] = Open[i];
	EP_Short = 0;
        //wasOPP[i] = True;
	}
	
	if( Cover[ i ] OR Sell [ i ] )
	wasOPP[i] = True;

}

In editor, try select all and Edit->Pretify selection

1 Like

Hi @awilson , thanks for your reply! In fact I did that correction somewhere in my testing and forgot to re-do it.. @beppe is going to point me for sure :sweat_smile:

Here is the complete code with the Explorer entries so anyone can test the logic:

_SECTION_BEGIN("Price");

SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) Vol " +WriteVal( V, 1.0 ) +" {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 )) ));
Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
_SECTION_END();

//-----------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------
_SECTION_BEGIN("Properties");
/*
//SetTradeDelays( 0,0,0, 0 );
SetOption( "InitialEquity", 100000);
SetOption("AllowSameBarExit",True);
SetOption("ActivateStopsImmediately",True);
SetOption("MaxOpenPositions", 1);
SetOption("FuturesMode" ,True);
SetOption("MinShares",1);
SetOption("CommissionMode",2);
SetOption("CommissionAmount",0.5);
//SetOption("AccountMargin",10);
SetOption("RefreshWhenCompleted",True);
SetPositionSize(2,spsShares);
SetOption( "AllowPositionShrinking", True );
*/
TickSize = 0.25;
PointValue = 2;

_SECTION_END();

//-----------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------
_SECTION_BEGIN("Donchian Channel");

dchUpper  = Ref(HHV(H,20),0);
dchLower  = Ref(LLV(L,20),0);
dchMiddle = (dchUpper + dchLower) / 2;

Plot(dchUpper,"DhU",colorBlue,styleLine);
Plot(dchLower,"DhL",colorBlue,styleLine);
Plot(dchMiddle,"DhM",colorOrange,styleLine);

_SECTION_END();

//-----------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------
//Logica de la estrategia
_SECTION_BEGIN("Logic");

//Inputs controls
lenght      = Param("Lenght",20,1,100,1);
stop        = Param("Stoploss",25,1,1000,1);
target      = Param("Target",50,1,1000,1);
displayline = ParamToggle("Show Target & Stoploss","HIDE|SHOW",1);

//Intraday controls
starttime = ParamTime("signalStartTime","10:30");
endtime   = ParamTime("signalEndTime","17:00");
//sqofftime = ParamTime("SquareoffTime","17:05");

//Trend
isUP   = Close > EMA(Close,200);
isDOWN = Close < EMA(Close,200);
inTime = TimeNum() >= starttime AND TimeNum() <= endtime;
sqoff  = TimeNum() > endtime;

//Long Conditions
oppBuy = Close > Ref(dchUpper,-1) AND isUP AND inTime;

//Short Conditions
oppShort = Close < Ref(dchLower,-1) AND isDOWN AND inTime;

//**************************************************************************************
//**************************************************************************************
BuyCond1 = Ref(oppBuy, -1);
ShortCond1 = Ref(oppShort, -1);

Buy = BuyCond1;
Short = ShortCond1;
Sell = 0;
Cover = 0;
BuyPrice = Open;
ShortPrice = Open;
SellPrice = 0;
CoverPrice = 0;
EP_Long = 0;
BuyStop = 0;
BuyTarget = 0;
EP_Short = 0;
ShortStop = 0;
ShortTarget = 0;

wasOPP = False;

for( i = 200; i < BarCount; i++ )
{

    if( EP_Long == 0 AND Buy[ i ] AND NOT wasOPP[ i - 1 ] ) //LONGS
    {

        if( BuyCond1[ i ] )
        {
            EP_Long = BuyPrice[ i ];
            BuyTarget = EP_Long + target;
            BuyStop = EP_Long - stop;
        }

        if( EP_Long > 0 AND High[ i ] > BuyTarget ) //Long TP?
        {
            Sell[ i ] = 1;
            SellPrice[ i ] = BuyTarget;
            EP_Long = 0;
        }

        if( EP_Long > 0 AND low[ i ] < BuyStop ) //Long SL?
        {
            Sell[ i ] = 1;
            SellPrice[ i ] = BuyStop;
            EP_Long = 0;
        }

        if( Sell[ i ] )
            wasOPP[i] = True;
    }

    if( EP_Short == 0 AND Short[ i ] AND NOT wasOPP[ i - 1 ] ) //SHORTS
    {

        if( ShortCond1[ i ] )
        {
            EP_Short = ShortPrice[ i ];
            ShortTarget = EP_Short - target;
            ShortStop = EP_Short + stop;
        }

        if( EP_Short > 0 AND Low[ i ] < ShortTarget ) //Short TP?
        {
            Cover[ i ] = 1;
            CoverPrice[ i ] = ShortTarget;
            EP_Short = 0;
        }

        if( EP_Short > 0 AND High[ i ] > ShortStop ) //Short SL?
        {
            Cover[ i ] = 1;
            CoverPrice[ i ] = ShortStop;
            EP_Short = 0;
        }

        if( Cover[ i ] )
            wasOPP[i] = True;
    }

    if( EP_Long > 0 AND sqoff[ i ] ) //Exit all positions if time session ends
    {
        Sell[ i ] = 1;
        SellPrice[ i ] = Open[i];
        EP_Long = 0;
    }

    if( EP_Short > 0 AND sqoff[ i ] )
    {
        Cover[ i ] = 1;
        CoverPrice[ i ] = Open[i];
        EP_Short = 0;
    }

    if( Cover[ i ] OR Sell [ i ] )
        wasOPP[i] = True;

}


Buy = ExRem(Buy, Short);
Short = ExRem(Short, Buy);
Sell = ExRem(Sell, Buy);
Cover = ExRem(Cover, Short);

InTrade_Long = Flip( Buy, Sell ) AND Flip( Buy, Short );
InTrade_Short = Flip( Short, Cover ) AND Flip( Short, Buy );

//Longs
EP_Long = ValueWhen( Buy, BuyPrice );
StopLevel_Long = stop;
Stopline_Long = IIf( InTrade_Long, EP_Long - StopLevel_Long, Null );
Plot( Stopline_Long, "BuyStop", colorRed );

TgtLevel_Long = target;
TgtLine_Long  = IIf( InTrade_Long, EP_Long + TgtLevel_Long, Null );
Plot( TgtLine_Long, "BuyTarget", colorGreen );

//Shorts
EP_Short = ValueWhen( Short, ShortPrice );
StopLevel_Short = stop; 
Stopline_Short = IIf( InTrade_Short, EP_Short + StopLevel_Short, Null );
Plot( Stopline_Short, "ShortStop", colorRed );

TgtLevel_Short = target;
TgtLine_Short  = IIf( InTrade_Short, EP_Short - TgtLevel_Short, Null );
Plot( TgtLine_Short, "ShortTarget", colorGreen );

//-----------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------
Plot(EMA(Close,200),"EMA",colorRed);

//Plotting Signals on chart
PlotShapes(IIf(BuyCond1 AND Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(BuyCond1 AND Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);                      
PlotShapes(IIf(BuyCond1 AND Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45);

PlotShapes(IIf(ShortCond1 AND Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(ShortCond1 AND Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);                      
PlotShapes(IIf(ShortCond1 AND Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);

PlotShapes(Sell * shapestar, colorBrightGreen, 0, High, 12);
PlotShapes(Cover * shapestar, colorRed, 0, Low, -12);

//-----------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------
//Exploration
filter = 1;
AddColumn(BarIndex(), "Index" );
AddColumn( Close, "Close" );
AddColumn( Open, "Open" );

AddColumn( Buy, "Buy", 1, colorDefault, IIf(Buy != 0, colorLime, colorDefault ));
AddColumn( BuyCond1, "OPPB", 1, colorDefault, IIf(BuyCond1 != 0, colorYellow, colorDefault ));
AddColumn( Sell, "Sell", 1, colorDefault, IIf(Sell != 0, colorOrange, colorDefault ));
AddColumn( SellPrice, "SellPrice" );

AddColumn(wasOPP, "wasOPP", 1, colorDefault, IIf(wasOPP != 0, colorLightOrange, colorDefault ));

AddColumn( Short, "Short", 1, colorDefault, IIf(Short != 0, colorLime, colorDefault ));
AddColumn( ShortCond1, "OPPS", 1, colorDefault, IIf(ShortCond1 != 0, colorYellow, colorDefault ));
AddColumn( Cover, "Cover", 1, colorDefault, IIf(Cover != 0, colorOrange, colorDefault ));
AddColumn( CoverPrice, "CoverPrice" );

AddColumn(Volume, "Vol", 1.4, colorDefault);

_SECTION_END();

I am relatively calm to see that there were no conceptual errors in the loop (?)
With this version the short opens but Explorer show me that closes in the same bar BUT another cover appear later with no new short entry.
Here the Explorer pics with the BarIndex highlighted:


To get better understanding of what is happening in your code and how functions work, use advice given here: How do I debug my formula?

SIMPLIFY. You wrote formula that you don't understand yourself. The only way to get to understand it is to remove parts / simplify. Use "divide and conquer" method. Write formulas in small pieces that you actually can understand.

1 Like