Apply target stop on 2R

Need a way to apply a stop after 2xRisk is achieved. Risk is a calculated amount which ends up being an array and this changes per bar. But i need this value fixed so it is able to apply the correct stop target and not changed after each bar after the entry bar.

ie:

risk = (ref(high,-1)-ref(low,-1));

ApplyStop(Type=stopTypeProfit, mode=stopModePoint, Amount=2*risk, 
            ExitAtStop=1, volatile=False, ReEntryDelay=0, ValidFrom=0, ValidTo=-1 );

But this doesn't work because risk is not a fixed integer and is an array so it dosn't work as expected. For this to work do i need to create an array and fill it in with the same value? What is the best way to do this?

Thanks!

@justintime, you might consider a static variable. Your code controls what to call it, when to set it, and when to reference it.

As always, check the manual (on the topics STATICVARSET and STATICVARGET).

Would the code look like this:

risk = criteriaRange;
StaticVarSet("staticRisk", risk);
ApplyStop(Type=stopTypeProfit, mode=stopModePoint, Amount=2*StaticVarGet("staticRisk"), 
            ExitAtStop=1, volatile=False, ReEntryDelay=0, ValidFrom=0, ValidTo=-1 );

It still didn't seem to work for me.

Right now your static variable is also an array. When setting it, you need to isolate the value of this array at the moment of entry so that it is one number, and not an array. Hint: LastValue( ValueWhen( ... ) )

You can use TypeOf() to test if you set the svar as an array or a number, see
https://www.amibroker.com/guide/keyword/typeof.html

FYI, include the symbol in the svar name so that it's unique. Once you start using svars, you need to have a naming convention so that all your svars don't get mixed together. You could name it like this: iRisk_symbol_interval so it might be iRisk_SPY_60 on a 1-minute interval or iRisk_SPY_300 on 15-min. This way you can have different initial risks for different timeframes.

If you don't do this, and run a backtest on multiple symbols, the same svar will be overwritten by multiple CPU threads competing to set the variable at the same time, which is very bad.

An easier way is to do this without an svar just by using ValueWhen(). Your array would always be filled with the iRisk at the moment of the most recent Buy signal, like this:

Range = Ref( H-L, -1 );
iRisk = ValueWhen( Buy == 1, Range, 1 );

This way, your ApplyStop() function would be using an array, but it would be populated with the value of iRisk when the Buy signal was triggered.

Thanks this seems to work better for me. I'm running back test on thousands of symbols so i can't have the multithread issue described above interferer with my results.

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