Wrong usage was: help with IF, FOR and Applystop in this code

I need to buy at the top of the "branco2" which is my buy trigger and put the stop at its low. I managed to do that part. The problem is the rest.

I need to make a 30% partial when the price hits ema9 and at the same time pull the stop to the entry price.

After that I would like to conduct the trade with the EMA9 until the first candle turns it downwards and then I would place the stop below that candlestick (it is not to stop on this candle, but to put the stop below it).

The trade ends only when one of the stops is triggered.

The part of the partial I didn't even start because I have no idea how to do it, but the rest I tried but I'm not getting it.

I tried to use 2 FORs but I believe that it is not possible to use a for inside another. I don't know how to solve it anymore.

Sell = 0;
Buy = 0;

for( i = 1; i < BarCount; i++ )

	if(  branco2[i-1] AND H[i]>H[i-1]  )
	Buy = branco2[i-1] AND H[i]>H[i-1];
	BuyPrice = H[i-1] + 0.03;
	ApplyStop(stopTypeLoss,stopModePoint,L[i-1] - 0.03,1,False,3);				
		for( z = 1; z < BarCount; z++)
			if( Cross(C[z],EMA(C,9)[z] ) )
					ApplyStop(stopTypeProfit,stopModePoint, L[i-1],1);
			if (Cross(EMA(C,9)[z],C[z]))
				ApplyStop(stopTypeProfit,stopModePoint, L(z) - 0.03,1);


In short: DO NOT use array functions inside loop. Your code is totally wrong because you did not read the most fundamental part of tutorial Understanding how AFL works

And as it was explained many times on this forum (USE SEARCH), ApplyStop must not be called inside loop because it is backtester GLOBAL SWITCH. It is either on or off for entire backtest.

Read the manual and use the examples as given in the manual and/or Knowledge Base. Do NOT invent your own wicked ways because quite clearly you don't know what you are doing.. Do not copy paste from Indian web pages. Use official docs only.


Thank you Tomas and I'm sorry.

Believe me, I read a lot before writing this distress call. But as I'm new and I don't have much programming experience - my experience is with trading - it's really hard to fully understand some concepts.
The user guide is extremely concise and it is difficult to find quality information gathered.
There are times when it feels like I need to write a rocket launch code just to try to do a partial.

I'm down and thinking about what to do... Maybe look for other solutions.

Below my last attempt which obviously didn't work either.

Buy = Ref(branco2,-1) AND H > Ref(H, -1); 
BuyPrice = Ref(H,-1) + 0.03;
Sell =  0;
M9 = EMA(C,9);
Cruzamento = Cross(EMA(C,9),C);
Sigbuy = 0;
virada = 0;
stopinicial =1;

for( i = 0; i < BarCount; i++ )

	if( sigbuy == 0 AND buy[i] == 1 )
		Sigbuy = 1;
		Stopinicial = L[i-1] - 0.03;
	if ( sigbuy == 1 AND H[i] >= M9[i] )
		stopinicial = buyprice;	
	if ( sigbuy == 1 AND cruzamento[i] )
		stopinicial = L[i];


This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.