Long Above and Short Below 200 EMA BackTest

dedjene

New member
Good afternoon all,

I was wondering if there was a way to backtest strategies that will only long above the 200 EMA and short below it. In result, automatically filtering out the longs below the 200 EMA and shorts above.

The purpose of this question is to limit my trades and to theoretically not fight the trend.

Let's use the default MACD strategy provided by thinkorswim as an example.

Code:
#
# TD Ameritrade IP Company, Inc. (c) 2013-2021
#

input fastLength = 12;
input slowLength = 26;
input macdLength = 9;
input averageType = AverageType.EXPONENTIAL;

def diff = reference MACD(fastLength, slowLength, macdLength, averageType).Diff;

AddOrder(OrderType.BUY_AUTO, diff crosses above 0, tickColor = GetColor(0), arrowColor = GetColor(0), name = "MACDStratLE");
AddOrder(OrderType.SELL_AUTO, diff crosses below 0, tickColor = GetColor(1), arrowColor = GetColor(1), name = "MACDStratSE");

How can we modify this code to achieve my desired result?


Thank you all,

Sincerely,

Dj
 
@dedjene Sure... Just add the 200 EMA into that code and then use it to compare against as part of your AddOrder conditions... You would add something like "and close > ema200" or "and close < ema200"... The following is a code snippet... However, this not being tested you may need additional logic if using BUY_AUTO and SELL_AUTO... Give it a go and holler if you get stumped...

Ruby:
def ema200 = ExpAverage(close, 200);

# the balance of your code goes here...

AddOrder(OrderType.BUY_AUTO, diff crosses above 0 and close > ema200, tickColor = GetColor(0), arrowColor = GetColor(0), name = "MACDStratLE");
AddOrder(OrderType.SELL_AUTO, diff crosses below 0 and close < ema200, tickColor = GetColor(1), arrowColor = GetColor(1), name = "MACDStratSE");
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

@dedjene Sure... Just add the 200 EMA into that code and then use it to compare against as part of your AddOrder conditions... You would add something like "and close > ema200" or "and close < ema200"... The following is a code snippet... However, this not being tested you may need additional logic if using BUY_AUTO and SELL_AUTO... Give it a go and holler if you get stumped...

Ruby:
def ema200 = ExpAverage(close, 200);

# the balance of your code goes here...

AddOrder(OrderType.BUY_AUTO, diff crosses above 0 and close > ema200, tickColor = GetColor(0), arrowColor = GetColor(0), name = "MACDStratLE");
AddOrder(OrderType.SELL_AUTO, diff crosses below 0 and close < ema200, tickColor = GetColor(1), arrowColor = GetColor(1), name = "MACDStratSE");
I really appreciate the help. I'll give it a try!
 
Hi @rad14733,

I utilized your advice and tried adding code that would allow my back test to only long above 200 EMA and short below. However, I'm still having difficulty.

It enters correctly (shorting below 200 EMA) but exits incorrectly (only will close above the 200 EMA instead of closing whenever the algorithm signaled it - the arrows you'll see in the screenshot).

I am back testing the Quantitative Qualitative Estimation by the way if any one is curious.

Attached is the screenshot and code below:



Code:
# QQE Indicator Color Coded
# Converted by Kory Gill for BenTen at useThinkScript.com
# Original https://www.tradingview.com/script/zwbe2plA-Ghosty-s-Zero-Line-QQE/

input RSI_Period = 20;
input Slow_Factor = 5;
input QQE = 4.236;

def Wilder_Period = RSI_Period * 2 - 1;
def vClose = close;

def rsi = RSI(price = vClose, length = RSI_Period).RSI;
def rsi_ma = MovingAverage(AverageType.EXPONENTIAL, rsi, Slow_Factor);
def atr_rsi = AbsValue(rsi_ma[1] - rsi_ma);
def atr_rsi_ma = MovingAverage(AverageType.EXPONENTIAL, atr_rsi, Wilder_Period);
def dar = MovingAverage(AverageType.EXPONENTIAL, atr_rsi_ma, Wilder_Period) * QQE;

def DeltaFastAtrRsi = dar;
def RSIndex = rsi_ma;
def newshortband =  RSIndex + DeltaFastAtrRsi;
def newlongband = RSIndex - DeltaFastAtrRsi;

def longband = if RSIndex[1] > longband[1] and RSIndex > longband[1]
               then max(longband[1],newlongband)
               else newlongband;

def shortband = if RSIndex[1] < shortband[1] and  RSIndex < shortband[1]
                then min(shortband[1], newshortband)
                else newshortband;

def trend = if Crosses(RSIndex, shortband[1])
            then 1
            else if Crosses(longband[1], RSIndex)
            then -1
            else if !IsNAN(trend[1])
            then trend[1]
            else 1;

def FastAtrRsiTL = if trend == 1
                   then longband
                   else shortband;

def pFastAtrRsiTL = FastAtrRsiTL;
def pRsiMa = rsi_ma;
def line50 = 50;

plot UpSignal = if pRSIMA crosses above pFastAtrRsiTL then low else Double.NaN;
plot DownSignal = if pRSIMA crosses below pFastAtrRsiTL then high else Double.NaN;

UpSignal.SetDefaultColor(Color.MAGENTA);
UpSignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
DownSignal.SetDefaultColor(Color.CYAN);
DownSignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);

def ema200 = ExpAverage(close, 200);

AddOrder(OrderType.BUY_AUTO, pRSIMA > pFastATRRsiTL and close > ema200, tickColor = Color.WHITE, arrowColor = Color.GREEN, name = "Long");
AddOrder(OrderType.SELL_AUTO, pRSIMA < pFastAtrRsiTL and close < ema200, tickColor = Color.BLACK, arrowColor =  Color.RED, name = "Short");

Would you happen to know where my mistake is?

Sincerly,

Dedjene
 
@dedjene As I expected, and mentioned above, you are having issues due to only using BUY_AUTO and SELL_AUTO... My suggestion would be to add two more AddOrder() lines, SELL_TO_CLOSE for exiting Longs and the BUY_TO_CLOSE for exiting Shorts, neither using the ema200... When I use AddOrder for backtesting, which I rarely do these days, I rarely ever use BUY_AUTO and SELL_AUTO but, instead, use multiple fully qualified Buy and SELL orders... This allows for much more refined entry and exit logic for both Longs and Shorts without a big glob of convoluted logic... I think that's your best option... In fact, I'd nix the auto's altogether and just write four or more AddOrder calls with clear directional logic... Hope this helps...
 
@dedjene As I expected, and mentioned above, you are having issues due to only using BUY_AUTO and SELL_AUTO... My suggestion would be to add two more AddOrder() lines, SELL_TO_CLOSE for exiting Longs and the BUY_TO_CLOSE for exiting Shorts, neither using the ema200... When I use AddOrder for backtesting, which I rarely do these days, I rarely ever use BUY_AUTO and SELL_AUTO but, instead, use multiple fully qualified Buy and SELL orders... This allows for much more refined entry and exit logic for both Longs and Shorts without a big glob of convoluted logic... I think that's your best option... In fact, I'd nix the auto's altogether and just write four or more AddOrder calls with clear directional logic... Hope this helps...
Ahh I see my mistake now. I'll keep tweaking it. Thanks again! @rad14733
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
348 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top