本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("aiTrendview · Options Buyer (BUY Only)", shorttitle="aiTV Options Buyer", overlay=false, max_lines_count=500, max_labels_count=500, precision=2)
// Designed for 1-min BANKNIFTY / NIFTY option (CE or PE) charts. Prints BUY signals only — buying the option premium.
// Works identically on a Call chart and a Put chart: it looks for the premium bottom of the chart it is applied to.
// ~~ Colours {
color cBlue = #0B3D91
color cBlue2 = #1E5AA8
color cBlueL = #E8F0FB
color cWhite = #FFFFFF
color cRed = #C8102E
color cNavy = #0B1F44
color cGrey = #6B7280
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Tooltips {
var string tScore = "Number of confluence checks (out of 8, or 7 when OI data is unavailable) that must pass before a BUY can print. Higher = fewer, cleaner signals."
var string tCandle = "Requires a bullish bar that closes above the previous bar's high, or engulfs the previous bar. Filters most false bottoms."
var string tCool = "Minimum number of bars between two BUY signals."
var string tSweep = "Bar must trade below the lowest low of this many prior bars and close back above it — a buy-side liquidity grab."
var string tDD = "Premium must have fallen at least this % from its recent high. We only buy after a discount, never on a spike."
var string tSL = "Stoploss = lowest low of N bars minus an ATR buffer, but never further than the Max SL % cap below entry."
var string tTrail = "Stop stays fixed until price touches Target 1. After that it steps up (entry → T1 → T2 → T3 → T4) and trails the highs by ATR × multiplier, and keeps trailing after T5 until hit."
var string tUnder = "Auto reads BANKNIFTY / NIFTY / FINNIFTY / MIDCPNIFTY / SENSEX from the chart ticker. Use Manual for anything else."
var string tStrike = "Auto parses strike and CE/PE from TradingView option tickers such as BANKNIFTY251125C52000. Use Manual if parsing fails."
var string tOI = "Window used to classify Long Buildup / Short Covering / Short Buildup / Long Unwinding from price and OI change."
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Inputs {
grpS = "Signal Engine"
rsiLen = input.int(14, "RSI Length", minval=2, group=grpS)
osLevel = input.float(30, "Oversold Level", minval=5, maxval=50, group=grpS)
osLookback = input.int(8, "Oversold Memory (bars)", minval=1, group=grpS)
sweepLen = input.int(15, "Liquidity Sweep Lookback (bars)", minval=3, group=grpS, tooltip=tSweep)
flowLen = input.int(5, "Buy/Sell Flow Window (bars)", minval=2, group=grpS)
buyPctMin = input.float(55, "Min Buy Volume % in Window", minval=50, maxval=90, group=grpS)
volLen = input.int(20, "Volume Average Length", minval=5, group=grpS)
volMult = input.float(1.2, "Volume Spike × Average", minval=0.5, step=0.1, group=grpS)
oiLen = input.int(5, "OI Change Window (bars)", minval=1, group=grpS, tooltip=tOI)
ddLen = input.int(30, "Drawdown Lookback (bars)", minval=5, group=grpS)
ddMin = input.float(15, "Min Premium Drawdown %", minval=0, step=1, group=grpS, tooltip=tDD)
minScore = input.int(6, "Min Confluence Score", minval=1, maxval=8, group=grpS, tooltip=tScore)
needCandle = input.bool(true, "Require Bullish Confirmation Candle", group=grpS, tooltip=tCandle)
cooldown = input.int(10, "Cooldown Between Signals (bars)", minval=0, group=grpS, tooltip=tCool)
useTrendF = input.bool(false,"Block BUY while premium is below a falling EMA", group=grpS)
emaLen = input.int(50, "Trend EMA Length", minval=5, group=grpS)
sess = input.session("0918-1500", "BUY Signal Window (IST)", group=grpS)
grpO = "Option / Underlying"
underMode = input.string("Auto", "Underlying Symbol", options=["Auto", "Manual"], group=grpO, tooltip=tUnder)
underMan = input.symbol("NSE:BANKNIFTY", "Manual Underlying", group=grpO)
strikeMode = input.string("Auto", "Strike & Option Type", options=["Auto", "Manual"], group=grpO, tooltip=tStrike)
strikeMan = input.float(52000, "Manual Strike", minval=0, group=grpO)
typeMan = input.string("CE", "Manual Option Type", options=["CE", "PE"], group=grpO)
grpR = "Risk Management"
slLen = input.int(10, "Structural SL Lookback (bars)", minval=2, group=grpR, tooltip=tSL)
slAtrBuf = input.float(0.5, "SL Buffer (× ATR)", minval=0, step=0.1, group=grpR)
slMaxPct = input.float(20, "Max SL % from Entry (cap)", minval=1, step=0.5, group=grpR)
atrLen = input.int(14, "ATR Length", minval=1, group=grpR)
t1Pct = input.float(10, "Target 1 %", minval=0.5, step=0.5, group=grpR)
t2Pct = input.float(20, "Target 2 %", minval=0.5, step=0.5, group=grpR)
t3Pct = input.float(30, "Target 3 %", minval=0.5, step=0.5, group=grpR)
t4Pct = input.float(40, "Target 4 %", minval=0.5, step=0.5, group=grpR)
t5Pct = input.float(50, "Target 5 %", minval=0.5, step=0.5, group=grpR)
trailOn = input.bool(true, "Enable Trailing Stoploss", group=grpR, tooltip=tTrail)
trailAtr = input.float(1.5, "ATR Trailing Multiplier", minval=0.1, step=0.1, group=grpR)
sqOffExit = input.bool(false,"Exit open trade at square-off time (else hold until SL/TSL)", group=grpR)
sqHour = input.int(15, "Square-off Hour (IST)", minval=9, maxval=15, group=grpR)
sqMin = input.int(20, "Square-off Minute (IST)", minval=0, maxval=59, group=grpR)
grpD = "Dashboard"
tablePosition = input.string("Bottom Center", "Table Position", options=["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group=grpD)
tableSize = input.string("Normal", "Table Size", options=["Tiny", "Small", "Normal", "Large"], group=grpD)
showVWAP = input.bool(true, "Plot VWAP", group=grpD)
showEMA = input.bool(false, "Plot Trend EMA", group=grpD)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Utilities {
f_num(float x) => na(x) ? "—" : str.tostring(x, "#.##")
f_pct(float x) => na(x) ? "—" : str.tostring(x, "#.#") + "%"
f_sgn(float x) => na(x) ? "—" : (x > 0 ? "+" : "") + str.tostring(x, "#.##")
f_big(float x) =>
na(x) ? "N/A" :
math.abs(x) >= 1e7 ? str.tostring(x / 1e7, "#.##") + " Cr" :
math.abs(x) >= 1e5 ? str.tostring(x / 1e5, "#.##") + " L" :
math.abs(x) >= 1e3 ? str.tostring(x / 1e3, "#.#") + " K" :
str.tostring(x, "#")
f_tick(bool b) => b ? "✔" : "✖"
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Option contract detection (strike, type, underlying, intrinsic) {
var string tickMatch = str.match(syminfo.ticker, "[CP][0-9]+$")
bool autoOK = str.length(tickMatch) > 1
string optType = (strikeMode == "Manual" or not autoOK) ? typeMan : (str.substring(tickMatch, 0, 1) == "C" ? "CE" : "PE")
float strike = (strikeMode == "Manual" or not autoOK) ? strikeMan : str.tonumber(str.substring(tickMatch, 1))
bool isCE = optType == "CE"
string autoUnder = str.startswith(syminfo.ticker, "BANKNIFTY") ? "NSE:BANKNIFTY" :
str.startswith(syminfo.ticker, "FINNIFTY") ? "NSE:CNXFINANCE" :
str.startswith(syminfo.ticker, "MIDCPNIFTY") ? "NSE:NIFTY_MID_SELECT" :
str.startswith(syminfo.ticker, "NIFTY") ? "NSE:NIFTY" :
str.startswith(syminfo.ticker, "SENSEX") ? "BSE:SENSEX" : "NSE:BANKNIFTY"
string underSym = underMode == "Manual" ? underMan : autoUnder
float spot = request.security(underSym, timeframe.period, close, ignore_invalid_symbol=true)
float intrinsic = na(spot) ? na : isCE ? math.max(spot - strike, 0.0) : math.max(strike - spot, 0.0)
float timeVal = na(spot) ? na : close - intrinsic
string moneyness = na(spot) ? "N/A" : intrinsic > 0 ? "ITM" : math.abs(spot - strike) <= strike * 0.002 ? "ATM" : "OTM"
float spotChg = spot - spot[1]
// Underlying must be moving in the option's favour (up for CE, down for PE)
bool spotOK = na(spot) ? true : isCE ? spotChg > 0 : spotChg < 0
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Open Interest {
float oi = request.security(syminfo.tickerid + "_OI", timeframe.period, close, ignore_invalid_symbol=true)
bool hasOI = not na(oi)
float oiChg = oi - oi[1]
float oiChgW = oi - oi[oiLen]
float pxChgW = close - close[oiLen]
float pxChg1 = close - close[1]
f_build(float px, float oiD) =>
not hasOI ? "N/A" :
px > 0 and oiD > 0 ? "Long Buildup" :
px > 0 and oiD < 0 ? "Short Covering" :
px < 0 and oiD > 0 ? "Short Buildup" :
px < 0 and oiD < 0 ? "Long Unwinding" : "Flat"
string buildW = f_build(pxChgW, oiChgW)
string build1 = f_build(pxChg1, oiChg)
bool bullBuild1 = build1 == "Short Covering" or build1 == "Long Buildup"
// OI check: short covering / long buildup in the window, OR the first bullish OI bar right after a short buildup phase (classic bottom)
bool oiOK = hasOI and (buildW == "Short Covering" or buildW == "Long Buildup" or (bullBuild1 and buildW[1] == "Short Buildup"))
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Per-bar features {
float atr = ta.atr(atrLen)
float rsi = ta.rsi(close, rsiLen)
float vwap = ta.vwap(hlc3)
float emaT = ta.ema(close, emaLen)
float volAvg = ta.sma(volume, volLen)
float barRange = high - low
// Buy / Sell volume split by where the bar closed inside its range
float buyVol = barRange > 0 ? volume * (close - low) / barRange : volume * 0.5
float sellVol = volume - buyVol
float buyVolW = math.sum(buyVol, flowLen)
float sellVolW = math.sum(sellVol, flowLen)
float totW = buyVolW + sellVolW
float buyPct = totW > 0 ? buyVolW / totW * 100 : 50
float sellPct = 100 - buyPct
float cumDelta = buyVolW - sellVolW
float barBuyPct = volume > 0 ? buyVol / volume * 100 : 50
float volRatio = volAvg > 0 ? volume / volAvg : 0
// Liquidity sweep: trade below prior lows, close back above them
float priorLow = ta.lowest(low, sweepLen)[1]
bool sweep = low < priorLow and close > priorLow
bool sweepRecent = math.sum(sweep ? 1 : 0, 3) > 0
float lowerWick = math.min(open, close) - low
float wickRatio = barRange > 0 ? lowerWick / barRange : 0
// Premium drawdown from recent high
float hh = ta.highest(high, ddLen)
float dd = hh > 0 ? (hh - close) / hh * 100 : 0
// Structural low for stoploss
float structLow = ta.lowest(low, slLen)
// Session / time (IST)
bool inSess = not na(time(timeframe.period, sess, "Asia/Kolkata"))
int istMins = hour(time, "Asia/Kolkata") * 60 + minute(time, "Asia/Kolkata")
bool sqOffNow = timeframe.isintraday and istMins >= sqHour * 60 + sqMin
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Confluence checks (8) {
bool osOK = ta.lowest(rsi, osLookback) < osLevel and rsi > rsi[1] // 1. oversold and turning up
bool liqOK = sweepRecent or (wickRatio >= 0.5 and close > open) // 2. buy-side liquidity grab / rejection wick
bool volOK = buyPct >= buyPctMin and (volRatio >= volMult or barBuyPct > 60) // 3. buy volume dominance
// oiOK // 4. short covering / long buildup
// spotOK // 5. underlying moving in favour
bool engulf = close > open and close[1] < open[1] and open <= close[1] and close > open[1]
bool candleOK = close > open and (close > high[1] or engulf) // 6. bullish confirmation bar
bool vwapOK = close < vwap or ta.crossover(close, vwap) // 7. buying at a discount / VWAP reclaim
bool ddOK = dd >= ddMin // 8. premium already discounted
int score = (osOK ? 1 : 0) + (liqOK ? 1 : 0) + (volOK ? 1 : 0) + (oiOK ? 1 : 0) + (spotOK ? 1 : 0) + (candleOK ? 1 : 0) + (vwapOK ? 1 : 0) + (ddOK ? 1 : 0)
int maxScore = hasOI ? 8 : 7
int minReq = hasOI ? minScore : math.max(1, minScore - 1)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Trade state {
var float entryPx = na
var float slPx = na
var float tslPx = na
var float t1 = na
var float t2 = na
var float t3 = na
var float t4 = na
var float t5 = na
var int tgtHit = 0
var int entryBar = na
var bool inTrade = false
var int lastSigBar = -100000
var float maxPts = 0.0
var int sigCount = 0
var int t1Count = 0
var int slCount = 0
var string lastResult = "—"
var float lastPts = na
var line lnE = na
var line lnS = na
var line lnT = na
var label lbE = na
var label lbS = na
var label lbT = na
var label lbP = na
var array<line> tLines = array.new<line>()
var array<label> tLabels = array.new<label>()
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ BUY signal {
bool trendOK = not useTrendF or not (close < emaT and emaT < emaT[1])
bool rawBuy = score >= minReq and (not needCandle or candleOK) and inSess and trendOK and volume > 0 and not sqOffNow
bool buySignal = rawBuy and not inTrade and (bar_index - lastSigBar) > cooldown and barstate.isconfirmed
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Trade management: targets, trailing stop (after T1), exit on stop only {
bool exitNow = false
string exitReason = ""
string hitTxt = ""
if inTrade and bar_index > entryBar
if low <= tslPx
exitNow := true
exitReason := tslPx >= entryPx ? "TSL" : "SL"
else
if tgtHit < 1 and high >= t1
tgtHit := 1
t1Count += 1
hitTxt := "T1 ✔"
if tgtHit < 2 and high >= t2
tgtHit := 2
hitTxt := hitTxt + (hitTxt == "" ? "" : " ") + "T2 ✔"
if tgtHit < 3 and high >= t3
tgtHit := 3
hitTxt := hitTxt + (hitTxt == "" ? "" : " ") + "T3 ✔"
if tgtHit < 4 and high >= t4
tgtHit := 4
hitTxt := hitTxt + (hitTxt == "" ? "" : " ") + "T4 ✔"
if tgtHit < 5 and high >= t5
tgtHit := 5
hitTxt := hitTxt + (hitTxt == "" ? "" : " ") + "T5 ✔"
maxPts := math.max(maxPts, high - entryPx)
if hitTxt != ""
label.new(bar_index, high, hitTxt, style=label.style_label_down, color=cBlue2, textcolor=cWhite, size=size.tiny, force_overlay=true)
alert("aiTV Options Buyer: " + hitTxt + " on " + syminfo.ticker, alert.freq_once_per_bar_close)
// Trailing stop only after Target 1 has been touched; keeps trailing after T5
if trailOn and tgtHit >= 1
float stepLvl = tgtHit == 1 ? entryPx : tgtHit == 2 ? t1 : tgtHit == 3 ? t2 : tgtHit == 4 ? t3 : t4
tslPx := math.max(tslPx, math.max(stepLvl, high - atr * trailAtr))
if not exitNow and sqOffExit and sqOffNow
exitNow := true
exitReason := "SQ-OFF"
if exitNow
float exitPx = exitReason == "SQ-OFF" ? close : tslPx
lastPts := exitPx - entryPx
lastResult := exitReason + " " + f_sgn(lastPts) + " (" + f_sgn(lastPts / entryPx * 100) + "%)"
if exitReason == "SL"
slCount += 1
bool isLoss = lastPts < 0
label.new(bar_index, isLoss ? low : high, "EXIT " + exitReason + "\n" + f_sgn(lastPts) + " pts " + f_sgn(lastPts / entryPx * 100) + "%",
style=isLoss ? label.style_label_up : label.style_label_down,
color=isLoss ? cRed : cBlue, textcolor=cWhite, size=size.tiny, force_overlay=true)
alert("aiTV Options Buyer: trade closed (" + exitReason + ") " + f_sgn(lastPts) + " pts on " + syminfo.ticker, alert.freq_once_per_bar_close)
// remove live level tags (lines stay on chart as a record)
label.delete(lbE)
label.delete(lbS)
label.delete(lbT)
label.delete(lbP)
if tLabels.size() > 0
for i = 0 to tLabels.size() - 1
label.delete(tLabels.get(i))
tLabels.clear()
inTrade := false
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ New BUY: entry, stoploss, 5 targets, drawings {
f_tag(float y, string txt, color bg) =>
label.new(bar_index + 1, y, txt, style=label.style_label_left, color=bg, textcolor=cWhite, size=size.tiny, force_overlay=true)
if buySignal
entryPx := close
float rawSL = structLow - atr * slAtrBuf
float capSL = close * (1 - slMaxPct / 100)
slPx := math.max(math.max(rawSL, capSL), syminfo.mintick)
tslPx := slPx
t1 := entryPx * (1 + t1Pct / 100)
t2 := entryPx * (1 + t2Pct / 100)
t3 := entryPx * (1 + t3Pct / 100)
t4 := entryPx * (1 + t4Pct / 100)
t5 := entryPx * (1 + t5Pct / 100)
tgtHit := 0
inTrade := true
entryBar := bar_index
lastSigBar := bar_index
sigCount += 1
maxPts := 0.0
lnE := line.new(bar_index, entryPx, bar_index + 1, entryPx, color=cBlue, width=2, force_overlay=true)
lnS := line.new(bar_index, slPx, bar_index + 1, slPx, color=cRed, width=2, force_overlay=true)
lnT := line.new(bar_index, tslPx, bar_index + 1, tslPx, color=cRed, width=1, style=line.style_dashed, force_overlay=true)
tLines.clear()
tLines.push(line.new(bar_index, t1, bar_index + 1, t1, color=cBlue2, width=1, style=line.style_dotted, force_overlay=true))
tLines.push(line.new(bar_index, t2, bar_index + 1, t2, color=cBlue2, width=1, style=line.style_dotted, force_overlay=true))
tLines.push(line.new(bar_index, t3, bar_index + 1, t3, color=cBlue2, width=1, style=line.style_dotted, force_overlay=true))
tLines.push(line.new(bar_index, t4, bar_index + 1, t4, color=cBlue2, width=1, style=line.style_dotted, force_overlay=true))
tLines.push(line.new(bar_index, t5, bar_index + 1, t5, color=cBlue2, width=1, style=line.style_dotted, force_overlay=true))
lbE := f_tag(entryPx, "ENTRY " + f_num(entryPx), cBlue)
lbS := f_tag(slPx, "SL " + f_num(slPx), cRed)
lbT := f_tag(tslPx, "TSL " + f_num(tslPx), color.new(cRed, 30))
tLabels.clear()
tLabels.push(f_tag(t1, "T1 " + f_num(t1), cBlue2))
tLabels.push(f_tag(t2, "T2 " + f_num(t2), cBlue2))
tLabels.push(f_tag(t3, "T3 " + f_num(t3), cBlue2))
tLabels.push(f_tag(t4, "T4 " + f_num(t4), cBlue2))
tLabels.push(f_tag(t5, "T5 " + f_num(t5), cBlue2))
lbP := label.new(bar_index + 1, close, "", style=label.style_label_left, color=cBlue, textcolor=cWhite, size=size.small, force_overlay=true)
label.new(bar_index, low, "BUY " + optType + "\nEntry " + f_num(entryPx) + "\nSL " + f_num(slPx) + "\nScore " + str.tostring(score) + "/" + str.tostring(maxScore),
style=label.style_label_up, color=cBlue, textcolor=cWhite, size=size.small, force_overlay=true)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Live update of lines, level tags and P&L tag while in trade {
float openPnl = inTrade ? close - entryPx : na
float openPnlPct = inTrade ? openPnl / entryPx * 100 : na
if inTrade
line.set_x2(lnE, bar_index)
line.set_x2(lnS, bar_index)
line.set_x2(lnT, bar_index)
line.set_y1(lnT, tslPx)
line.set_y2(lnT, tslPx)
label.set_x(lbE, bar_index + 1)
label.set_x(lbS, bar_index + 1)
label.set_x(lbT, bar_index + 1)
label.set_y(lbT, tslPx)
label.set_text(lbT, "TSL " + f_num(tslPx) + (tgtHit >= 1 ? " ▲" : " (fixed)"))
label.set_color(lbT, tslPx >= entryPx ? cBlue2 : color.new(cRed, 30))
if tLines.size() > 0
for i = 0 to tLines.size() - 1
line.set_x2(tLines.get(i), bar_index)
label.set_x(tLabels.get(i), bar_index + 1)
if tgtHit > i
label.set_text(tLabels.get(i), "T" + str.tostring(i + 1) + " ✔ " + f_num(tLines.get(i).get_y1()))
// P&L tag beside the live price
label.set_x(lbP, bar_index + 1)
label.set_y(lbP, close)
label.set_text(lbP, "P&L " + f_sgn(openPnl) + " (" + f_sgn(openPnlPct) + "%)")
label.set_color(lbP, openPnl >= 0 ? cBlue : cRed)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Plots & alerts {
plot(showVWAP ? vwap : na, "VWAP", color=color.new(cBlue2, 0), linewidth=1, force_overlay=true)
plot(showEMA ? emaT : na, "Trend EMA", color=color.new(cGrey, 0), linewidth=1, force_overlay=true)
// Pane plots (behind the dashboard): confluence score vs required minimum
plot(score, "Confluence Score", style=plot.style_columns, color=score >= minReq ? color.new(cBlue2, 30) : color.new(cRed, 60))
plot(minReq, "Min Score", style=plot.style_stepline, color=cRed, linewidth=1)
alertcondition(buySignal, "aiTV BUY Signal", "aiTV Options Buyer: BUY {{ticker}} @ {{close}}")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Dashboard table — 12 columns × 7 rows, sized for 1366 px screens {
var table tb = table.new(position.bottom_center, 12, 7, bgcolor=cWhite, border_width=1, border_color=color.new(cBlue, 78), frame_width=2, frame_color=cBlue)
var bool merged = false
string headerSize = tableSize == "Tiny" ? size.small : tableSize == "Small" ? size.small : tableSize == "Large" ? size.large : size.normal
string valSize = tableSize == "Tiny" ? size.tiny : tableSize == "Small" ? size.small : tableSize == "Large" ? size.large : size.normal
string lblSize = tableSize == "Tiny" ? size.tiny : tableSize == "Small" ? size.tiny : tableSize == "Large" ? size.normal : size.small
// Text progress bar: v out of mx, n segments
f_bar(float v, float mx, int n) =>
int k = na(v) or mx <= 0 ? 0 : int(math.round(math.max(0.0, math.min(1.0, v / mx)) * n))
string s = ""
for i = 1 to n
s += i <= k ? "█" : "░"
s
f_lbl(int c, int r, string txt) =>
table.cell(tb, c, r, txt, text_color=cBlue2, bgcolor=cBlueL, text_size=lblSize, text_halign=text.align_center)
f_val(int c, int r, string txt, color tc) =>
table.cell(tb, c, r, txt, text_color=tc, bgcolor=cWhite, text_size=valSize, text_halign=text.align_center)
f_sec(int c, int r, string txt) =>
table.cell(tb, c, r, txt, text_color=cWhite, bgcolor=cBlue2, text_size=lblSize, text_halign=text.align_center)
f_kv(int c, int r, string k, string v, color tc) =>
f_lbl(c, r, k)
f_val(c, r + 1, v, tc)
if barstate.islast
table.set_position(tb,
tablePosition == "Top Left" ? position.top_left :
tablePosition == "Top Center" ? position.top_center :
tablePosition == "Top Right" ? position.top_right :
tablePosition == "Middle Left" ? position.middle_left :
tablePosition == "Middle Center" ? position.middle_center :
tablePosition == "Middle Right" ? position.middle_right :
tablePosition == "Bottom Left" ? position.bottom_left :
tablePosition == "Bottom Right" ? position.bottom_right : position.bottom_center)
if not merged
table.merge_cells(tb, 0, 0, 11, 0) // header
table.merge_cells(tb, 0, 1, 11, 1) // TRADE PLAN band title
table.merge_cells(tb, 0, 4, 3, 4) // OPTION DATA
table.merge_cells(tb, 4, 4, 7, 4) // FLOW & OI
table.merge_cells(tb, 8, 4, 11, 4) // MOMENTUM & SCORE
merged := true
// ---- Derived display values ----
float slPctNow = na(entryPx) ? na : (slPx - entryPx) / entryPx * 100
float tslPctNow = na(entryPx) ? na : (tslPx - entryPx) / entryPx * 100
float rr = na(entryPx) or entryPx - slPx <= 0 ? na : (t1 - entryPx) / (entryPx - slPx)
string statusTxt = inTrade ? "● LONG " + f_sgn(openPnl) + " (" + f_sgn(openPnlPct) + "%)" : na(entryPx) ? "○ WAITING FOR BUY" : "○ FLAT"
color statusCol = inTrade ? (openPnl >= 0 ? cBlue : cRed) : cGrey
color buildCol = buildW == "Short Covering" or buildW == "Long Buildup" ? cBlue : buildW == "Short Buildup" or buildW == "Long Unwinding" ? cRed : cGrey
string rsiZone = rsi < osLevel ? "OVERSOLD" : osOK ? "RECOVERY" : rsi > 70 ? "OVERBOUGHT" : "NEUTRAL"
color rsiCol = rsi < osLevel ? cBlue : rsi > 70 ? cRed : cNavy
bool trUp = close > emaT and emaT > emaT[1]
bool trDn = close < emaT and emaT < emaT[1]
string trendTxt = trUp ? "▲ UP" : trDn ? "▼ DOWN" : "► SIDEWAYS"
color trendCol = trUp ? cBlue : trDn ? cRed : cGrey
string winTxt = sqOffNow ? "SQ-OFF" : inSess ? "OPEN" : "CLOSED"
color winCol = sqOffNow ? cRed : inSess ? cBlue : cGrey
string oiChgTxt = hasOI ? (oiChgW > 0 ? "+" : "") + f_big(oiChgW) : "N/A"
string tfTxt = timeframe.period + (timeframe.isintraday and not timeframe.isseconds ? "m" : "")
// ---- Header ----
table.cell(tb, 0, 0, "aiTrendview | OPTIONS BUYER | " + syminfo.ticker + " · " + tfTxt + " · " + optType + " · BUY-ONLY",
text_color=cWhite, bgcolor=cBlue, text_size=headerSize, text_halign=text.align_center)
// ================= BAND 1 : TRADE PLAN (rows 1-3) =================
f_sec(0, 1, "TRADE PLAN · stop stays fixed until T1, then trails · exit only on SL / TSL")
f_kv(0, 2, "STATUS · OPEN P&L", statusTxt, statusCol)
f_kv(1, 2, "ENTRY", f_num(entryPx), cBlue)
f_kv(2, 2, "STOPLOSS", f_num(slPx) + " " + f_pct(slPctNow), cRed)
f_kv(3, 2, "TRAILING SL", f_num(tslPx) + " " + f_sgn(tslPctNow) + "%" + (inTrade and tgtHit >= 1 ? " ▲" : ""), tslPx >= entryPx ? cBlue : cRed)
f_kv(4, 2, "T1 +" + f_pct(t1Pct), f_num(t1) + (tgtHit >= 1 ? " ✔" : ""), tgtHit >= 1 ? cBlue : cNavy)
f_kv(5, 2, "T2 +" + f_pct(t2Pct), f_num(t2) + (tgtHit >= 2 ? " ✔" : ""), tgtHit >= 2 ? cBlue : cNavy)
f_kv(6, 2, "T3 +" + f_pct(t3Pct), f_num(t3) + (tgtHit >= 3 ? " ✔" : ""), tgtHit >= 3 ? cBlue : cNavy)
f_kv(7, 2, "T4 +" + f_pct(t4Pct), f_num(t4) + (tgtHit >= 4 ? " ✔" : ""), tgtHit >= 4 ? cBlue : cNavy)
f_kv(8, 2, "T5 +" + f_pct(t5Pct), f_num(t5) + (tgtHit >= 5 ? " ✔" : ""), tgtHit >= 5 ? cBlue : cNavy)
f_kv(9, 2, "PROGRESS · MAX PTS", f_bar(tgtHit, 5, 5) + " " + str.tostring(tgtHit) + "/5 · " + f_num(maxPts), tgtHit > 0 ? cBlue : cGrey)
f_kv(10, 2, "R : R (T1) · LAST RESULT", (na(rr) ? "—" : "1:" + str.tostring(rr, "#.##")) + " · " + lastResult, na(lastPts) ? cNavy : lastPts >= 0 ? cBlue : cRed)
f_kv(11, 2, "WINDOW · SIGNALS · T1 · SL", winTxt + " · " + str.tostring(sigCount) + " · " + str.tostring(t1Count) + " · " + str.tostring(slCount), winCol)
// ================= BAND 2 : OPTION · FLOW · MOMENTUM (rows 4-6) =================
f_sec(0, 4, "OPTION DATA")
f_sec(4, 4, "FLOW & OPEN INTEREST")
f_sec(8, 4, "MOMENTUM & SCORE")
f_kv(0, 5, "SPOT " + underSym, f_num(spot) + " " + f_sgn(spotChg), na(spotChg) ? cGrey : spotChg >= 0 ? cBlue : cRed)
f_kv(1, 5, "STRIKE · TYPE · MONEYNESS", f_num(strike) + " " + optType + " " + moneyness, moneyness == "ITM" ? cBlue : moneyness == "OTM" ? cRed : cNavy)
f_kv(2, 5, "INTRINSIC · TIME VALUE", f_num(intrinsic) + " · " + f_num(timeVal), cBlue)
f_kv(3, 5, "VWAP · DRAWDOWN (MIN " + f_pct(ddMin) + ")", f_num(vwap) + " " + f_sgn(close - vwap) + " · " + f_pct(dd), close >= vwap ? cBlue : cRed)
f_kv(4, 5, "OPEN INTEREST", f_big(oi), cNavy)
f_kv(5, 5, "OI CHG (" + str.tostring(oiLen) + "B) · BUILDUP", oiChgTxt + " · " + buildW, buildCol)
f_kv(6, 5, "BUY VOLUME % (" + str.tostring(flowLen) + "B)", f_bar(buyPct, 100, 5) + " " + f_pct(buyPct), buyPct >= 50 ? cBlue : cRed)
f_kv(7, 5, "VOL vs AVG · SWEEP", f_bar(volRatio, 2, 5) + " " + str.tostring(volRatio, "#.##") + "× · " + (sweep ? "NOW" : sweepRecent ? "RECENT" : "NO"), volRatio >= volMult ? cBlue : cNavy)
f_kv(8, 5, "RSI " + str.tostring(rsiLen) + " · " + rsiZone, f_bar(rsi, 100, 5) + " " + f_num(rsi), rsiCol)
f_kv(9, 5, "TREND EMA " + str.tostring(emaLen), trendTxt, trendCol)
f_kv(10, 5, "CONFLUENCE (MIN " + str.tostring(minReq) + ")", f_bar(score, maxScore, maxScore) + " " + str.tostring(score) + "/" + str.tostring(maxScore), score >= minReq ? cBlue : cRed)
f_kv(11, 5, "OS LQ VL OI SP CD VW DD", f_tick(osOK) + " " + f_tick(liqOK) + " " + f_tick(volOK) + " " + (hasOI ? f_tick(oiOK) : "–") + " " + f_tick(spotOK) + " " + f_tick(candleOK) + " " + f_tick(vwapOK) + " " + f_tick(ddOK), cNavy)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}