OPEN-SOURCE SCRIPT

Hybrid Strategy with Position Control

317
//version=6
indicator('Hybrid Strategy with Position Control', overlay=true)

// === INPUTS ===
emaFastLen = input.int(8, 'Fast EMA')
emaSlowLen = input.int(21, 'Slow EMA')
rsiLen = input.int(14, 'RSI Length')
rsiOverbought = input.int(70, 'RSI Overbought')
rsiOversold = input.int(30, 'RSI Oversold')
macdFast = input.int(12, 'MACD Fast')
macdSlow = input.int(26, 'MACD Slow')
macdSignal = input.int(9, 'MACD Signal')

// === CALCULATIONS ===
emaFast = ta.ema(close, emaFastLen)
emaSlow = ta.ema(close, emaSlowLen)
rsi = ta.rsi(close, rsiLen)
[macdLine, signalLine, _] = ta.macd(close, macdFast, macdSlow, macdSignal)

// === POSITION TRACKING ===
var int position = 0 // 0 = no position, 1 = long, -1 = short

// === ENTRY CONDITIONS ===
longCondition = ta.crossover(emaFast, emaSlow) and rsi < rsiOverbought and macdLine > signalLine and position != 1
shortCondition = ta.crossunder(emaFast, emaSlow) and rsi > rsiOversold and macdLine < signalLine and position != -1

// === EXIT CONDITIONS (Optional logic for reset) ===
exitLong = ta.crossunder(emaFast, emaSlow)
exitShort = ta.crossover(emaFast, emaSlow)

// === SIGNAL PLOTS ===
buySignal = longCondition
sellSignal = shortCondition

plotshape(buySignal, title='Buy Signal', location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small, text='BUY')
plotshape(sellSignal, title='Sell Signal', location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small, text='SELL')

// === STATE MANAGEMENT ===
if (longCondition)
position := 1
if (shortCondition)
position := -1

// Reset position if trend reverses
if (exitLong and position == 1)
position := 0
if (exitShort and position == -1)
position := 0

// === PLOT EMAs ===
plot(emaFast, color=color.orange, title='Fast EMA')
plot(emaSlow, color=color.blue, title='Slow EMA')

Disclaimer

The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.