Fix MACD HA Strategy

Lesnewby

Member
Can anyone help me add criteria to this strategy so entries and exits are never possible when the MACD signal line is below the MACD average line.
mod edited: misleading stats

. Any help will be much appreciated.

Here is the code:
Code:
#2022 1202 LJJ_GrnRedFPL
#HA Enter trade on first green bar and exit on first red .
#NEVER ENTER TRADE IF MACD SIGNAL LINE IS BELOW AVERAGE LINE.
#Thanks to Modius, RConner7, Barbaros and Eddielee394.
#start
def haClose = ohlc4;
def haOpen =  open;

input AtrMult = .60;#hint AtrMult: Modify to FloatingPL Plot-Original set to 1.00
input nATR = 6;
input AvgType = AverageType.HULL;
input ShowBubbles = NO;
def ATR = ATR("length" = nATR, "average type" = AvgType);
def UP_Band_Basic = HL2 + (AtrMult * ATR);
def LW_Band_Basic = HL2 + (-AtrMult * ATR);
def UP_Band = if ((UP_Band_Basic < UP_Band[1]) or (close[1] > UP_Band[1])) then UP_Band_Basic else UP_Band[1];
def LW_Band = if ((LW_Band_Basic > LW_Band[1]) or (close[1] < LW_Band[1])) then LW_Band_Basic else LW_Band[1];


def ST = if ((ST[1] == UP_Band[1]) and (close < UP_Band)) then UP_Band
else if ((ST[1] == UP_Band[1]) and (close > Up_Band)) then LW_Band
else if ((ST[1] == LW_Band[1]) and (close > LW_Band)) then LW_Band
else if ((ST[1] == LW_Band) and (close < LW_Band)) then UP_Band
else LW_Band;


def Long = if close > ST then ST else Double.NaN;
#Long.AssignValueColor(Color.GREEN);
#Long.SetLineWeight(2);

def Short = if close < ST then ST else Double.NaN;
#Short.AssignValueColor(Color.RED);
#Short.SetLineWeight(3);
def LongTrigger = IsNaN(Long[1]) and !IsNaN(Long);
def ShortTrigger = IsNaN(Short[1]) and !IsNaN(Short);
plot LongDot = if LongTrigger then ST else Double.NaN;
LongDot.SetPaintingStrategy(PaintingStrategy.POINTS);
LongDot.AssignValueColor(Color.GREEN);
LongDot.SetLineWeight(4);

plot ShortDot = if ShortTrigger then ST else Double.NaN;
ShortDot.SetPaintingStrategy(PaintingStrategy.POINTS);
ShortDot.AssignValueColor(Color.RED);
ShortDot.SetLineWeight(4);

AddChartBubble(ShowBubbles and LongTrigger, ST, "B", color.YELLOW, yes);
AddChartBubble(ShowBubbles and ShortTrigger, ST, "S", color.CYAN, yes);


def ha_up = MACD()."Value" crosses above MACD()."Avg" and haClose > haOpen ;
def ha_dn = MACD()."Value" crosses below MACD()."Avg" and haClose < haOpen;
def bto = ha_up ;
def stc = ha_dn ;
addOrder(OrderType.BUY_TO_OPEN, Long , Open, name = "LE");
addOrder(OrderType.Sell_TO_CLOSE, Short, open, name = "LX");
 
Last edited by a moderator:
Ok I understand a bit of what you’re doing from the analytics side. As far as to fix the issue with MACD, it comes down to coding the conditions correctly. I found it easier to write things similar to how the standard TOS indicator “Impulse” writes it; set conditions I want for longs as “bullish” and exits or shorts as “bearish” and if I have extra criteria I use the “neutral”. Once I have my conditions defined as bull/bear etc. I can set the strategy function to “buy when bullish” for example and “exit when bearish”. Check out its source code, it could be inspirational. Replying from my phone, otherwise I’d show you an example code write-up, sorry.
I am sorry but I do not understand, which source code do you suggest I check out! Thx,
 

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

I am sorry but I do not understand, which source code do you suggest I check out! Thx,
Fixed your MACD issue. Still an issue of calculating P/L properly so refer to the response from @MerryDay for that. Also I believe there is an issue with HAopen, but have not looked at it enough.

Edit: Fixed the reason the entries and exits were not aligned correctly. Performance should be more accurate now.

Code:
#2022 1202 LJJ_GrnRedFPL
#HA Enter trade on first green bar and exit on first red .
#NEVER ENTER TRADE IF MACD SIGNAL LINE IS BELOW AVERAGE LINE.
#Thanks to Modius, RConner7, Barbaros and Eddielee394.
#start
def haClose = ohlc4;
def haOpen =  open;

input AtrMult = .60;#hint AtrMult: Modify to FloatingPL Plot-Original set to 1.00
input nATR = 6;
input AvgType = AverageType.HULL;
input ShowBubbles = NO;
def ATR = ATR("length" = nATR, "average type" = AvgType);
def UP_Band_Basic = HL2 + (AtrMult * ATR);
def LW_Band_Basic = HL2 + (-AtrMult * ATR);
def UP_Band = if ((UP_Band_Basic < UP_Band[1]) or (close[1] > UP_Band[1])) then UP_Band_Basic else UP_Band[1];
def LW_Band = if ((LW_Band_Basic > LW_Band[1]) or (close[1] < LW_Band[1])) then LW_Band_Basic else LW_Band[1];


def ST = if ((ST[1] == UP_Band[1]) and (close < UP_Band)) then UP_Band
else if ((ST[1] == UP_Band[1]) and (close > Up_Band)) then LW_Band
else if ((ST[1] == LW_Band[1]) and (close > LW_Band)) then LW_Band
else if ((ST[1] == LW_Band) and (close < LW_Band)) then UP_Band
else LW_Band;


def Long = if close > ST then ST else Double.NaN;
#Long.AssignValueColor(Color.GREEN);
#Long.SetLineWeight(2);

def Short = if close < ST then ST else Double.NaN;
#Short.AssignValueColor(Color.RED);
#Short.SetLineWeight(3);
def LongTrigger = IsNaN(Long[1]) and !IsNaN(Long);
def ShortTrigger = IsNaN(Short[1]) and !IsNaN(Short);
plot LongDot = if LongTrigger then ST else Double.NaN;
LongDot.SetPaintingStrategy(PaintingStrategy.POINTS);
LongDot.AssignValueColor(Color.GREEN);
LongDot.SetLineWeight(4);

plot ShortDot = if ShortTrigger then ST else Double.NaN;
ShortDot.SetPaintingStrategy(PaintingStrategy.POINTS);
ShortDot.AssignValueColor(Color.RED);
ShortDot.SetLineWeight(4);

AddChartBubble(ShowBubbles and LongTrigger, ST, "B", color.YELLOW, yes);
AddChartBubble(ShowBubbles and ShortTrigger, ST, "S", color.CYAN, yes);

input fastLength = 12;
input slowLength = 26;
input MACDLength = 9;
input averageType = AverageType.EXPONENTIAL;
input showBreakoutSignals = no;

def Value = MovingAverage(averageType, close, fastLength) - MovingAverage(averageType, close, slowLength);
def Avg = MovingAverage(averageType, Value, MACDLength);

def Diff = Value - Avg;
def ZeroLine = 0;


def ha_up = MACD()."Value" crosses above MACD()."Avg" and haClose > haOpen ;
def ha_dn = MACD()."Value" crosses below MACD()."Avg" and haClose < haOpen;
def bto = ha_up  and value > Avg;
def stc = ha_dn;
addOrder(OrderType.BUY_TO_OPEN, bto , Close, name = "LE");
addOrder(OrderType.Sell_TO_CLOSE, stc, Close, name = "LX");
 
Last edited:
@Lesnewby
Everyone has been attempting to tell you that the strategy is not working as you think it is, even with making @tradebyday's changes.

The backtesting format must be:
Ruby:
addOrder(OrderType.BUY_TO_OPEN, Long , Open[-1], name = "LE");
addOrder(OrderType.Sell_TO_CLOSE, Short, open[-1], name = "LX");
read more:
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Others/AddOrder#:~:text=close > close[1],-,open[-1],-, 50, Color.ORANGE
AddOrder is not designed to operate on anything but the condition of the strategy at the close of a bar. Think of it as doing a calculation once per bar, at the end of the bar, and it makes more sense. This is just the way it is designed. It is a limitation, but not a design flaw per sey.

-mashume

When AddOrder is used correctly. The p/l stats are:
MSXw04O.png
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
221 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