Reputation: 1
The issue is that when using a Pine script to enter a trade based on a MACD crossover and setting the stop loss and take profit levels based on the average true range, the stop loss and take profit levels are triggered as soon as the price moves just one tick. here is the code:
//@version=5
strategy("MACD + ATR Trading Strategy", overlay=true)
// Input variables
atr_length = input(14, title="ATR Length")
overbought_level = input(1.0, title="Overbought Level")
oversold_level = input(-1.0, title="Oversold Level")
// Calculate ATR
atr = ta.atr(atr_length)[1]
// Calculate MACD
macd_fast = input(12)
macd_slow = input(26)
macd_signal = input(9)
[macd_line, signal_line, _] = ta.macd(close, macd_fast, macd_slow, macd_signal)
// Determine long entry conditions
long_entry = ta.crossover(macd_line, signal_line) and macd_line < -atr
// Determine short entry conditions
short_entry = ta.crossunder(macd_line, signal_line) and macd_line > atr
// Submit long entry order
if (long_entry)
strategy.entry("Long", strategy.long)
strategy.exit('exit long', "Long", profit = close + 4 * atr, stop = close - 2 * atr)
// Submit short entry order
if (short_entry)
strategy.entry("Short", strategy.short)
strategy.exit('exit short', "Short", profit = close - 4 * atr, stop = close - 2 * atr)
I attempted to adjust the ATR levels to change the stop loss and take profit levels, by multiplying them, but this did not solve the problem of the levels being triggered too quickly. Additionally, I tried using different functions such as 'strategy.exit' and 'strategy.order' to exit the trades, but this also did not resolve the issue.
Upvotes: 0
Views: 768
Reputation: 21294
You should use the strategy.exit()
function in the global scope.
Also, note that the profit
argument of the strategy.exit()
function expects the profit target specified in ticks. What you want to use is the limit
argument which would be in price.
profit (series int/float) An optional parameter. Profit target (specified in ticks). If it is specified, a limit order is placed to exit market position when the specified amount of profit (in ticks) is reached. The default value is 'NaN'.
limit (series int/float) An optional parameter. Profit target (requires a specific price). If it is specified, a limit order is placed to exit market position at the specified price (or better). Priority of the parameter 'limit' is higher than priority of the parameter 'profit' ('limit' is used instead of 'profit', if its value is not 'NaN'). The default value is 'NaN'.
Upvotes: 0