本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("RangeFlip [RF15]", shorttitle="RF15", overlay=true, max_lines_count=50, max_labels_count=50)
//====================================================
// 01. SETTINGS
//====================================================
string GR_LEVELS = "01. Historical Levels"
string GR_STYLE = "02. Level Appearance"
string GR_SIGNAL = "03. RangeFlip Rules"
string GR_DASH = "04. Dashboard"
string GR_COLORS = "05. Colors"
string GR_ORB = "06. ORB Settings"
int lookbackDays = input.int(250, "Days searched for flip levels", minval=2, maxval=1000, group=GR_LEVELS, tooltip="Number of previous regular trading sessions searched when identifying historical range and flip levels. The original level-identification method is retained.")
int extendBars = input.int(5, "Line extension (chart bars)", minval=0, maxval=100, group=GR_LEVELS, tooltip="Number of chart bars for which the four historical level lines extend beyond the latest candle.")
bool showLabels = input.bool(true, "Show level labels", group=GR_LEVELS, tooltip="Display the name and price of each available historical level.")
string levelStyleInput = input.string("Solid", "Level line style", options=["Solid", "Dashed", "Dotted"], group=GR_STYLE, tooltip="Select the appearance of the four historical range and flip level lines.")
int rangeWidth = input.int(1, "Range line width", minval=1, maxval=4, group=GR_STYLE, tooltip="Line thickness for Range High and Range Low.")
int flipWidth = input.int(2, "Flip line width", minval=1, maxval=4, group=GR_STYLE, tooltip="Line thickness for Flip High and Flip Low.")
string selectedSession = input.string("US", "Setup session", options=["US", "Asia", "Europe", "India"], group=GR_SIGNAL)
float minBodyPct = input.float(50.0, "Opening candle minimum body (%)", minval=10, maxval=100, step=5, group=GR_SIGNAL, tooltip="Minimum opening candle body as a percentage of its total high-low range. Default is 50%.")
string breachMode = input.string("Wick", "Range breach detection", options=["Wick", "Body"], group=GR_SIGNAL, tooltip="Wick: a candle high/low touching or crossing a level qualifies as a breach. Body: the candle must open on one side and close beyond the level. Default is Wick.")
int openingWindowMins = input.int(60, "Setup window after session open (minutes)", options=[15, 30, 45, 60], group=GR_SIGNAL, tooltip="Maximum time after the regular-session open in which the setup may qualify. The default is the first 60 minutes.")
bool showEntryLines = input.bool(true, "Show entry, stop and target lines", group=GR_SIGNAL, tooltip="Draw reference lines for the entry trigger, stop reference and target when a two-candle setup qualifies.")
bool showSignalLabels = input.bool(true, "Show signal labels", group=GR_SIGNAL, tooltip="Display a Bullish RangeFlip or Bearish RangeFlip label when the opening breakout and opposite second-candle reversal qualify.")
bool enableBullishAlerts = input.bool(true, "Enable bullish alerts", group=GR_SIGNAL)
bool enableBearishAlerts = input.bool(true, "Enable bearish alerts", group=GR_SIGNAL)
bool enableDynamicAlerts = input.bool(true, "Enable dynamic alert() messages", group=GR_SIGNAL)
// DASHBOARD SETTINGS
//====================================================
bool showDashboard = input.bool(true, "Display dashboard?", group=GR_DASH, tooltip="Enable or hide the complete RangeFlip dashboard.")
bool showTableHeader = input.bool(true, "Show table header?", group=GR_DASH, tooltip="Enable or hide the RANGEFLIP / RF15 header row without hiding dashboard values.")
string dashboardPosition = input.string("Top Right", "Panel Position", options=["Top Right", "Bottom Right", "Top Left", "Bottom Left", "Middle Right"], group=GR_DASH, tooltip="Choose where the dashboard appears on the chart. Middle Right places it vertically in the center along the right edge.")
string dashboardTextSize = input.string("Small", "Label Text Size", options=["Tiny", "Small", "Normal", "Large"], group=GR_DASH, tooltip="Set the text size used throughout the dashboard.")
color dashboardBg = input.color(color.new(#32373F, 15), "Background Color", group=GR_DASH, tooltip="Set the dashboard background color and transparency. Higher transparency allows more chart detail to show through.")
color dashboardText = input.color(#C5BDBD, "Default Text Color", group=GR_DASH, tooltip="Set the default text color for dashboard headings and values. Bullish and bearish bias cells retain their own status colors.")
bool showSessionRow = input.bool(true, "Show session row", group=GR_DASH)
bool showSignalHistory = input.bool(true, "Show recent signal history", group=GR_DASH)
int historyDays = input.int(15, "Signal history lookback (calendar days)", minval=1, maxval=365, group=GR_DASH)
bool showBias = input.bool(true, "Show trade bias", group=GR_DASH, tooltip="Show Bullish, Bearish or No Trade.")
bool showSetupStatus = input.bool(true, "Show setup status", group=GR_DASH, tooltip="Show whether the opening breakout and opposite second-candle reversal qualify.")
bool showTestedLevel = input.bool(true, "Show tested level", group=GR_DASH, tooltip="Show the name and price of the historical level broken by the opening candle.")
bool showEntry = input.bool(true, "Show entry price", group=GR_DASH, tooltip="Show the second candle's high for a bullish setup or low for a bearish setup when candle two closes and confirms. No third-candle confirmation is required; this is a trigger price, not a confirmed fill.")
bool showStop = input.bool(true, "Show stop reference", group=GR_DASH, tooltip="Show the tested level used as the stop reference. A protective buffer beyond the level is not currently applied.")
bool showTarget = input.bool(true, "Show target", group=GR_DASH, tooltip="Show the qualifying opposite historical level if it lies beyond the entry trigger.")
bool showRiskReward = input.bool(true, "Show reward/risk", group=GR_DASH, tooltip="Show the potential reward-to-risk ratio calculated from the entry trigger, stop reference and target. This is a theoretical ratio, not a backtested result.")
bool showTimeframe = input.bool(true, "Show timeframe status", group=GR_DASH, tooltip="Indicate whether the chart is using the required 15-minute timeframe.")
//====================================================
// ORB SETTINGS
// Uses the same selectedSession setting as RangeFlip.
//====================================================
string ORB_SOLID = "Solid"
string ORB_DASHED = "Dashed"
string ORB_DOTTED = "Dotted"
string ORB_T_TINY = "Tiny"
string ORB_T_SMALL = "Small"
string ORB_T_NORMAL = "Normal"
string ORB_T_LARGE = "Large"
string ORB_T_HUGE = "Huge"
bool showOrbInput = input.bool(true, "Show ORB Lines", group=GR_ORB, tooltip="Enable or disable Opening Range Breakout lines.")
color orbHighColorInput = input.color(color.rgb(66, 189, 168, 35), "ORB High Color", group=GR_ORB)
color orbLowColorInput = input.color(color.rgb(255, 238, 88, 35), "ORB Low Color", group=GR_ORB)
int orbMinutesInput = input.int(15, "ORB Duration (Minutes)", minval=1, group=GR_ORB, tooltip="Opening range duration from the selected session's regular open.")
string orbStyleInput = input.string(ORB_SOLID, "ORB Line Style", options=[ORB_SOLID, ORB_DASHED, ORB_DOTTED], group=GR_ORB)
int orbWidthInput = input.int(1, "ORB Line Width", minval=1, maxval=10, group=GR_ORB)
bool orbCurrentDayOnly = input.bool(false, "Show Only for Current Day", group=GR_ORB)
bool orbExtendAH = input.bool(false, "Extend ORB Lines After Hours", group=GR_ORB, tooltip="If disabled, ORB lines stop at the selected session end.")
string labelSizeInput = input.string(ORB_T_TINY, "Label Size", options=[ORB_T_TINY, ORB_T_SMALL, ORB_T_NORMAL, ORB_T_LARGE, ORB_T_HUGE], group=GR_ORB)
color orbVolTextColor = input.color(color.rgb(13, 13, 14), "ORB Text Color", group=GR_ORB)
bool showOrbMidInput = input.bool(true, "Show ORB Mid Line", group=GR_ORB)
color orbMidColorInput = input.color(color.rgb(202, 209, 235, 35), "ORB Mid Color", group=GR_ORB)
string orbMidStyleInput = input.string(ORB_SOLID, "ORB Mid Line Style", options=[ORB_SOLID, ORB_DASHED, ORB_DOTTED], group=GR_ORB)
int orbMidWidthInput = input.int(1, "ORB Mid Line Width", minval=1, maxval=10, group=GR_ORB)
bool showUpperTInput = input.bool(true, "Show Upper Targets (T1-T4)", group=GR_ORB)
bool showLowerTInput = input.bool(true, "Show Lower Targets (T1-T4)", group=GR_ORB)
string targetStyleInput = input.string(ORB_DASHED, "Target Line Style", options=[ORB_SOLID, ORB_DASHED, ORB_DOTTED], group=GR_ORB)
int targetWidthInput = input.int(1, "Target Line Width", minval=1, maxval=10, group=GR_ORB)
string orbTargetMethod = input.string("Linear", "Target Method", options=["Linear", "Fibonacci"], group=GR_ORB, tooltip="Linear uses equal spacing. Fibonacci uses custom ratios relative to ORB half-range.")
float fib1 = input.float(1.618, "T1 Ratio", group=GR_ORB, inline="fib12")
float fib2 = input.float(2.618, "T2 Ratio", group=GR_ORB, inline="fib12")
float fib3 = input.float(3.618, "T3 Ratio", group=GR_ORB, inline="fib34")
float fib4 = input.float(4.236, "T4 Ratio", group=GR_ORB, inline="fib34")
//====================================================
// COLORS
//====================================================
color sellCol = input.color(#F0443A, "Sell side / resistance", group=GR_COLORS, tooltip="Color used for Range High and Flip High.")
color buyCol = input.color(#3DDC6B, "Buy side / support", group=GR_COLORS, tooltip="Color used for Range Low and Flip Low.")
color bullishCol = input.color(#26A69A, "Bullish signal", group=GR_COLORS, tooltip="Color used for bullish bias, labels and target references.")
color bearishCol = input.color(#EF5350, "Bearish signal", group=GR_COLORS, tooltip="Color used for bearish bias, labels and stop references.")
//====================================================
// HELPERS
//====================================================
lineStyle = levelStyleInput == "Dotted" ? line.style_dotted : levelStyleInput == "Dashed" ? line.style_dashed : line.style_solid
f_orbLineStyle(string style) =>
style == ORB_DASHED ? line.style_dashed : style == ORB_DOTTED ? line.style_dotted : line.style_solid
f_orbLabelSize(string sz) =>
sz == ORB_T_SMALL ? size.small : sz == ORB_T_NORMAL ? size.normal : sz == ORB_T_LARGE ? size.large : sz == ORB_T_HUGE ? size.huge : size.tiny
f_position(string p) =>
p == "Top Left" ? position.top_left :
p == "Bottom Right" ? position.bottom_right :
p == "Bottom Left" ? position.bottom_left :
p == "Middle Right" ? position.middle_right :
position.top_right
f_textSize(string s) =>
s == "Tiny" ? size.tiny :
s == "Normal" ? size.normal :
s == "Large" ? size.large :
size.small
f_price(float p) =>
na(p) ? "—" : str.tostring(p, format.mintick)
f_bodyPct(float o, float h, float l, float c) =>
h == l ? 0.0 : math.abs(c - o) / (h - l) * 100.0
f_drawLevel(line oldLine, label oldLabel, float price, int t0, int tEnd, color col, int width, string name) =>
line.delete(oldLine)
label.delete(oldLabel)
line newLine = na
label newLabel = na
if not na(price) and not na(t0)
newLine := line.new(t0, price, tEnd, price, xloc=xloc.bar_time, color=col, width=width, style=lineStyle)
if showLabels
newLabel := label.new(tEnd, price, name + " " + str.tostring(price, format.mintick), xloc=xloc.bar_time, style=label.style_label_left, color=color.new(col, 100), textcolor=col, size=size.small)
[newLine, newLabel]
//====================================================
// SELECTED SESSION TIMEZONE AND DAILY RESET
//====================================================
string marketTZ = selectedSession == "US" ? "America/New_York" :
selectedSession == "Asia" ? "Asia/Tokyo" :
selectedSession == "Europe" ? "Europe/London" :
"Asia/Kolkata"
int setupHour = 9
int setupMinute = selectedSession == "US" ? 45 : 15
int secondHour = selectedSession == "US" ? 10 : selectedSession == "India" ? 9 : 9
int secondMinute = selectedSession == "US" ? 0 : selectedSession == "India" ? 30 : 30
bool is15m = timeframe.isminutes and timeframe.multiplier == 15
bool isFirstSetupBar = is15m and hour(time, marketTZ) == setupHour and minute(time, marketTZ) == setupMinute
bool isSecondSetupBar = is15m and hour(time, marketTZ) == secondHour and minute(time, marketTZ) == secondMinute
int selectedDayTime = time("D", "0000-2359", marketTZ)
bool newSelectedDay = not na(selectedDayTime[1]) and selectedDayTime != selectedDayTime[1]
//====================================================
// ORIGINAL HISTORICAL RANGE LEVEL CALCULATION
//====================================================
var array<float> dayHi = array.new<float>()
var array<float> dayLo = array.new<float>()
var array<int> dayHiT = array.new<int>()
var array<int> dayLoT = array.new<int>()
var float sessHi = na
var float sessLo = na
var int sessHiT = na
var int sessLoT = na
var float rangeHigh = na
var float rangeLow = na
var int rangeHighT = na
var int rangeLowT = na
var float flipHigh = na
var float flipLow = na
var int flipHighT = na
var int flipLowT = na
if session.isfirstbar_regular
if not na(sessHi)
dayHi.unshift(sessHi)
dayLo.unshift(sessLo)
dayHiT.unshift(sessHiT)
dayLoT.unshift(sessLoT)
if dayHi.size() > lookbackDays + 1
dayHi.pop()
dayLo.pop()
dayHiT.pop()
dayLoT.pop()
sessHi := high
sessLo := low
sessHiT := time
sessLoT := time
if dayHi.size() > 0
rangeHigh := dayHi.get(0)
rangeLow := dayLo.get(0)
rangeHighT := dayHiT.get(0)
rangeLowT := dayLoT.get(0)
flipHigh := na
flipLow := na
flipHighT := na
flipLowT := na
if dayHi.size() > 1
for i = 1 to dayHi.size() - 1
if na(flipHigh) and dayHi.get(i) > rangeHigh
flipHigh := dayHi.get(i)
flipHighT := dayHiT.get(i)
if na(flipLow) and dayLo.get(i) < rangeLow
flipLow := dayLo.get(i)
flipLowT := dayLoT.get(i)
if not na(flipHigh) and not na(flipLow)
break
else if session.ismarket and not na(sessHi)
if high > sessHi
sessHi := high
sessHiT := time
if low < sessLo
sessLo := low
sessLoT := time
//====================================================
// DRAW HISTORICAL LEVELS
//====================================================
var line lnFH = na
var line lnRH = na
var line lnRL = na
var line lnFL = na
var label lbFH = na
var label lbRH = na
var label lbRL = na
var label lbFL = na
if barstate.islast
float dRH = rangeHigh
float dRL = rangeLow
float dFH = flipHigh
float dFL = flipLow
int dRHT = rangeHighT
int dRLT = rangeLowT
int dFHT = flipHighT
int dFLT = flipLowT
bool sessionOver = not session.ismarket or (session.islastbar_regular and barstate.isconfirmed)
if sessionOver and not na(sessHi)
dRH := sessHi
dRHT := sessHiT
dRL := sessLo
dRLT := sessLoT
dFH := na
dFHT := na
dFL := na
dFLT := na
int n = math.min(dayHi.size(), lookbackDays)
if n > 0
for i = 0 to n - 1
if na(dFH) and dayHi.get(i) > dRH
dFH := dayHi.get(i)
dFHT := dayHiT.get(i)
if na(dFL) and dayLo.get(i) < dRL
dFL := dayLo.get(i)
dFLT := dayLoT.get(i)
if not na(dFH) and not na(dFL)
break
int tEnd = time + extendBars * timeframe.in_seconds() * 1000
[l1, b1] = f_drawLevel(lnFH, lbFH, dFH, dFHT, tEnd, sellCol, flipWidth, "Flip high")
[l2, b2] = f_drawLevel(lnRH, lbRH, dRH, dRHT, tEnd, sellCol, rangeWidth, "Range high")
[l3, b3] = f_drawLevel(lnRL, lbRL, dRL, dRLT, tEnd, buyCol, rangeWidth, "Range low")
[l4, b4] = f_drawLevel(lnFL, lbFL, dFL, dFLT, tEnd, buyCol, flipWidth, "Flip low")
lnFH := l1
lbFH := b1
lnRH := l2
lbRH := b2
lnRL := l3
lbRL := b3
lnFL := l4
lbFL := b4
//====================================================
// SIGNAL HISTORY STORAGE
// 1 = bullish, -1 = bearish
//====================================================
var array<int> signalTimes = array.new<int>()
var array<int> signalDirections = array.new<int>()
//====================================================
// ENTRY / STOP / TARGET DRAWING OBJECTS
//====================================================
var line entryLine = na
var line stopLine = na
var line targetLine = na
var label signalLabel = na
//====================================================
// RANGEFLIP SETUP STATE
//====================================================
var int sessionStartTime = na
var float firstOpen = na
var float firstHigh = na
var float firstLow = na
var float firstClose = na
var bool firstStrong = false
var bool firstBullish = false
var bool firstBearish = false
var float testedPrice = na
var string testedName = "—"
var bool testedSupport = false
var bool testedResistance = false
var bool setupInvalid = false
var bool setupEvaluated = false
var string tradeBias = "No Trade"
var string setupStatus = "Waiting for session"
var float entryPrice = na
var float stopPrice = na
var float targetPrice = na
bool bullishSignal = false
bool bearishSignal = false
// Reset current-day setup/dashboard values in selected timezone.
if newSelectedDay
sessionStartTime := na
firstOpen := na
firstHigh := na
firstLow := na
firstClose := na
firstStrong := false
firstBullish := false
firstBearish := false
testedPrice := na
testedName := "—"
testedSupport := false
testedResistance := false
setupInvalid := false
setupEvaluated := false
tradeBias := "No Trade"
setupStatus := "Waiting for session"
entryPrice := na
stopPrice := na
targetPrice := na
line.delete(entryLine)
line.delete(stopLine)
line.delete(targetLine)
label.delete(signalLabel)
entryLine := na
stopLine := na
targetLine := na
signalLabel := na
//====================================================
// FIRST SETUP CANDLE
//====================================================
if isFirstSetupBar
sessionStartTime := time
firstOpen := open
firstHigh := high
firstLow := low
firstClose := close
firstStrong := f_bodyPct(open, high, low, close) >= minBodyPct
firstBullish := close > open
firstBearish := close < open
testedPrice := na
testedName := "—"
testedSupport := false
testedResistance := false
setupInvalid := false
setupEvaluated := false
tradeBias := "No Trade"
setupStatus := "Checking opening candle"
entryPrice := na
stopPrice := na
targetPrice := na
if not firstStrong
setupStatus := "Opening candle not strong"
else if not firstBullish and not firstBearish
setupStatus := "Opening candle is a doji"
else
if firstBullish
bool flipHighBreached = not na(flipHigh) and open <= flipHigh and (breachMode == "Wick" ? high >= flipHigh : firstClose > flipHigh)
bool rangeHighBreached = not na(rangeHigh) and open <= rangeHigh and (breachMode == "Wick" ? high >= rangeHigh : firstClose > rangeHigh)
if flipHighBreached
testedPrice := flipHigh
testedName := "Flip High"
testedResistance := true
else if rangeHighBreached
testedPrice := rangeHigh
testedName := "Range High"
testedResistance := true
if firstBearish
bool flipLowBreached = not na(flipLow) and open >= flipLow and (breachMode == "Wick" ? low <= flipLow : firstClose < flipLow)
bool rangeLowBreached = not na(rangeLow) and open >= rangeLow and (breachMode == "Wick" ? low <= rangeLow : firstClose < rangeLow)
if flipLowBreached
testedPrice := flipLow
testedName := "Flip Low"
testedSupport := true
else if rangeLowBreached
testedPrice := rangeLow
testedName := "Range Low"
testedSupport := true
if na(testedPrice)
setupStatus := "No Trade: no level touched/broken"
else
setupStatus := "Level broken; waiting for candle 2"
//====================================================
// SECOND SETUP CANDLE: CONFIRM OR REJECT REVERSAL
//====================================================
if isSecondSetupBar and not setupEvaluated and not na(sessionStartTime)
setupEvaluated := true
int elapsedMinutes = int((time - sessionStartTime) / 60000)
bool insideWindow = elapsedMinutes <= openingWindowMins
if not insideWindow
setupStatus := "No Trade: outside opening window"
else if na(testedPrice)
setupStatus := "No Trade: no level touched/broken"
else
bool secondBearish = close < open
bool secondBullish = close > open
bool bearishReversal = testedResistance and firstBullish and secondBearish
bool bullishReversal = testedSupport and firstBearish and secondBullish
if bearishReversal
tradeBias := "Bearish"
setupStatus := "Confirmed: bearish RangeFlip"
entryPrice := low
stopPrice := testedPrice
targetPrice := not na(rangeLow) and rangeLow < entryPrice ? rangeLow : not na(flipLow) and flipLow < entryPrice ? flipLow : na
bearishSignal := true
else if bullishReversal
tradeBias := "Bullish"
setupStatus := "Confirmed: bullish RangeFlip"
entryPrice := high
stopPrice := testedPrice
targetPrice := not na(rangeHigh) and rangeHigh > entryPrice ? rangeHigh : not na(flipHigh) and flipHigh > entryPrice ? flipHigh : na
bullishSignal := true
else
tradeBias := "No Trade"
setupStatus := "No Trade: opposite candle not confirmed"
//====================================================
// RECORD CONFIRMED SIGNALS
//====================================================
if barstate.isconfirmed and bullishSignal
array.push(signalTimes, time)
array.push(signalDirections, 1)
if barstate.isconfirmed and bearishSignal
array.push(signalTimes, time)
array.push(signalDirections, -1)
//====================================================
// COMPLETED-DAY SIGNAL HISTORY
// Excludes the current calendar day in selected timezone.
//====================================================
// Anchor the window to the active chart/replay bar, not wall-clock time.
// This makes Replay count relative to the day currently being replayed.
int currentDayStart = timestamp(
marketTZ,
year(time, marketTZ),
month(time, marketTZ),
dayofmonth(time, marketTZ),
0, 0)
int historyCutoff = timestamp(
marketTZ,
year(time, marketTZ),
month(time, marketTZ),
dayofmonth(time, marketTZ) - historyDays,
0, 0)
// Prune signals older than the configured calendar-day window.
while array.size(signalTimes) > 0 and array.get(signalTimes, 0) < historyCutoff
array.shift(signalTimes)
array.shift(signalDirections)
int bullishCount = 0
int bearishCount = 0
if array.size(signalTimes) > 0
for i = 0 to array.size(signalTimes) - 1
int signalTime = array.get(signalTimes, i)
// Count only previous completed calendar days.
if signalTime >= historyCutoff and signalTime < currentDayStart
if array.get(signalDirections, i) == 1
bullishCount += 1
else if array.get(signalDirections, i) == -1
bearishCount += 1
string signalHistoryText = "Bear (" + str.tostring(bearishCount) + "), Bull (" + str.tostring(bullishCount) + ")"
//====================================================
// ENTRY / STOP / TARGET REFERENCE LINES
//====================================================
if (bullishSignal or bearishSignal) and barstate.isconfirmed
line.delete(entryLine)
line.delete(stopLine)
line.delete(targetLine)
label.delete(signalLabel)
if showEntryLines
entryLine := line.new(bar_index, entryPrice, bar_index + 10, entryPrice, color=color.yellow, width=2, style=line.style_dashed)
stopLine := line.new(bar_index, stopPrice, bar_index + 10, stopPrice, color=bearishCol, width=2, style=line.style_dotted)
if not na(targetPrice)
targetLine := line.new(bar_index, targetPrice, bar_index + 10, targetPrice, color=bullishCol, width=2, style=line.style_dotted)
if showSignalLabels
signalLabel := label.new(bar_index, bullishSignal ? low : high, tradeBias + " RangeFlip\nEntry trigger: " + f_price(entryPrice), style=bullishSignal ? label.style_label_up : label.style_label_down, color=bullishSignal ? bullishCol : bearishCol, textcolor=color.white)
//====================================================
// ALERTS
//====================================================
alertcondition(enableBullishAlerts and bullishSignal and barstate.isconfirmed, "RangeFlip Bullish", "Bullish RangeFlip confirmed on {{ticker}}.")
alertcondition(enableBearishAlerts and bearishSignal and barstate.isconfirmed, "RangeFlip Bearish", "Bearish RangeFlip confirmed on {{ticker}}.")
if enableDynamicAlerts and enableBullishAlerts and bullishSignal and barstate.isconfirmed
alert("RangeFlip BULLISH | Session: " + selectedSession + " | " + syminfo.ticker + " | Entry trigger: " + f_price(entryPrice), alert.freq_once_per_bar_close)
if enableDynamicAlerts and enableBearishAlerts and bearishSignal and barstate.isconfirmed
alert("RangeFlip BEARISH | Session: " + selectedSession + " | " + syminfo.ticker + " | Entry trigger: " + f_price(entryPrice), alert.freq_once_per_bar_close)
//====================================================
//====================================================
// ORB CALCULATION AND DRAWING
// Shares RangeFlip's selectedSession and market timezone.
// Target lines are shown only in the direction of confirmed RangeFlip bias.
//====================================================
string orbSessionTime = selectedSession == "US" ? "0930-1600" : selectedSession == "Asia" ? "0900-1500" : selectedSession == "Europe" ? "0800-1630" : "0915-1530"
int orbEndHour = selectedSession == "US" ? 16 : selectedSession == "Europe" ? 16 : selectedSession == "Asia" ? 15 : 15
int orbEndMinute = selectedSession == "US" ? 0 : selectedSession == "Europe" ? 30 : selectedSession == "Asia" ? 0 : 30
bool isOrbSession = not na(time(timeframe.period, orbSessionTime, marketTZ))
bool isNewOrbSession = isOrbSession and not isOrbSession[1]
var int orbSessionStartTimestamp = na
var float orbHigh = na
var float orbLow = na
var bool orbRangeReady = false
if isNewOrbSession
orbSessionStartTimestamp := time
orbHigh := high
orbLow := low
orbRangeReady := false
else if isOrbSession and not na(orbSessionStartTimestamp) and (time - orbSessionStartTimestamp) < orbMinutesInput * 60 * 1000
orbHigh := na(orbHigh) ? high : math.max(orbHigh, high)
orbLow := na(orbLow) ? low : math.min(orbLow, low)
if not na(orbSessionStartTimestamp) and not na(orbHigh) and not na(orbLow) and (not isOrbSession or (time - orbSessionStartTimestamp) >= orbMinutesInput * 60 * 1000)
orbRangeReady := true
int orbSessionEndTimestamp = not na(orbSessionStartTimestamp) ? timestamp(marketTZ, year(orbSessionStartTimestamp, marketTZ), month(orbSessionStartTimestamp, marketTZ), dayofmonth(orbSessionStartTimestamp, marketTZ), orbEndHour, orbEndMinute, 0) : na
int orbLineEndX = orbExtendAH and not na(orbSessionStartTimestamp) ? orbSessionStartTimestamp + 60000 : orbSessionEndTimestamp
bool orbIsLatestDay = not na(orbSessionStartTimestamp) and year(orbSessionStartTimestamp, marketTZ) == year(last_bar_time, marketTZ) and month(orbSessionStartTimestamp, marketTZ) == month(last_bar_time, marketTZ) and dayofmonth(orbSessionStartTimestamp, marketTZ) == dayofmonth(last_bar_time, marketTZ)
bool showOrbBase = showOrbInput and timeframe.isintraday and orbRangeReady and not na(orbSessionStartTimestamp) and (not orbCurrentDayOnly or orbIsLatestDay)
bool showOrbExtras = showOrbBase and orbIsLatestDay
float orbMid = not na(orbHigh) and not na(orbLow) ? (orbHigh + orbLow) / 2.0 : na
float orbTargetStep = not na(orbMid) and not na(orbHigh) ? orbHigh - orbMid : na
orbLineExt = orbExtendAH ? extend.right : extend.none
var line orbHLine = na
var line orbLLine = na
var line orbMLine = na
var label orbHLabel = na
var label orbLLabel = na
var label orbMLabel = na
var array<line> upperTLines = array.new<line>(4)
var array<label> upperTLabels = array.new<label>(4)
var array<line> lowerTLines = array.new<line>(4)
var array<label> lowerTLabels = array.new<label>(4)
if barstate.isfirst
orbHLine := line.new(na, na, na, na, xloc=xloc.bar_time)
orbLLine := line.new(na, na, na, na, xloc=xloc.bar_time)
orbMLine := line.new(na, na, na, na, xloc=xloc.bar_time)
orbHLabel := label.new(na, na, "", xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_right)
orbLLabel := label.new(na, na, "", xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_right)
orbMLabel := label.new(na, na, "", xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_right)
for i = 0 to 3
array.set(upperTLines, i, line.new(na, na, na, na, xloc=xloc.bar_time))
array.set(upperTLabels, i, label.new(na, na, "", xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_right))
array.set(lowerTLines, i, line.new(na, na, na, na, xloc=xloc.bar_time))
array.set(lowerTLabels, i, label.new(na, na, "", xloc=xloc.bar_time, yloc=yloc.price, style=label.style_label_right))
if showOrbBase and not na(orbLineEndX)
line.set_xy1(orbHLine, orbSessionStartTimestamp, orbHigh)
line.set_xy2(orbHLine, orbLineEndX, orbHigh)
line.set_extend(orbHLine, orbLineExt)
line.set_color(orbHLine, orbHighColorInput)
line.set_style(orbHLine, f_orbLineStyle(orbStyleInput))
line.set_width(orbHLine, orbWidthInput)
line.set_xy1(orbLLine, orbSessionStartTimestamp, orbLow)
line.set_xy2(orbLLine, orbLineEndX, orbLow)
line.set_extend(orbLLine, orbLineExt)
line.set_color(orbLLine, orbLowColorInput)
line.set_style(orbLLine, f_orbLineStyle(orbStyleInput))
line.set_width(orbLLine, orbWidthInput)
label.set_xy(orbHLabel, orbSessionStartTimestamp, orbHigh)
label.set_text(orbHLabel, "ORBH-" + str.tostring(orbHigh, format.mintick))
label.set_textcolor(orbHLabel, orbVolTextColor)
label.set_color(orbHLabel, orbHighColorInput)
label.set_size(orbHLabel, f_orbLabelSize(labelSizeInput))
label.set_xy(orbLLabel, orbSessionStartTimestamp, orbLow)
label.set_text(orbLLabel, "ORBL-" + str.tostring(orbLow, format.mintick))
label.set_textcolor(orbLLabel, orbVolTextColor)
label.set_color(orbLLabel, orbLowColorInput)
label.set_size(orbLLabel, f_orbLabelSize(labelSizeInput))
else
line.set_xy1(orbHLine, na, na), line.set_xy2(orbHLine, na, na)
line.set_xy1(orbLLine, na, na), line.set_xy2(orbLLine, na, na)
label.set_xy(orbHLabel, na, na), label.set_xy(orbLLabel, na, na)
if showOrbExtras and showOrbMidInput and not na(orbMid) and not na(orbLineEndX)
line.set_xy1(orbMLine, orbSessionStartTimestamp, orbMid)
line.set_xy2(orbMLine, orbLineEndX, orbMid)
line.set_extend(orbMLine, orbLineExt)
line.set_color(orbMLine, orbMidColorInput)
line.set_style(orbMLine, f_orbLineStyle(orbMidStyleInput))
line.set_width(orbMLine, orbMidWidthInput)
label.set_xy(orbMLabel, orbSessionStartTimestamp, orbMid)
label.set_text(orbMLabel, "ORBM-" + str.tostring(orbMid, format.mintick))
label.set_textcolor(orbMLabel, orbVolTextColor)
label.set_color(orbMLabel, orbMidColorInput)
label.set_size(orbMLabel, f_orbLabelSize(labelSizeInput))
else
line.set_xy1(orbMLine, na, na), line.set_xy2(orbMLine, na, na)
label.set_xy(orbMLabel, na, na)
for i = 0 to 3
float ratio = orbTargetMethod == "Linear" ? i + 2.0 : i == 0 ? fib1 : i == 1 ? fib2 : i == 2 ? fib3 : fib4
float upperPrice = not na(orbMid) and not na(orbTargetStep) ? orbMid + ratio * orbTargetStep : na
float lowerPrice = not na(orbMid) and not na(orbTargetStep) ? orbMid - ratio * orbTargetStep : na
line upperLine = array.get(upperTLines, i)
label upperLabel = array.get(upperTLabels, i)
line lowerLine = array.get(lowerTLines, i)
label lowerLabel = array.get(lowerTLabels, i)
bool showUpperNow = showOrbExtras and showUpperTInput and tradeBias == "Bullish" and not na(upperPrice) and not na(rangeLow) and upperPrice > rangeLow and not na(orbLineEndX)
bool showLowerNow = showOrbExtras and showLowerTInput and tradeBias == "Bearish" and not na(lowerPrice) and not na(flipLow) and lowerPrice < flipLow and not na(orbLineEndX)
if showUpperNow
line.set_xy1(upperLine, orbSessionStartTimestamp, upperPrice)
line.set_xy2(upperLine, orbLineEndX, upperPrice)
line.set_extend(upperLine, orbLineExt)
line.set_color(upperLine, orbHighColorInput)
line.set_style(upperLine, f_orbLineStyle(targetStyleInput))
line.set_width(upperLine, targetWidthInput)
label.set_xy(upperLabel, orbSessionStartTimestamp, upperPrice)
label.set_text(upperLabel, "T" + str.tostring(i + 1) + "-" + str.tostring(upperPrice, format.mintick))
label.set_textcolor(upperLabel, orbVolTextColor)
label.set_color(upperLabel, orbHighColorInput)
label.set_size(upperLabel, f_orbLabelSize(labelSizeInput))
else
line.set_xy1(upperLine, na, na), line.set_xy2(upperLine, na, na)
label.set_xy(upperLabel, na, na)
if showLowerNow
line.set_xy1(lowerLine, orbSessionStartTimestamp, lowerPrice)
line.set_xy2(lowerLine, orbLineEndX, lowerPrice)
line.set_extend(lowerLine, orbLineExt)
line.set_color(lowerLine, orbLowColorInput)
line.set_style(lowerLine, f_orbLineStyle(targetStyleInput))
line.set_width(lowerLine, targetWidthInput)
label.set_xy(lowerLabel, orbSessionStartTimestamp, lowerPrice)
label.set_text(lowerLabel, "T" + str.tostring(i + 1) + "-" + str.tostring(lowerPrice, format.mintick))
label.set_textcolor(lowerLabel, orbVolTextColor)
label.set_color(lowerLabel, orbLowColorInput)
label.set_size(lowerLabel, f_orbLabelSize(labelSizeInput))
else
line.set_xy1(lowerLine, na, na), line.set_xy2(lowerLine, na, na)
label.set_xy(lowerLabel, na, na)
//====================================================
// DASHBOARD
//====================================================
var table dashboard = table.new(f_position(dashboardPosition), 2, 11, bgcolor=dashboardBg, border_width=1, border_color=color.new(color.gray, 50), frame_width=1, frame_color=color.new(color.gray, 50))
dashboardSize = f_textSize(dashboardTextSize)
color headerBg = color.new(#202630, 5)
color rowBg = dashboardBg
if barstate.islast
table.clear(dashboard, 0, 0, 1, 10)
if showDashboard
int row = 0
if showTableHeader
table.cell(dashboard, 0, row, "RANGEFLIP", bgcolor=headerBg, text_color=color.white, text_size=dashboardSize)
table.cell(dashboard, 1, row, "RF15", bgcolor=headerBg, text_color=color.white, text_size=dashboardSize)
row += 1
if showSessionRow
table.cell(dashboard, 0, row, "Session", text_color=dashboardText, bgcolor=rowBg, text_size=dashboardSize)
table.cell(dashboard, 1, row, selectedSession, text_color=dashboardText, bgcolor=rowBg, text_size=dashboardSize)
row += 1
if showSignalHistory
table.cell(dashboard, 0, row, "Previous " + str.tostring(historyDays) + " days", text_color=dashboardText, bgcolor=rowBg, text_size=dashboardSize)
table.cell(dashboard, 1, row, signalHistoryText, text_color=dashboardText, bgcolor=rowBg, text_size=dashboardSize)
row += 1
if showBias
color biasColor = tradeBias == "Bullish" ? bullishCol : tradeBias == "Bearish" ? bearishCol : color.new(color.gray, 25)
table.cell(dashboard, 0, row, "Bias", text_color=dashboardText, bgcolor=rowBg, text_size=dashboardSize)
table.cell(dashboard, 1, row, tradeBias, text_color=color.white, bgcolor=biasColor, text_size=dashboardSize)
row += 1
if showSetupStatus
table.cell(dashboard, 0, row, "Setup", text_color=dashboardText, bgcolor=rowBg, text_size=dashboardSize)
table.cell(dashboard, 1, row, setupStatus, text_color=dashboardText, bgcolor=rowBg, text_size=dashboardSize)
row += 1
if showTestedLevel
table.cell(dashboard, 0, row, "Tested level", text_color=dashboardText, bgcolor=rowBg, text_size=dashboardSize)
table.cell(dashboard, 1, row, testedName + " " + f_price(testedPrice), text_color=dashboardText, bgcolor=rowBg, text_size=dashboardSize)
row += 1
if showEntry
table.cell(dashboard, 0, row, "Entry trigger", text_color=dashboardText, bgcolor=rowBg, text_size=dashboardSize)
table.cell(dashboard, 1, row, f_price(entryPrice), text_color=color.yellow, bgcolor=rowBg, text_size=dashboardSize)
row += 1
if showStop
table.cell(dashboard, 0, row, "Stop reference", text_color=dashboardText, bgcolor=rowBg, text_size=dashboardSize)
table.cell(dashboard, 1, row, f_price(stopPrice), text_color=bearishCol, bgcolor=rowBg, text_size=dashboardSize)
row += 1
if showTarget
table.cell(dashboard, 0, row, "Target", text_color=dashboardText, bgcolor=rowBg, text_size=dashboardSize)
table.cell(dashboard, 1, row, f_price(targetPrice), text_color=bullishCol, bgcolor=rowBg, text_size=dashboardSize)
row += 1
if showRiskReward
float risk = not na(entryPrice) and not na(stopPrice) ? math.abs(entryPrice - stopPrice) : na
float reward = not na(entryPrice) and not na(targetPrice) ? math.abs(targetPrice - entryPrice) : na
float rr = not na(risk) and risk > 0 and not na(reward) ? reward / risk : na
table.cell(dashboard, 0, row, "Reward / Risk", text_color=dashboardText, bgcolor=rowBg, text_size=dashboardSize)
table.cell(dashboard, 1, row, na(rr) ? "—" : "1:" + str.tostring(rr, "#.##"), text_color=dashboardText, bgcolor=rowBg, text_size=dashboardSize)
row += 1
if showTimeframe
table.cell(dashboard, 0, row, "Timeframe", text_color=dashboardText, bgcolor=rowBg, text_size=dashboardSize)
table.cell(dashboard, 1, row, is15m ? "15m OK" : "Switch to 15m", text_color=color.white, bgcolor=is15m ? bullishCol : bearishCol, text_size=dashboardSize)