0
votes

I've got a code for MACD strategy that only takes long positions (based on a Kodify.net tutorial). The entry condition happens when the macd line crosses over the signal line. The exit condition occurs when the macd line crosses under the signal line.

//@version=4
strategy(title="MACD example strategy", overlay=false, max_bars_back=2000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=10000)

// Create inputs
fastLen = input(title="Fast Length", type=input.integer, defval=12)
slowLen = input(title="Slow Length", type=input.integer, defval=26)
sigLen  = input(title="Signal Length", type=input.integer, defval=9)

// Get MACD values
[macdLine, signalLine, _] = macd(close, fastLen, slowLen, sigLen)

// Plot MACD values and line
plot(series=macdLine, color=#6495ED, linewidth=2)
plot(series=signalLine, color=color.orange, linewidth=2)

hline(price=0)

// Determine long and short conditions
entryCondition  = crossover(macdLine, signalLine)
exitCondition = crossunder(macdLine, signalLine)

// Submit orders
strategy.entry(id="Long Entry", long=true, when=entryCondition)
strategy.close("Long Entry", when=exitCondition)

The strategy works fine like it is, but I would like to add a stop loss of 5% from the entry price. How to accomplish this since substituting strategy.close("Long Entry", when=exitCondition) line for strategy.exit("Long Exit", from_entry="Long Entry", stop=strategy.position_avg_price * 0.95, when=exitCondition) doesn't work?

1

1 Answers

0
votes

Try this:

...
// Submit orders
strategy.entry(id="Long Entry", long=true, when=entryCondition)
strategy.exit("Long Exit", from_entry="Long Entry", stop=strategy.position_avg_price * 0.95)
strategy.close("Long Entry", when=exitCondition)