I'm trying to implement a simple market filter that will exit current trades and stop future ones when my definition of a bear market is present (a declining 40-week MA).
I don't get any errors but I also don't get any trades. I am using TC2000 for EOD data and I've been tinkering with the Russell 1000 components in a watchlist for testing. Am I missing something regarding the use of "SPY" since it would not be in the watchlist? It is in the database and when I test the code on SPY alone it also offers no trades. Other systems I've tested without a market filter worked fine.
Many thanks for the assistance
//Simple Trend with Market Filter
// Simple trend following example so I can learn how to code a market filter correctly
NumPos = 1; //Number of allowed positions
SetPositionSize(100/NumPos,spsPercentOfEquity);
SetOption( "MaxOpenPositions", NumPos );
MA1_len = 20;
MA_1 = MA(C,MA1_len);
//Entry based on a rising moving average
MA_entry = IIf(MA_1>Ref(MA_1,-1),1,0);
//Attempting to add a market level filter.
//Bear Market filter
SetForeign("SPY");
BearMkt = C < MA(C,40);
RestorePriceArrays();
IIf(BearMkt,MA_entry=0,MA_entry == MA_entry);
MA_Buy = MA_entry == 1;
MA_sell = MA_entry == 0;
Buy = MA_buy;
Sell = MA_sell;```
@TrendSurfer is correct: you are not using 'IIf()' correctly. However, your logic does not even require the use of 'IIf()', so i suggest you remove those and simplify your coding.
@PropKid as you appear to be new to the forum I would point you to the Official Knowledge Base which as many very useful articles and will answer most of your questions.
Kudos to @TrendSurfer@tonyr and @mradtke for making you feel welcome on the forum (but guys, point him toward the knowledge base )
Many thanks for the assistance, folks. I had read the Knowledge Base on the topic but for some reason hadn't considered a different logic. Also had some unnecessary code in there too.
The final looks like this and works well.
Thanks again.
//Simple Trend with Market Filter
// Simple trend following example so I can learn how to code a market filter correctly
NumPos = 14; //Number of allowed positions
SetPositionSize(100/NumPos,spsPercentOfEquity);
SetOption( "MaxOpenPositions", NumPos );
MA1_len = 20;
MA_1 = MA(C,MA1_len);
//Attempting to add a market level filter.
//Bear Market filter
SetForeign("SPY");
BearMkt = C < MA(C,40);
RestorePriceArrays();
//Entry based on a rising moving average
Buy = MA_1>Ref(MA_1,-1) AND NOT BearMkt;
//Exit based on declining moving average OR BearMkt
Sell = MA_1<=Ref(MA_1,-1) OR BearMkt;