OPEN-SOURCE SCRIPT

VWAP + EMA9/21/50 + Ichimoku + RSI (M5) - Strict + TPSL

41
//version=5
indicator("VWAP + EMA9/21/50 + Ichimoku + RSI (M5) - Strict + TPSL", overlay=true, shorttitle="VWAP_EMA_ICH_RSI_TPSL")

// === Inputs ===
emaFastLen = input.int(9, "EMA Fast (9)")
emaMidLen = input.int(21, "EMA Mid (21)")
emaSlowLen = input.int(50, "EMA Slow (50)")

// Ichimoku inputs
tenkanLen = input.int(9, "Tenkan Sen Length")
kijunLen = input.int(26, "Kijun Sen Length")
senkouBLen = input.int(52, "Senkou B Length")
displacement = input.int(26, "Displacement")

// RSI
rsiLen = input.int(14, "RSI Length")
rsiThreshold = input.int(50, "RSI Threshold")

// VWAP option
useSessionVWAP = input.bool(true, "Use Session VWAP (true) / Daily VWAP (false)")

// Volume filter
useVolumeFilter = input.bool(true, "Enable Volume Filter")
volAvgLen = input.int(20, "Volume Avg Length")
volMultiplier = input.float(1.2, "Min Volume > avg *", step=0.1)

// Higher timeframe trend check
useHTF = input.bool(true, "Enable Higher-Timeframe Trend Check")
htfTF = input.string("60", "HTF timeframe (e.g. 60, 240, D)")

// Alerts / webhook
alertOn = input.bool(true, "Enable Alerts")
useWebhook = input.bool(true, "Send webhook on alerts")
webhookURL = input.string("", "Webhook URL (leave blank to set in alert)")

// TP/SL & Trailing inputs
useTP = input.bool(true, "Enable Take Profit (TP)")
tpTypeRR = input.bool(true, "TP as Risk-Reward ratio (true) / Fixed points (false)")
tpRR = input.float(1.5, "TP RR (e.g. 1.5)", step=0.1)
fixedTPpts = input.float(40.0, "Fixed TP (ticks/pips) if not RR")

useSL = input.bool(true, "Enable Stop Loss (SL)")
slTypeATR = input.bool(true, "SL as ATR-based (true) / Fixed points (false)")
atrLen = input.int(14, "ATR Length")
atrMult = input.float(1.5, "ATR Multiplier for SL", step=0.1)
fixedSLpts = input.float(20.0, "Fixed SL (ticks/pips) if not ATR")

useTrailing = input.bool(true, "Enable Trailing Stop")
trailType = input.string("ATR", "Trailing type: ATR or EMA", options=["ATR", "EMA"]) // "ATR" or "EMA"
trailATRmult = input.float(1.0, "Trailing ATR Multiplier", step=0.1)
trailEMAlen = input.int(9, "Trailing EMA Length (if EMA chosen)")
trailLockInPts = input.float(5.0, "Trail lock-in (min profit before trail active, pts)")

// Other
showArrows = input.bool(true, "Show Entry Arrows")

// === Calculations ===
ema9 = ta.ema(close, emaFastLen)
ema21 = ta.ema(close, emaMidLen)
ema50 = ta.ema(close, emaSlowLen)

// VWAP
vwapVal = ta.vwap

// Ichimoku
highestHighTenkan = ta.highest(high, tenkanLen)
lowestLowTenkan = ta.lowest(low, tenkanLen)
tenkan = (highestHighTenkan + lowestLowTenkan) / 2

highestHighKijun = ta.highest(high, kijunLen)
lowestLowKijun = ta.lowest(low, kijunLen)
kijun = (highestHighKijun + lowestLowKijun) / 2

highestHighSenkouB = ta.highest(high, senkouBLen)
lowestLowSenkouB = ta.lowest(low, senkouBLen)
senkouB = (highestHighSenkouB + lowestLowSenkouB) / 2
senkouA = (tenkan + kijun) / 2

// RSI
rsi = ta.rsi(close, rsiLen)

// Volume
volAvg = ta.sma(volume, volAvgLen)
volOk = not useVolumeFilter or (volume > volAvg * volMultiplier)

// Higher timeframe trend values
htf_close = request.security(syminfo.tickerid, htfTF, close)
htf_ema50 = request.security(syminfo.tickerid, htfTF, ta.ema(close, emaSlowLen))
htf_rsi = request.security(syminfo.tickerid, htfTF, ta.rsi(close, rsiLen))
htf_bull = htf_close > htf_ema50
htf_bear = htf_close < htf_ema50
htf_ok = not useHTF or (htf_bull and close > ema50) or (htf_bear and close < ema50)

// Trend filters (on current timeframe)
priceAboveVWAP = close > vwapVal
priceAboveEMA50 = close > ema50
priceAboveCloud = close > senkouA and close > senkouB

bullTrend = priceAboveVWAP and priceAboveEMA50 and priceAboveCloud
bearTrend = not priceAboveVWAP and not priceAboveEMA50 and not priceAboveCloud

// Pullback detection (price near EMA21 within tolerance)
tolPerc = input.float(0.35, "Pullback tolerance (%)", step=0.05) / 100.0
nearEMA21 = math.abs(close - ema21) <= ema21 * tolPerc

// Entry conditions
emaCrossUp = ta.crossover(ema9, ema21)
emaCrossDown = ta.crossunder(ema9, ema21)

longConditionBasic = bullTrend and (nearEMA21 or close >= vwapVal) and emaCrossUp and rsi > rsiThreshold
shortConditionBasic = bearTrend and (nearEMA21 or close <= vwapVal) and emaCrossDown and rsi < rsiThreshold

longCondition = longConditionBasic and volOk and htf_ok and (not useHTF or htf_bull) and (rsi > rsiThreshold)
shortCondition = shortConditionBasic and volOk and htf_ok and (not useHTF or htf_bear) and (rsi < rsiThreshold)

// More strict: require Tenkan > Kijun for bull and Tenkan < Kijun for bear
ichimokuAlign = (tenkan > kijun) ? 1 : (tenkan < kijun ? -1 : 0)
longCondition := longCondition and (ichimokuAlign == 1)
shortCondition := shortCondition and (ichimokuAlign == -1)

// ATR for SL / trailing
atr = ta.atr(atrLen)

// --- Trade management state variables ---
var float activeLongEntry = na
var float activeShortEntry = na
var float activeLongSL = na
var float activeShortSL = na
var float activeLongTP = na
var float activeShortTP = na
var float activeLongTrail = na
var float activeShortTrail = na

// Function to convert fixed points to price (assumes chart in points as price units)
fixedToPriceLong(p) => p
fixedToPriceShort(p) => p

// On signal, set entry, SL and TP
if longCondition
activeLongEntry := close
// SL
if useSL
if slTypeATR
activeLongSL := close - atr * atrMult
else
activeLongSL := close - fixedToPriceLong(fixedSLpts)
else
activeLongSL := na
// TP
if useTP
if tpTypeRR and useSL and not na(activeLongSL)
risk = activeLongEntry - activeLongSL
activeLongTP := activeLongEntry + risk * tpRR
else
activeLongTP := activeLongEntry + fixedToPriceLong(fixedTPpts)
else
activeLongTP := na
// reset short
activeShortEntry := na
activeShortSL := na
activeShortTP := na
// init trailing
activeLongTrail := activeLongSL

if shortCondition
activeShortEntry := close
if useSL
if slTypeATR
activeShortSL := close + atr * atrMult
else
activeShortSL := close + fixedToPriceShort(fixedSLpts)
else
activeShortSL := na
if useTP
if tpTypeRR and useSL and not na(activeShortSL)
riskS = activeShortSL - activeShortEntry
activeShortTP := activeShortEntry - riskS * tpRR
else
activeShortTP := activeShortEntry - fixedToPriceShort(fixedTPpts)
else
activeShortTP := na
// reset long
activeLongEntry := na
activeLongSL := na
activeLongTP := na
// init trailing
activeShortTrail := activeShortSL

// Trailing logic (update only when in profit beyond 'lock-in')
if not na(activeLongEntry) and useTrailing
// current unrealized profit in points
currProfitPts = close - activeLongEntry
if currProfitPts >= trailLockInPts
// declare candidate before use to avoid undeclared identifier errors
float candidate = na
if trailType == "ATR"
candidate := close - atr * trailATRmult
else
candidate := close - ta.ema(close, trailEMAlen)
// move trail stop up but never below initial SL
activeLongTrail := math.max(nz(activeLongTrail, activeLongSL), candidate)
// ensure trail never goes below initial SL if SL exists
if useSL and not na(activeLongSL)
activeLongTrail := math.max(activeLongTrail, activeLongSL)
// update SL to trailing
activeLongSL := activeLongTrail

if not na(activeShortEntry) and useTrailing
currProfitPtsS = activeShortEntry - close
if currProfitPtsS >= trailLockInPts
// declare candidateS before use
float candidateS = na
if trailType == "ATR"
candidateS := close + atr * trailATRmult
else
candidateS := close + ta.ema(close, trailEMAlen)
activeShortTrail := math.min(nz(activeShortTrail, activeShortSL), candidateS)
if useSL and not na(activeShortSL)
activeShortTrail := math.min(activeShortTrail, activeShortSL)
activeShortSL := activeShortTrail

// Detect TP/SL hits (for plotting & alerts)
longTPHit = not na(activeLongTP) and close >= activeLongTP
longSLHit = not na(activeLongSL) and close <= activeLongSL
shortTPHit = not na(activeShortTP) and close <= activeShortTP
shortSLHit = not na(activeShortSL) and close >= activeShortSL

if longTPHit or longSLHit
// reset long state after hit
activeLongEntry := na
activeLongSL := na
activeLongTP := na
activeLongTrail := na

if shortTPHit or shortSLHit
activeShortEntry := na
activeShortSL := na
activeShortTP := na
activeShortTrail := na

// Plot EMAs
p_ema9 = plot(ema9, title="EMA9", linewidth=1)
plot(ema21, title="EMA21", linewidth=1)
plot(ema50, title="EMA50", linewidth=2)

// Plot VWAP
plot(vwapVal, title="VWAP", linewidth=2, style=plot.style_line)

// Plot Ichimoku lines (Tenkan & Kijun)
plot(tenkan, title="Tenkan", linewidth=1)
plot(kijun, title="Kijun", linewidth=1)

// Plot cloud (senkouA & senkouB shifted forward)
plot(senkouA, title="Senkou A", offset=displacement, transp=60)
plot(senkouB, title="Senkou B", offset=displacement, transp=60)
fill(plot(senkouA, offset=displacement), plot(senkouB, offset=displacement), color = senkouA > senkouB ? color.new(color.green, 80) : color.new(color.red, 80))

// Plot active trade lines
plotshape(not na(activeLongEntry), title="Active Long", location=location.belowbar, color=color.new(color.green, 0), style=shape.circle, size=size.tiny)
plotshape(not na(activeShortEntry), title="Active Short", location=location.abovebar, color=color.new(color.red, 0), style=shape.circle, size=size.tiny)

plot(activeLongSL, title="Long SL", color=color.red, linewidth=2)
plot(activeLongTP, title="Long TP", color=color.green, linewidth=2)
plot(activeShortSL, title="Short SL", color=color.red, linewidth=2)
plot(activeShortTP, title="Short TP", color=color.green, linewidth=2)

// Arrows / labels
if showArrows
if longCondition
label.new(bar_index, low, "BUY", style=label.style_label_up, color=color.green, textcolor=color.white, size=size.small)
if shortCondition
label.new(bar_index, high, "SELL", style=label.style_label_down, color=color.red, textcolor=color.white, size=size.small)

// Alerts
// alertcondition must be declared in global scope so TradingView can create alerts from them
alertcondition(longCondition, "VWAP+EMA+Ichimoku+RSI — BUY (STRICT)", "BUY signal from VWAP+EMA+Ichimoku+RSI (STRICT)")
alertcondition(shortCondition, "VWAP+EMA+Ichimoku+RSI — SELL (STRICT)", "SELL signal from VWAP+EMA+Ichimoku+RSI (STRICT)")

// Runtime alerts (still use alert() to trigger immediate alerts; webhook is added in TradingView Alert dialog)
if alertOn
if longCondition
alert("VWAP+EMA+Ichimoku+RSI — BUY (STRICT)", alert.freq_once_per_bar_close)
if shortCondition
alert("VWAP+EMA+Ichimoku+RSI — SELL (STRICT)", alert.freq_once_per_bar_close)

// Alerts for TP/SL hits
if longTPHit
alert("LONG TP HIT", alert.freq_once_per_bar_close)
if longSLHit
alert("LONG SL HIT", alert.freq_once_per_bar_close)
if shortTPHit
alert("SHORT TP HIT", alert.freq_once_per_bar_close)
if shortSLHit
alert("SHORT SL HIT", alert.freq_once_per_bar_close)

// Info table
var table info = table.new(position.top_right, 1, 8)
if barstate.islast
table.cell(info, 0, 0, text = 'Trend: ' + (bullTrend ? 'Bull' : bearTrend ? 'Bear' : 'Neutral'))
table.cell(info, 0, 1, text = 'EMA9/21/50: ' + str.tostring(ema9, format.mintick) + ' / ' + str.tostring(ema21, format.mintick) + ' / ' + str.tostring(ema50, format.mintick))
table.cell(info, 0, 2, text = 'VWAP: ' + str.tostring(vwapVal, format.mintick))
table.cell(info, 0, 3, text = 'RSI: ' + str.tostring(rsi, format.mintick))
table.cell(info, 0, 4, text = 'Vol OK: ' + (volOk ? 'Yes' : 'No'))
table.cell(info, 0, 5, text = 'HTF: ' + htfTF + ' ' + (htf_bull ? 'Bull' : htf_bear ? 'Bear' : 'Neutral'))
table.cell(info, 0, 6, text = 'ActiveLong: ' + (not na(activeLongEntry) ? 'Yes' : 'No'))
table.cell(info, 0, 7, text = 'ActiveShort: ' + (not na(activeShortEntry) ? 'Yes' : 'No'))

// End of script

Thông báo miễn trừ trách nhiệm

Thông tin và các ấn phẩm này không nhằm mục đích, và không cấu thành, lời khuyên hoặc khuyến nghị về tài chính, đầu tư, giao dịch hay các loại khác do TradingView cung cấp hoặc xác nhận. Đọc thêm tại Điều khoản Sử dụng.