Reputation: 11
I am kind of new to this stuff and would like some help with my pine script. I am trying to script a simple strategy which buys once 1 min, 5 min and 15 min MACD are all in dark green and sells when a candle closes under 9 ema. The issue is it's never synchronized it's doing different trades on all three time frames which should be the same trade on all of them. here is the code. Any help is greatly appreciated.
//@version=5
strategy("Multi Time Frame MACD Strategy", overlay=true)
// Input parameters
stopLossPercent = input.float(1.0, title="Stop Loss Percentage", minval=0.1, step=0.1)
emaLength = input.int(9, title="EMA Length", minval=1)
// Define MACD function
macd(src, fastLength, slowLength, signalSmoothing) =\>
fastMA = ta.ema(src, fastLength)
slowMA = ta.ema(src, slowLength)
macdLine = fastMA - slowMA
signalLine = ta.ema(macdLine, signalSmoothing)
\[macdLine, signalLine, macdLine - signalLine\]
// Get MACD values for different time frames
\[macdLine1m, signalLine1m, \_\] = request.security(syminfo.tickerid, "1", macd(close, 12, 26, 9))
\[macdLine5m, signalLine5m, \_\] = request.security(syminfo.tickerid, "5", macd(close, 12, 26, 9))
\[macdLine15m, signalLine15m, \_\] = request.security(syminfo.tickerid, "15", macd(close, 12, 26, 9))
// Conditions for MACD being in the green and crossed over
macdGreen1m = macdLine1m \> signalLine1m and macdLine1m \> 0
macdGreen5m = macdLine5m \> signalLine5m and macdLine5m \> 0
macdGreen15m = macdLine15m \> signalLine15m and macdLine15m \> 0
// Buy condition
buyCondition = macdGreen1m and macdGreen5m and macdGreen15m
// EMA for exit condition
ema = ta.ema(close, emaLength)
// Sell condition
sellCondition = close \< ema
// Plotting
plot(ema, color=color.orange, title="9 EMA")
// Strategy execution
if (buyCondition and not strategy.opentrades)
strategy.entry("Buy", strategy.long)
if (sellCondition)
strategy.close("Buy")
// Stop Loss
if (strategy.opentrades)
strategy.exit("Stop Loss", "Buy", stop=strategy.position_avg_price \* (1 - stopLossPercent / 100))
I am expecting it to make sure that it only takes trades when macd is dark green on all 3 time frames and hence it should be the same trade on the 3 time frames.
Upvotes: 1
Views: 27