本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("NIFTY BANKNIFTY VWAP RSI ORB Retest Pro v1.5", shorttitle="ORB Retest Pro v1.5", overlay=true, max_labels_count=500)
// =====================================================
// 1. INPUTS
// =====================================================
g1 = "1. Opening Range"
orbMinutes = input.int(15, "Opening Range Minutes", options=[15, 30, 45, 60], group=g1)
orbBuffer = input.float(5.0, "Breakout Buffer (Points)", minval=0, step=1, group=g1)
showORB = input.bool(true, "Show ORB High / Low", group=g1)
shadeORB = input.bool(true, "Shade Opening Range", group=g1)
g2 = "2. Breakout + Retest"
retestBars = input.int(8, "Maximum Bars to Retest", minval=1, maxval=30, group=g2)
retestToleranceATR = input.float(0.20, "Retest Tolerance (ATR)", minval=0, maxval=2, step=0.05, group=g2)
requireRejection = input.bool(true, "Require Rejection Candle", group=g2)
rejectionClosePct = input.float(65, "Rejection Close Position %", minval=50, maxval=95, group=g2)
useStrength = input.bool(false, "Require Strong Breakout Candle", group=g2)
minBodyATR = input.float(0.35, "Minimum Breakout Body (ATR)", minval=0.05, step=0.05, group=g2)
g3 = "3. VWAP + RSI"
showVWAP = input.bool(true, "Show VWAP", group=g3)
useVWAP = input.bool(true, "Require VWAP Confirmation", group=g3)
useRSI = input.bool(true, "Require RSI Confirmation", group=g3)
rsiLength = input.int(14, "RSI Length", minval=2, group=g3)
ceRSI = input.float(60, "CE Minimum RSI", minval=50, maxval=100, group=g3)
peRSI = input.float(40, "PE Maximum RSI", minval=0, maxval=50, group=g3)
useVWAPSlope = input.bool(false, "Require VWAP Slope", group=g3)
slopeBars = input.int(3, "VWAP Slope Lookback", minval=1, maxval=20, group=g3)
g4 = "4. Signal Control"
allowCE = input.bool(true, "Enable CE BUY", group=g4)
allowPE = input.bool(true, "Enable PE BUY", group=g4)
requireCandle = input.bool(true, "Require Directional Retest Candle", group=g4)
maxTradesDay = input.int(2, "Maximum Entries Per Day", minval=1, maxval=10, group=g4)
cooldownBars = input.int(6, "Cooldown Between Entries", minval=0, maxval=100, group=g4)
lastEntryHour = input.int(15, "Last Entry Hour", minval=9, maxval=15, group=g4)
lastEntryMinute = input.int(0, "Last Entry Minute", minval=0, maxval=59, group=g4)
g5 = "5. Risk Management"
stopMethod = input.string("ATR", "Stop-Loss Method", options=["ATR", "ORB Structure"], group=g5)
atrLength = input.int(14, "ATR Length", minval=1, group=g5)
stopATR = input.float(1.5, "ATR Stop Multiplier", minval=0.1, step=0.1, group=g5)
target1RR = input.float(1.0, "Target 1 Risk/Reward", minval=0.1, group=g5)
target2RR = input.float(2.0, "Target 2 Risk/Reward", minval=0.1, group=g5)
moveBE = input.bool(true, "Move Stop to Breakeven After T1", group=g5)
g6 = "6. Performance"
historyDays = input.int(90, "Performance Lookback (Calendar Days)", options=[30, 60, 90, 180], group=g6)
showDashboard = input.bool(true, "Show Dashboard", group=g6)
showSignals = input.bool(true, "Show CE / PE Signals", group=g6)
showExits = input.bool(true, "Show Exit Markers", group=g6)
showLevels = input.bool(true, "Show Active Trade Levels", group=g6)
g7 = "7. Previous Day Levels"
showPDH = input.bool(true, "Show PDH", group=g7)
showPDL = input.bool(true, "Show PDL", group=g7)
showPDC = input.bool(true, "Show PDC", group=g7)
pdhColor = input.color(color.blue, "PDH Color", group=g7)
pdlColor = input.color(color.red, "PDL Color", group=g7)
pdcColor = input.color(color.purple, "PDC Color", group=g7)
g8 = "8. Line Titles and Labels"
showLineTitles = input.bool(true, "Show Titles on All Lines", group=g8)
labelOffset = input.int(6, "Label Distance (Bars)", minval=1, maxval=50, group=g8)
labelSizeInput = input.string("Tiny", "Label Size", options=["Tiny", "Small", "Normal"], group=g8)
labelSize = labelSizeInput == "Normal" ? size.normal : labelSizeInput == "Small" ? size.small : size.tiny
// =====================================================
// 2. PREVIOUS DAILY CANDLE
// =====================================================
[pdh, pdl, pdc] = request.security(syminfo.tickerid, "D", [high[1], low[1], close[1]], lookahead=barmerge.lookahead_on)
// =====================================================
// 3. NSE SESSION
// =====================================================
if not timeframe.isintraday or timeframe.in_seconds() != 300
runtime.error("Use a 5-minute chart.")
if target2RR <= target1RR
runtime.error("Target 2 must exceed Target 1.")
string tz = "Asia/Kolkata"
inMarket = not na(time(timeframe.period, "0915-1530", tz))
newSession = inMarket and not (inMarket[1] == true)
newDay = timeframe.change("D")
yy = year(time, tz)
mm = month(time, tz)
dd = dayofmonth(time, tz)
orbStart = timestamp(tz, yy, mm, dd, 9, 15)
orbEnd = orbStart + orbMinutes * 60000
entryCutoff = timestamp(tz, yy, mm, dd, lastEntryHour, lastEntryMinute)
exitCutoff = timestamp(tz, yy, mm, dd, 15, 25)
eodBar = inMarket and time_close == exitCutoff
canEnter = inMarket and time_close <= entryCutoff and time_close < exitCutoff
// =====================================================
// 4. OPENING RANGE
// =====================================================
var float orbHigh = na
var float orbLow = na
var bool orbReady = false
if newSession or newDay
orbHigh := na
orbLow := na
orbReady := false
buildingORB = inMarket and time >= orbStart and time < orbEnd
if buildingORB
orbHigh := na(orbHigh) ? high : math.max(orbHigh, high)
orbLow := na(orbLow) ? low : math.min(orbLow, low)
if inMarket and time >= orbEnd and not na(orbHigh) and not na(orbLow)
orbReady := true
// =====================================================
// 5. INDICATORS
// =====================================================
vwapValue = ta.vwap(hlc3)
rsiValue = ta.rsi(close, rsiLength)
atrValue = ta.atr(atrLength)
bullVWAP = not useVWAP or (not na(vwapValue) and close > vwapValue)
bearVWAP = not useVWAP or (not na(vwapValue) and close < vwapValue)
bullRSI = not useRSI or rsiValue >= ceRSI
bearRSI = not useRSI or rsiValue <= peRSI
bullSlope = not useVWAPSlope or (not na(vwapValue[slopeBars]) and vwapValue > vwapValue[slopeBars])
bearSlope = not useVWAPSlope or (not na(vwapValue[slopeBars]) and vwapValue < vwapValue[slopeBars])
bullCandle = not requireCandle or close > open
bearCandle = not requireCandle or close < open
bodySize = math.abs(close - open)
strongBull = not useStrength or (close > open and bodySize >= atrValue * minBodyATR)
strongBear = not useStrength or (close < open and bodySize >= atrValue * minBodyATR)
// =====================================================
// 6. BREAKOUT + RETEST
// =====================================================
ceLevel = orbHigh + orbBuffer
peLevel = orbLow - orbBuffer
crossCE = ta.crossover(close, ceLevel)
crossPE = ta.crossunder(close, peLevel)
breakCE = barstate.isconfirmed and orbReady and inMarket and crossCE and strongBull
breakPE = barstate.isconfirmed and orbReady and inMarket and crossPE and strongBear
var bool pendingCE = false
var bool pendingPE = false
var int ceBreakBar = na
var int peBreakBar = na
var float ceRetestLevel = na
var float peRetestLevel = na
if newSession or newDay
pendingCE := false
pendingPE := false
ceBreakBar := na
peBreakBar := na
ceRetestLevel := na
peRetestLevel := na
if breakCE
pendingCE := true
pendingPE := false
ceBreakBar := bar_index
ceRetestLevel := ceLevel
if breakPE
pendingPE := true
pendingCE := false
peBreakBar := bar_index
peRetestLevel := peLevel
if pendingCE and not na(ceBreakBar) and bar_index - ceBreakBar > retestBars
pendingCE := false
if pendingPE and not na(peBreakBar) and bar_index - peBreakBar > retestBars
pendingPE := false
tolerance = nz(atrValue, 0) * retestToleranceATR
candleRange = math.max(high - low, syminfo.mintick)
closeLocation = (close - low) / candleRange * 100.0
ceReject = not requireRejection or closeLocation >= rejectionClosePct
peReject = not requireRejection or closeLocation <= 100.0 - rejectionClosePct
ceRetest = pendingCE and not na(ceBreakBar) and bar_index > ceBreakBar and low <= ceRetestLevel + tolerance and close > ceRetestLevel and close > open and ceReject
peRetest = pendingPE and not na(peBreakBar) and bar_index > peBreakBar and high >= peRetestLevel - tolerance and close < peRetestLevel and close < open and peReject
if pendingCE and close < orbLow
pendingCE := false
if pendingPE and close > orbHigh
pendingPE := false
if not canEnter
pendingCE := false
pendingPE := false
ceConfirmed = ceRetest and bullVWAP and bullRSI and bullSlope and bullCandle
peConfirmed = peRetest and bearVWAP and bearRSI and bearSlope and bearCandle
// =====================================================
// 7. DAILY CONTROL
// =====================================================
var int signalsToday = 0
var int lastSignalBar = na
if newSession or newDay
signalsToday := 0
lastSignalBar := na
cooldownOK = na(lastSignalBar) or bar_index - lastSignalBar > cooldownBars
// =====================================================
// 8. TRADE STATE
// =====================================================
var bool active = false
var bool t1Hit = false
var int side = 0
var int entryBar = na
var float entryPrice = na
var float stopPrice = na
var float target1 = na
var float target2 = na
var float remaining = 0.0
var float realized = 0.0
var string status = "NO TRADE"
bool ceSignal = false
bool peSignal = false
bool t1Event = false
bool t2Event = false
bool slEvent = false
bool beEvent = false
bool eodEvent = false
var int[] tradeTimes = array.new_int()
var int[] tradeSides = array.new_int()
var float[] tradeResults = array.new_float()
f_record(int t, int s, float result) =>
array.push(tradeTimes, t)
array.push(tradeSides, s)
array.push(tradeResults, result)
// =====================================================
// 9. EXIT MANAGEMENT
// =====================================================
if barstate.isconfirmed and active and bar_index > entryBar
direction = side == 1 ? 1.0 : -1.0
stopHit = side == 1 ? low <= stopPrice : high >= stopPrice
firstHit = side == 1 ? high >= target1 : low <= target1
secondHit = side == 1 ? high >= target2 : low <= target2
if stopHit
realized += remaining * (stopPrice - entryPrice) * direction
remaining := 0.0
active := false
if t1Hit and math.abs(stopPrice - entryPrice) <= syminfo.mintick
status := "BREAKEVEN EXIT"
beEvent := true
else
status := "STOP HIT"
slEvent := true
f_record(time_close, side, realized)
else
if firstHit and not t1Hit
realized += 0.5 * (target1 - entryPrice) * direction
remaining := 0.5
t1Hit := true
t1Event := true
status := "TARGET 1 HIT"
if moveBE
stopPrice := entryPrice
if secondHit and active
realized += remaining * (target2 - entryPrice) * direction
remaining := 0.0
active := false
status := "TARGET 2 HIT"
t2Event := true
f_record(time_close, side, realized)
// =====================================================
// 10. MANDATORY EOD
// =====================================================
if barstate.isconfirmed and active and eodBar
direction = side == 1 ? 1.0 : -1.0
realized += remaining * (close - entryPrice) * direction
remaining := 0.0
active := false
status := "EOD CLOSED"
eodEvent := true
f_record(time_close, side, realized)
if barstate.isconfirmed and active and (newSession or newDay)
active := false
remaining := 0.0
status := "EOD DATA GAP"
eodEvent := true
// =====================================================
// 11. ENTRIES
// =====================================================
ceCandidate = barstate.isconfirmed and allowCE and canEnter and orbReady and not active and signalsToday < maxTradesDay and cooldownOK and ceConfirmed
peCandidate = barstate.isconfirmed and allowPE and canEnter and orbReady and not active and signalsToday < maxTradesDay and cooldownOK and peConfirmed
if ceCandidate or peCandidate
isCE = ceCandidate
proposedEntry = close
proposedStop = stopMethod == "ATR" ? (isCE ? close - atrValue * stopATR : close + atrValue * stopATR) : (isCE ? orbLow : orbHigh)
risk = math.abs(proposedEntry - proposedStop)
validStop = not na(risk) and risk >= syminfo.mintick * 2 and (isCE ? proposedStop < proposedEntry : proposedStop > proposedEntry)
if validStop
entryPrice := proposedEntry
stopPrice := proposedStop
target1 := isCE ? proposedEntry + risk * target1RR : proposedEntry - risk * target1RR
target2 := isCE ? proposedEntry + risk * target2RR : proposedEntry - risk * target2RR
side := isCE ? 1 : -1
entryBar := bar_index
active := true
t1Hit := false
remaining := 1.0
realized := 0.0
signalsToday += 1
lastSignalBar := bar_index
status := "ACTIVE"
ceSignal := isCE
peSignal := not isCE
pendingCE := false
pendingPE := false
// =====================================================
// 12. PERFORMANCE
// =====================================================
cutoffTime = last_bar_time - historyDays * 86400000
int totalTrades = 0
int wins = 0
int losses = 0
int ceTrades = 0
int peTrades = 0
int ceWins = 0
int peWins = 0
float netPoints = 0.0
float grossProfit = 0.0
float grossLoss = 0.0
float cePoints = 0.0
float pePoints = 0.0
if barstate.islast and array.size(tradeTimes) > 0
for i = 0 to array.size(tradeTimes) - 1
t = array.get(tradeTimes, i)
if t >= cutoffTime
result = array.get(tradeResults, i)
tradeSide = array.get(tradeSides, i)
totalTrades += 1
netPoints += result
if result > syminfo.mintick
wins += 1
grossProfit += result
else if result < -syminfo.mintick
losses += 1
grossLoss += math.abs(result)
if tradeSide == 1
ceTrades += 1
cePoints += result
if result > syminfo.mintick
ceWins += 1
else
peTrades += 1
pePoints += result
if result > syminfo.mintick
peWins += 1
winRate = totalTrades > 0 ? wins * 100.0 / totalTrades : na
profitFactor = grossLoss > 0 ? grossProfit / grossLoss : na
avgPoints = totalTrades > 0 ? netPoints / totalTrades : na
ceWinRate = ceTrades > 0 ? ceWins * 100.0 / ceTrades : na
peWinRate = peTrades > 0 ? peWins * 100.0 / peTrades : na
// =====================================================
// 13. CHART LINES
// =====================================================
pH = plot(showORB and inMarket and orbReady ? orbHigh : na, "ORB High", color=color.green, linewidth=2, style=plot.style_linebr)
pL = plot(showORB and inMarket and orbReady ? orbLow : na, "ORB Low", color=color.red, linewidth=2, style=plot.style_linebr)
fill(pH, pL, color=shadeORB ? color.new(color.blue, 95) : na)
plot(showVWAP and inMarket ? vwapValue : na, "VWAP", color=color.orange, linewidth=2)
plot(showLevels and active ? entryPrice : na, "Entry", color=color.blue, linewidth=2, style=plot.style_linebr)
plot(showLevels and active ? stopPrice : na, "Active Stop", color=color.red, linewidth=2, style=plot.style_linebr)
plot(showLevels and active and not t1Hit ? target1 : na, "Target 1", color=color.lime, style=plot.style_linebr)
plot(showLevels and active ? target2 : na, "Target 2", color=color.green, style=plot.style_linebr)
plot(showPDH and inMarket ? pdh : na, "PDH", color=pdhColor, linewidth=2, style=plot.style_linebr)
plot(showPDL and inMarket ? pdl : na, "PDL", color=pdlColor, linewidth=2, style=plot.style_linebr)
plot(showPDC and inMarket ? pdc : na, "PDC", color=pdcColor, linewidth=2, style=plot.style_linebr)
// =====================================================
// 14. LABELS FOR EVERY LINE
// =====================================================
// Labels are updated only on the latest bar.
// Each label includes its title and exact price.
var label[] lineLabels = array.new_label()
f_addLabel(string title, float price, color bg) =>
if not na(price)
newLabel = label.new(
bar_index + labelOffset,
price,
title + " " + str.tostring(price, format.mintick),
style=label.style_label_left,
color=bg,
textcolor=color.white,
size=labelSize)
array.push(lineLabels, newLabel)
if barstate.islast
if array.size(lineLabels) > 0
for i = 0 to array.size(lineLabels) - 1
label.delete(array.get(lineLabels, i))
array.clear(lineLabels)
if showLineTitles
if showORB and orbReady
f_addLabel("ORB HIGH", orbHigh, color.green)
f_addLabel("ORB LOW", orbLow, color.red)
if showPDH
f_addLabel("PDH", pdh, pdhColor)
if showPDL
f_addLabel("PDL", pdl, pdlColor)
if showPDC
f_addLabel("PDC", pdc, pdcColor)
if showVWAP
f_addLabel("VWAP", vwapValue, color.orange)
if showLevels and active
f_addLabel(side == 1 ? "CE ENTRY" : "PE ENTRY", entryPrice, color.blue)
f_addLabel("STOP LOSS", stopPrice, color.red)
if not t1Hit
f_addLabel("TARGET 1", target1, color.lime)
f_addLabel("TARGET 2", target2, color.green)
// =====================================================
// 15. SIGNALS AND EXIT MARKERS
// =====================================================
plotshape(showSignals and ceSignal, title="CE BUY", style=shape.labelup, location=location.belowbar, color=color.green, text="CE BUY", textcolor=color.white, size=size.tiny)
plotshape(showSignals and peSignal, title="PE BUY", style=shape.labeldown, location=location.abovebar, color=color.red, text="PE BUY", textcolor=color.white, size=size.tiny)
plotshape(showExits and t1Event, title="T1", style=shape.circle, location=location.abovebar, color=color.lime, size=size.tiny)
plotshape(showExits and t2Event, title="T2", style=shape.labeldown, location=location.abovebar, color=color.green, text="T2", textcolor=color.white, size=size.tiny)
plotshape(showExits and slEvent, title="SL", style=shape.labeldown, location=location.abovebar, color=color.red, text="SL", textcolor=color.white, size=size.tiny)
plotshape(showExits and beEvent, title="BE", style=shape.labeldown, location=location.abovebar, color=color.orange, text="BE", textcolor=color.white, size=size.tiny)
plotshape(showExits and eodEvent, title="EOD", style=shape.labeldown, location=location.abovebar, color=color.gray, text="EOD", textcolor=color.white, size=size.tiny)
// =====================================================
// 16. ALERTS
// =====================================================
alertcondition(ceSignal, "CE BUY", "ORB Retest Pro v1.5 CE BUY on {{ticker}} at {{close}}")
alertcondition(peSignal, "PE BUY", "ORB Retest Pro v1.5 PE BUY on {{ticker}} at {{close}}")
alertcondition(t1Event, "Target 1", "ORB Retest Pro v1.5 Target 1 hit on {{ticker}}")
alertcondition(t2Event, "Target 2", "ORB Retest Pro v1.5 Target 2 hit on {{ticker}}")
alertcondition(slEvent, "Stop Loss", "ORB Retest Pro v1.5 Stop hit on {{ticker}}")
alertcondition(beEvent, "Breakeven", "ORB Retest Pro v1.5 Breakeven exit on {{ticker}}")
alertcondition(eodEvent, "EOD Exit", "ORB Retest Pro v1.5 EOD exit on {{ticker}}")
// =====================================================
// 17. PERFORMANCE DASHBOARD
// =====================================================
var table dash = table.new(position.top_right, 2, 23, border_width=1)
f_num(float v) =>
na(v) ? "N/A" : str.tostring(v, "#.##")
if barstate.islast
if showDashboard
table.cell(dash, 0, 0, "ORB RETEST v1.5", bgcolor=color.navy, text_color=color.white)
table.cell(dash, 1, 0, syminfo.ticker, bgcolor=color.navy, text_color=color.white)
table.cell(dash, 0, 1, "Entry Method")
table.cell(dash, 1, 1, "BREAKOUT + RETEST")
table.cell(dash, 0, 2, "Lookback")
table.cell(dash, 1, 2, str.tostring(historyDays) + " days")
table.cell(dash, 0, 3, "ORB High")
table.cell(dash, 1, 3, f_num(orbHigh))
table.cell(dash, 0, 4, "ORB Low")
table.cell(dash, 1, 4, f_num(orbLow))
table.cell(dash, 0, 5, "PDH")
table.cell(dash, 1, 5, f_num(pdh))
table.cell(dash, 0, 6, "PDL")
table.cell(dash, 1, 6, f_num(pdl))
table.cell(dash, 0, 7, "PDC")
table.cell(dash, 1, 7, f_num(pdc))
table.cell(dash, 0, 8, "VWAP")
table.cell(dash, 1, 8, f_num(vwapValue))
table.cell(dash, 0, 9, "RSI")
table.cell(dash, 1, 9, f_num(rsiValue))
table.cell(dash, 0, 10, "Completed Trades")
table.cell(dash, 1, 10, str.tostring(totalTrades))
table.cell(dash, 0, 11, "Wins / Losses")
table.cell(dash, 1, 11, str.tostring(wins) + " / " + str.tostring(losses))
table.cell(dash, 0, 12, "Win Rate")
table.cell(dash, 1, 12, na(winRate) ? "N/A" : f_num(winRate) + "%")
table.cell(dash, 0, 13, "Profit Factor")
table.cell(dash, 1, 13, f_num(profitFactor))
table.cell(dash, 0, 14, "Net Index Points")
table.cell(dash, 1, 14, f_num(netPoints), text_color=netPoints >= 0 ? color.green : color.red)
table.cell(dash, 0, 15, "Avg Points / Trade")
table.cell(dash, 1, 15, f_num(avgPoints))
table.cell(dash, 0, 16, "CE Trades / Wins")
table.cell(dash, 1, 16, str.tostring(ceTrades) + " / " + str.tostring(ceWins))
table.cell(dash, 0, 17, "CE Win Rate")
table.cell(dash, 1, 17, na(ceWinRate) ? "N/A" : f_num(ceWinRate) + "%")
table.cell(dash, 0, 18, "CE Net Points")
table.cell(dash, 1, 18, f_num(cePoints))
table.cell(dash, 0, 19, "PE Trades / Wins")
table.cell(dash, 1, 19, str.tostring(peTrades) + " / " + str.tostring(peWins))
table.cell(dash, 0, 20, "PE Win Rate")
table.cell(dash, 1, 20, na(peWinRate) ? "N/A" : f_num(peWinRate) + "%")
table.cell(dash, 0, 21, "PE Net Points")
table.cell(dash, 1, 21, f_num(pePoints))
table.cell(dash, 0, 22, "Trade Status")
table.cell(dash, 1, 22, status)
else
table.clear(dash, 0, 0, 1, 22)