Looping code - position variable not working

Hi all,
I am trying to setup a more complex stop through looping code. Somehow I am not able to use a local variable to store information inside the loop. In the simplified version below I illustrate this by using the local variable 'pos' to reflect the trading position. When I run it enters a long trade but it never exits (where I expect it to exit as the short signal will trigger an exit).
Been staring at this for days but do not see the flaw. Any tips?
-QD-
ps. I am using latest 6.35.0

SetOption("FuturesMode", True);                                         // Use MarginDeposit and PointValue in calculations 
SetOption("InitialEquity", 100000 );                                    // Initial equity $ 
SetOption("AccountMargin", 100);                                        // Account margin, 100 = no margin			 
SetOption("MinShares", 1);                                              // Min number shares one 
SetOption("MinPosValue", 0);                                            // Min position value to make trade worthwhile, 0 = no limit 
SetTradeDelays(0,0,0,0);                                                // Trade delays applied by the backtester        
contracts = 1;                                                          // contracts to acquire 
SetPositionSize( contracts, spsShares );                                // spsShares = size expressed in shares/contracts 
SetOption("Allowsamebarexit", false);         

//--- SIGNAL CODE ---//
OpenD=ValueWhen(TimeNum()==083000,O,1);
EntryCondTime = TimeNum()==083500;
EntryLong = EntryCondTime AND L>OpenD ;
EntryShort = EntryCondTime AND H<OpenD;

//--- BUY|SELL|SHORT|COVER CODE ---///
SetOption("ReverseSignalForcesExit", true); 
Buy= Entrylong; 
Short=0; 
Sell=0;
Cover= 0; 

//--- LOOPING CODE ---///
pos = 0;
prevposition=0; ;
shortexit = 0;
tpprice=0;//

for( i=1; i<BarCount; i++ )  
{  
	
	if ( pos >0)
	{
		Cover[i]=1;
		continue;
	}
	
	if(EntryShort[i]>0 AND pos == 0)   
	{  
		_TRACE("EntryShort");
		Short[i]=1; ;
		pos=1;
		tpprice = ShortPrice[i];
		_TRACE(NumToStr(tpprice,5.2));
		continue;
	}  
 }

You should reset variables on exit.

SetOption("FuturesMode", True);                                         // Use MarginDeposit and PointValue in calculations 
SetOption("InitialEquity", 100000 );                                    // Initial equity $ 
SetOption("AccountMargin", 100);                                        // Account margin, 100 = no margin			 
SetOption("MinShares", 1);                                              // Min number shares one 
SetOption("MinPosValue", 0);                                            // Min position value to make trade worthwhile, 0 = no limit 
SetTradeDelays(0,0,0,0);                                                // Trade delays applied by the backtester        
contracts = 1;                                                          // contracts to acquire 
SetPositionSize( contracts, spsShares );                                // spsShares = size expressed in shares/contracts 
SetOption("Allowsamebarexit", false);         

//--- SIGNAL CODE ---//
OpenD=ValueWhen(TimeNum()==083000,O,1);
EntryCondTime = TimeNum()==083500;
EntryLong = EntryCondTime AND L>OpenD;
EntryShort = EntryCondTime AND H<OpenD;

//--- BUY|SELL|SHORT|COVER CODE ---///
SetOption("ReverseSignalForcesExit", true); 

Buy= Entrylong; 
Short=0; 
Sell=0;
Cover= 0; 

dt = DateTime();
//--- LOOPING CODE ---///
pos = 0;
prevposition=0;
shortexit = 0;
tpprice=0;//
for( i=1; i<BarCount; i++ )  
{  
	if(EntryShort[i]>0 AND pos == 0)   
	{  
		_TRACE("EntryShort");

		Short[i]=1;

		pos=1;
		tpprice = ShortPrice[i];

		_TRACE(NumToStr(tpprice,5.2));
		_TRACEF("Entry dt: %s", DatetimetoStr(dt[i]));
	}  

	if ( pos > 0 )
	{
		Cover[i]=1;
		pos = tpprice = 0;	// RESET!	
		_TRACEF("Exit dt: %s", DatetimetoStr(dt[i]));
	}
 }

Then you will get same bar exits.
9


If you do e.g.

	if ( pos > 0 && ! EntryShort[i] ) 
	{
		Cover[i]=1;
		pos = tpprice = 0;	// RESET!	
		_TRACEF("Exit dt: %s", DatetimetoStr(dt[i]));
	}

Then you will get next bar exit

10


Or add exit on tpprice break

	if ( pos > 0 && H[i] > tpprice + 20*ticksize ) 
	{
		Cover[i]=1;
		pos = tpprice = 0;	// RESET!	
		_TRACEF("Exit dt: %s", DatetimetoStr(dt[i]));
	}

etc....

Hi fxshrat,
Very much appreciated. I missed this reset and that solved the first piece. I am now adding more conditions and the code gets stuck again after adding the condition that "C[i] < tpprice". After adding this, the code again does not executes the cover statement. See below the new code that does not run....again looks I am blind for my own mistakes :wink:

  • QD -
 for( i=1; i<BarCount; i++ )  
{  
	if(EntryShort[i]>0 AND pos == 0)   
	{  
		_TRACE("EntryShort");
		Short[i]=1;
		pos=1;
		tpprice = ShortPrice[i];
		_TRACE(NumToStr(tpprice,5.2));
		_TRACEF("Entry dt: %s", DatetimetoStr(dt[i]));
	}  
	if ( pos > 0 && ! EntryShort[i] && C[i]<tpprice) 
	{
		Cover[i]=3;
		pos = tpprice = 0;	// RESET!	
		_TRACEF("Exit dt: %s", DatetimetoStr(dt[i]));
	}
 }

You do not say where you excute the code. I suppose you execute it in analysis.

So you have to check interval (Periodicity) there. You are entering at exact timenum value since you use equality check operator ( == ). So if timenum value is not to be found in timenum array then there won't be an entry.

Secondly you should enable Short in analysis.

10

FYI, I do get Cover exit on my end.


Rather use ApplyStop function. You do not need looping for profit target stop.

I have those settings ok I and run it at 5m periodicity.
If I remove the C[i]<tpprice condition it runs with covers with the condition it doesn't work at my end...

Why am I not using Applystop?
The bigger picture is that I want to simulate following condition TP:
a) Short or Long entry is under different entry condition at @8:30 in the morning
b) As of 11am I am enabling a profit target for SHORTS ONLY
c) Next day, in case the SHORT position is not closed or we are already in LONG position, we will not enter.
Do you think we can do this with Applystop? or alternative IIF conditions?
Tks, -QD-

I don't see why you couldn't do your a), b), c) via Applystop().
As for b)... see valid from/to setting or you may use volatile = 1 and amount being an IIf() array and IIf() expression being TimeNum() >= 110000.

Let's try this with the following example:

Day 1:
= we enter short at 8:35am. shortprice = 2700.
= at 11:00 we activate the TP stop at e.g. 4 points until end of the trading day
= TP stop is not hit

Day 2:
= we are still short, no long entry so we remain in short
= at 11:00 we activate the TP stop at 4 points, until end of the trading day
= TP hit at 15:00 and we exit.

Day 3:
= we enter long at 8:35am. buyprice 2720
= no stops we wait to next day

Day 4:
= we enter short at 8:35am and trigger exit of the long at e.g. shortprice 2725
= at 11:00 we activate the TP stop at 4 points, until end of the trading day
= TP hit at 15:00 and we exit.

How would that work with Applystop? Two options:

OPTION 1:
Applystop(StopTypeProfit, StopModePoints,4,0,volatile =0, validfrom=29 (bars),-1);
=> this has downside that the next day stop is still activated before 11am

OPTION 2:
TP = IIF(TimeNum>=110000, 4, Null);
Applystop(StopTypeProfit, StopModePoints,TP, 0,volatile =1, validfrom=0,-1);
=> how do disable the long side?

Thanks again, -QD-