Conditional stop based on index filter

I'm not sure how to do this. I want to raise the stop from -40% to -10% if the index crosses below the 10-month moving average. Once raised, it should not be lowered.

Here is my formula:

index = Foreign("$SPX", "Close");

monthly_close = TimeFrameCompress(Close, inMonthly);
index_filter = monthly_close > MA(monthly_close, 10);

Buy = TimeFrameExpand(index_filter, inMonthly, inWeekly) AND ROC(C, 20) > 30 AND C > HHV(Ref(C, -1), 20);
Sell = 0;

stop_percent = 40;

ApplyStop(stopTypeTrailing, stopModePercent, stop_percent);

SetPositionSize(5, method=spsPercentOfEquity);

I tried making the stop conditional on the index filter using if-then but found this is a common AFL mistake (using an array when a boolean is exxpected):

if (index_filter) {
} else {

I have a feeling the way to do this is to loop over the bars and set the stop loss based on the last closing price (using weekly bars in my system). 

Is that the right approach?

I came up with this, but my sell rule is not getting triggered:

Sell = (TimeFrameExpand(monthly_close < MA(monthly_close, 10), inMonthly, inWeekly) AND C < 0.90 * BuyPrice) OR (TimeFrameExpand(monthly_close > MA(monthly_close, 10), inMonthly, inWeekly) AND C < 0.60 * BuyPrice);

Any ideas?

Such single-line super long statements are difficult to write correctly, difficult to read and difficult to debug.
You have to split it into separate SMALL pieces, store parts into variables and use this:

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?

1 Like

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