Code Error in Dynamic Stop Loss

Good day fellow Amibroker Coders

I'm having difficulty with a few lines of code. Please bare with me since I'm a complete noob when it comes to coding. After staring at the code for hours, browsing the web/forum and refraining from immediately looking for someone to spoon feed me the answer, I eventually couldn't resist to post my question here.

The code snippet is not the exact idea I'm trying to implement but the principal remains the same. I'm trying to update/tighten my dynamic trailing stop after an certain event occurs, in this case lets say when price is extended x $ amount away from the moving average.

As one can see in the image it is plotted correctly (blue line) and should've taken me out the trade earlier. However, the stop wasn't updated and the trade exited with the original % trail (red line)


herewith the code:

SetPositionSize(5, spsPercentOfEquity);
SetOption("MaxOpenPositions", 20);

LongEntry = C > MA(C,150);

Stretch = 15 < (C-MA(C,150));

StopL = IIf(Stretch,10,25); // if price is stretched more than $15 use a stop of 10% otherwise use a stop of 25%

Buy = LongEntry;
Sell = 0;

ApplyStop(stopTypeTrailing, stopModePercent, StopL, 0, True, 1);

Equity(1,0); // evaluate stops, all quotes

inTrade = Flip(Buy,Sell); // True when buy, False when Sell

SetOption("EveryBarNullCheck", True); // Checks for null bars

stopline = IIf(inTrade, HighestSince (Buy, H - (H*StopL/100)), Null);

Plot(stopline, "StopLine", colorRed, styleLine,0,0,0,0);
PlotShapes(Buy*shapeUpArrow, colorBrightGreen, 0,L);
PlotShapes(Sell*shapeDownArrow, colorRed, 0,H);


Only users with License Verified Badge are allowed to post on this forum.

Hi @TrendSurfer

I used the same email as the email I used purchasing Amibroker.

Some assistance on the topic I posted by anyone would be much appreciated. I've tried using a "for loop" variant of the trailing stop but running into some errors (obviously from side) as well

Contact support via email using from registered email address to sort.

Then you will be able to receive assistance.

Where is code of blue line :question:

@codejunkie, My apologies meant to say red line. Should exit at red line but exited at blue line

The image is 2 AFLs overlaid on 1 chart just to show what is meant to happen. Blue line is meant to be updated with the red line (when price is stretched by more than $15 from the moving average)

The trailing stop distance should update when price is stretched : " StopL = IIf(Stretch,10,25); "



1 Like

A For Loop will give you more control if desired/required?

See following links for more details on ApplyStop and For Loops.

Thanks. Resolved with a for loop

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