Reversion Probability Bands [QuantAlgo]

QuantAlgo · study · 355 行 · 点赞 713 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This script is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
// https://creativecommons.org/licenses/by-nc-sa/4.0/
// © QuantAlgo
 
//@version=6
indicator("Reversion Probability Bands [QuantAlgo]", overlay = true)
 
//              ╔════════════════════════════════╗              //
//              ║      USER-DEFINED SETTINGS     ║              //
//              ╚════════════════════════════════╝              //
 
var string band_settings   = "════════ Band Settings ════════"
var string stats_settings  = "════════ Statistics Settings ════════"
var string signal_settings = "════════ Signal Settings ════════"
var string visual_settings = "════════ Visualization Settings ════════"
 
tooltip_source       = "The price series the mean and bands are built from. Close follows settled bar values, while averaged sources such as HL2 or HLC3 soften individual closing prints. Excursions, mean touches, and re-entry signals are always judged from each bar's close, high, and low, whichever source is selected."
tooltip_mean         = "Moving average used as the mean that price is expected to revert toward, and the level every excursion must reach to count as reverted. SMA weights every bar in the window equally, so the mean moves steadily. EMA and WMA weight recent bars more heavily, so the mean follows price more closely and meets a stretched price sooner. VWMA weights each bar by its volume, so the mean leans toward prices where the most trading took place. It needs volume data from the symbol, so on symbols without it, such as many indices, a warning appears on the chart in place of the bands."
tooltip_length       = "Number of bars used for the mean and the band width. Longer lengths (100-200) produce a slower mean and wider, steadier bands that price reaches less often, so each excursion reflects a larger stretch and fewer excursions are recorded. Shorter lengths (20-30) produce a faster mean and tighter bands that price reaches more often, so the statistics build a larger sample sooner. The bands begin once that many bars have loaded, so a length longer than the chart's history leaves them blank."
tooltip_basis        = "Unit used to space the bands from the mean. Standard Deviation measures how widely the source has been spread around its simple average over the same length, whichever Mean Type is selected, so the bands widen when prices scatter and tighten when they cluster. ATR measures the average true range of the chart's bars over the same length, including gaps and wicks, so the bands follow the size of individual bars rather than the spread of the source."
tooltip_inner        = "Distance of the inner bands from the mean, in units of the Band Width Basis. A close that crosses beyond an inner band starts an excursion for that band, and a close back inside it after closing beyond it prints a re-entry signal. Lower values place the inner bands closer to the mean, so excursions and signals occur more often. Keep the inner, middle, and outer multipliers in increasing order so the bands and zones stay nested."
tooltip_middle       = "Distance of the middle bands from the mean, in units of the Band Width Basis. Excursions beyond the middle bands are tracked separately from the inner bands, so the dashboard shows how often a deeper stretch has reverted. Keep the inner, middle, and outer multipliers in increasing order so the bands and zones stay nested."
tooltip_outer        = "Distance of the outer bands from the mean, in units of the Band Width Basis. These are the deepest stretches tracked, and excursions beyond them are the rarest, so their statistics take the longest history to reach the Min Sample Size. Keep the inner, middle, and outer multipliers in increasing order so the bands and zones stay nested."
tooltip_horizon      = "Number of bars an excursion is given to reach the mean. An excursion begins on a close that crosses from inside a band to beyond it, and counts as reverted if price reaches the mean within this many bars, or as not reverted once this many bars pass without it. Each band tracks one excursion at a time, so price can close back inside the band and cross it again within the same excursion, and the next excursion begins on the first such crossing after the open one resolves. The mean keeps moving while an excursion is open, so it can also meet price partway. Higher values (30-50) give each excursion more time and raise reversion rates. Lower values (5-10) count only fast reversions. Excursions still open on the latest bar are not counted until they resolve."
tooltip_touch        = "How a return to the mean is detected. Wick counts a reversion when the bar's low reaches the mean after an excursion above it, or its high reaches the mean after an excursion below it, so intrabar touches count. Close requires the bar to close at or through the mean, which is stricter and produces lower reversion rates and longer times to revert."
tooltip_max_events   = "Number of most recent completed excursions kept for each band. Once a band reaches this count, each new excursion replaces its oldest one, so the statistics follow a rolling sample. Lower values (50-100) make the statistics reflect recent behavior. Higher values (500-1000) draw on a longer history and produce steadier figures. Each band can only collect the excursions that occur within the bars loaded on the chart, which depend on the symbol's history, the chart timeframe, and the TradingView plan."
tooltip_min_sample   = "Number of completed excursions a band needs before its reversion rate, median bars to revert, and average adverse excursion are reported, and before the Min Reversion Rate filter can qualify it. Until then, the dashboard marks the band as below this sample size. Keep it at or below Max Events per Band, since a band never holds more excursions than that."
tooltip_signals      = "Enable/disable the re-entry signal markers. A bearish setup prints as a triangle above the closed bar where price closes back at or below the upper inner band after closing above it, and a bullish setup prints as a triangle below the closed bar where price closes back at or above the lower inner band after closing below it. The reversion setup alerts fire whether or not the markers are shown, and the Any alert() function call option sends every inner band stretch and reversion setup with that band's dashboard figures and the level of the mean in its message."
tooltip_min_rate     = "Reversion rate the inner band on that side must have reached before its re-entry signals print and alert. At 0, every signal prints. Above 0, a signal also requires that band to hold at least the Min Sample Size of completed excursions, and higher values keep only signals on sides whose inner band has reverted at least this often on this symbol and timeframe. The rate is measured from each excursion's first close beyond the band, so it describes the band's excursions as a whole rather than the outcome of an individual signal."
tooltip_color_preset = "Pre-configured color schemes for different chart themes and visual preferences. Classic uses traditional green and red. Aqua provides ocean-inspired blue and orange. Cosmic offers futuristic cyan and purple. Cyber features cool cyan and warm orange contrast. Neon delivers high-contrast yellow and magenta for maximum visibility. Each preset sets the bullish and bearish colors, while Custom uses the Bullish Color and Bearish Color set below. The bearish color marks the upper bands, where price is stretched above the mean, and the bullish color marks the lower bands, where it is stretched below. The Mean Color applies under every preset. On light chart backgrounds, colors too bright to stand out are darkened automatically, more for lines, markers, and text than for fills, and on dark backgrounds colors too dark to stand out are lightened, so every preset and custom color stays readable on either theme."
tooltip_bullish      = "Color applied to the lower bands and their labels, the lower zones, the bullish re-entry signals, and the dashboard rows for the lower bands, where price is stretched below the mean. Use a vibrant color to highlight potential long reversion opportunities. Its shade adapts to light and dark chart backgrounds as described under Color Preset. Only used when Color Preset is set to Custom."
tooltip_bearish      = "Color applied to the upper bands and their labels, the upper zones, the bearish re-entry signals, and the dashboard rows for the upper bands, where price is stretched above the mean. Use a warning color to highlight potential short reversion opportunities or exits. Its shade adapts to light and dark chart backgrounds as described under Color Preset. Only used when Color Preset is set to Custom."
tooltip_mean_color   = "Color of the mean line that every excursion is measured against. It applies under every Color Preset, so the mean keeps one consistent color while the band colors follow the preset. Its shade adapts to light and dark chart backgrounds as described under Color Preset."
tooltip_fills        = "Enable/disable the shaded zones between the bands. The zone between the inner and middle bands is shaded lightly and the zone between the middle and outer bands more strongly, so deeper stretches stand out. Upper zones use the bearish color and lower zones the bullish color."
tooltip_band_labels  = "Enable/disable the short labels at the right end of each band, such as 1 SD, 2 SD, and 3 SD, or the ATR multiple when Band Width Basis is set to ATR, so each band can be matched to its dashboard row at a glance. Each label takes its band's color and moves with the band on the latest bar."
tooltip_dashboard    = "Enable/disable the dashboard, which lists the reversion statistics of all six bands. Band names each band by side and distance from the mean. Events is the number of completed excursions beyond the band, up to Max Events per Band. Reverted is the share of those excursions that reached the mean within the Reversion Horizon, shaded more strongly as the share rises. Median Bars is the median number of bars the reverted excursions took to reach the mean. Avg Adverse is the average of the largest move against the reversion during each excursion, measured from its first close beyond the band as a percentage of that close, with decimal places added as it gets smaller so it stays readable down to second charts. Status shows the age in bars of the band's open excursion, which stays open until price reaches the mean or the Reversion Horizon passes, even while price is back inside the band, and stays blank after an excursion resolves until price next closes from inside the band to beyond it. Bands with fewer completed excursions than the Min Sample Size read n < followed by that size, with dashes in place of their figures. Hovering over each column heading explains its figure."
tooltip_dash_pos     = "Position on the chart where the dashboard is anchored, covering every corner, the middle of each edge, and the center. Tables from other indicators placed at the same position overlap with it. Only applies when Show Dashboard is turned on."
tooltip_text_size    = "Text size for the band labels and every row and figure in the dashboard. Tiny and Small keep them compact on the chart, while Normal and Large suit presentation and screen recording."
 
float srcInput          = input.source(close, "Source", group = band_settings, tooltip = tooltip_source)
string meanInput        = input.string("SMA", "Mean Type", group = band_settings, options = ["SMA", "EMA", "WMA", "VWMA"], tooltip = tooltip_mean)
int lenInput            = input.int(50, "Length", group = band_settings, minval = 3, maxval = 5000, tooltip = tooltip_length)
string dispInput        = input.string("Standard Deviation", "Band Width Basis", group = band_settings, options = ["Standard Deviation", "ATR"], tooltip = tooltip_basis)
float mult1Input        = input.float(1.0, "Inner Band Multiplier", group = band_settings, minval = 0.01, step = 0.1, tooltip = tooltip_inner)
float mult2Input        = input.float(2.0, "Middle Band Multiplier", group = band_settings, minval = 0.01, step = 0.1, tooltip = tooltip_middle)
float mult3Input        = input.float(3.0, "Outer Band Multiplier", group = band_settings, minval = 0.01, step = 0.1, tooltip = tooltip_outer)
 
int horizonInput        = input.int(20, "Reversion Horizon (Bars)", group = stats_settings, minval = 1, tooltip = tooltip_horizon)
string touchInput       = input.string("Wick", "Mean Touch", group = stats_settings, options = ["Wick", "Close"], tooltip = tooltip_touch)
int maxEventsInput      = input.int(300, "Max Events per Band", group = stats_settings, minval = 1, maxval = 100000, tooltip = tooltip_max_events)
int minSampleInput      = input.int(10, "Min Sample Size", group = stats_settings, minval = 1, maxval = 100000, tooltip = tooltip_min_sample)
 
bool signalsInput       = input.bool(true, "Show Re-Entry Signals", group = signal_settings, tooltip = tooltip_signals)
float minRateInput      = input.float(0.0, "Min Reversion Rate (%)", group = signal_settings, minval = 0.0, maxval = 100.0, step = 5.0, tooltip = tooltip_min_rate)
 
string colorPreset      = input.string("Custom", "Color Preset", group = visual_settings, options = ["Custom", "Classic", "Aqua", "Cosmic", "Cyber", "Neon"], tooltip = tooltip_color_preset)
color bullCustomInput   = input.color(#00ffaa, "Bullish Color", group = visual_settings, tooltip = tooltip_bullish)
color bearCustomInput   = input.color(#ff0000, "Bearish Color", group = visual_settings, tooltip = tooltip_bearish)
color meanColorInput    = input.color(#8c8c8c, "Mean Color", group = visual_settings, tooltip = tooltip_mean_color)
bool fillsInput         = input.bool(true, "Show Zone Fills", group = visual_settings, tooltip = tooltip_fills)
bool bandLabelsInput    = input.bool(true, "Show Band Labels", group = visual_settings, tooltip = tooltip_band_labels)
bool tableInput         = input.bool(true, "Show Dashboard", group = visual_settings, tooltip = tooltip_dashboard)
string tablePosInput    = input.string("Bottom Right", "Dashboard Position", group = visual_settings, options = ["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], tooltip = tooltip_dash_pos)
string textSizeInput    = input.string("Small", "Text Size", group = visual_settings, options = ["Tiny", "Small", "Normal", "Large"], tooltip = tooltip_text_size)
 
//              ╔════════════════════════════════╗              //
//              ║      PRESET CONFIGURATION      ║              //
//              ╚════════════════════════════════╝              //
 
[bullColor, bearColor] = switch colorPreset
    "Classic" => [#00ff00, #ff0000]
    "Aqua" => [#00d4ff, #ff8c00]
    "Cosmic" => [#49ffce, #9932cc]
    "Cyber" => [#00cccc, #ff6600]
    "Neon" => [#ffff00, #ff00ff]
    => [bullCustomInput, bearCustomInput]
 
string textSize = switch textSizeInput
    "Tiny"   => size.tiny
    "Normal" => size.normal
    "Large"  => size.large
    => size.small
 
float bgBright = (color.r(chart.bg_color) * 299.0 + color.g(chart.bg_color) * 587.0 + color.b(chart.bg_color) * 114.0) / 1000.0
bool lightBg   = bgBright >= 128.0
 
themed(color c, float lightCap, float darkFloor) =>
    float cB = (color.r(c) * 299.0 + color.g(c) * 587.0 + color.b(c) * 114.0) / 1000.0
    if lightBg and cB > lightCap
        color.rgb(color.r(c) * lightCap / cB, color.g(c) * lightCap / cB, color.b(c) * lightCap / cB)
    else if not lightBg and cB < darkFloor
        float t = (darkFloor - cB) / (255.0 - cB)
        color.rgb(color.r(c) + (255.0 - color.r(c)) * t, color.g(c) + (255.0 - color.g(c)) * t, color.b(c) + (255.0 - color.b(c)) * t)
    else
        c
 
color bullText = themed(bullColor, 100.0, 70.0)
color bearText = themed(bearColor, 100.0, 70.0)
color meanText = themed(meanColorInput, 100.0, 70.0)
color bullFill = themed(bullColor, 150.0, 50.0)
color bearFill = themed(bearColor, 150.0, 50.0)
 
//              ╔════════════════════════════════╗              //
//              ║            FUNCTIONS           ║              //
//              ╚════════════════════════════════╝              //
 
type ReversionSlot
    int startBar = -1
    float entry = na
    float adverse = 0.0
    int hitCount = 0
    array<int> hits
    array<int> bars
    array<float> adverses
 
bandMult(int lvl) =>
    lvl == 0 ? mult1Input : lvl == 1 ? mult2Input : mult3Input
 
slotCount(ReversionSlot s) =>
    array.size(s.hits)
 
slotRate(ReversionSlot s) =>
    int n = slotCount(s)
    n > 0 ? float(s.hitCount) / n * 100.0 : na
 
slotMedianBars(ReversionSlot s) =>
    array<float> hitBars = array.new<float>()
    int n = slotCount(s)
    if n > 0
        for j = 0 to n - 1
            if array.get(s.hits, j) == 1
                array.push(hitBars, float(array.get(s.bars, j)))
    array.size(hitBars) > 0 ? array.median(hitBars) : na
 
slotAvgAdverse(ReversionSlot s) =>
    array.size(s.adverses) > 0 ? array.avg(s.adverses) : na
 
bandTag(int lvl) =>
    str.tostring(bandMult(lvl), "#.##") + (dispInput == "ATR" ? " ATR" : " SD")
 
slotName(int i) =>
    (i < 3 ? "Upper " : "Lower ") + bandTag(i % 3)
 
fmtAdverse(float v) =>
    int dec = v > 0 ? math.max(2, math.ceil(-math.log10(v)) + 1) : 2
    str.tostring(v, "#." + str.repeat("#", dec)) + "%"
 
countText(float v, string unit) =>
    str.tostring(v, "#.#") + " " + unit + (v == 1 ? "" : "s")
 
statsText(ReversionSlot s, int i) =>
    int n          = slotCount(s)
    float medBars  = slotMedianBars(s)
    string medPart = na(medBars) ? "" : ", median " + countText(medBars, "bar")
    n >= minSampleInput ? slotName(i) + ": " + str.tostring(slotRate(s), "#.#") + "% of " + countText(n, "event") + " reverted within " + countText(horizonInput, "bar") + medPart + ", avg adverse " + fmtAdverse(slotAvgAdverse(s)) : slotName(i) + ": " + countText(n, "event") + ", below the Min Sample Size of " + str.tostring(minSampleInput)
 
//              ╔════════════════════════════════╗              //
//              ║        BAND CALCULATIONS       ║              //
//              ╚════════════════════════════════╝              //
 
float meanSma  = ta.sma(srcInput, lenInput)
float meanEma  = ta.ema(srcInput, lenInput)
float meanWma  = ta.wma(srcInput, lenInput)
float meanVwma = ta.vwma(srcInput, lenInput)
float basis    = meanInput == "EMA" ? meanEma : meanInput == "WMA" ? meanWma : meanInput == "VWMA" ? meanVwma : meanSma
float dispStd  = ta.stdev(srcInput, lenInput)
float dispAtr  = ta.atr(lenInput)
float bandUnit = dispInput == "ATR" ? dispAtr : dispStd
 
float up1 = basis + mult1Input * bandUnit
float up2 = basis + mult2Input * bandUnit
float up3 = basis + mult3Input * bandUnit
float dn1 = basis - mult1Input * bandUnit
float dn2 = basis - mult2Input * bandUnit
float dn3 = basis - mult3Input * bandUnit
 
//              ╔════════════════════════════════╗              //
//              ║        VOLUME VALIDATION       ║              //
//              ╚════════════════════════════════╝              //
 
float totalVolume = ta.cum(nz(volume))
var string warningText = "\n⚠️  WARNING  ⚠️\n\nNo volume data is provided for this symbol,\nso the VWMA mean and bands cannot be calculated.\n\nPlease set Mean Type to SMA, EMA, or WMA,\nor switch to a symbol that provides volume data.\n\nThis message will disappear once you make either change.\n"
 
if barstate.islast and meanInput == "VWMA" and totalVolume == 0
    var table warningTable = table.new(position.middle_center, 1, 1, frame_color = color.red, frame_width = 12)
    table.cell(warningTable, 0, 0, warningText, text_color = color.white, bgcolor = color.red, text_size = size.large)
 
//              ╔════════════════════════════════╗              //
//              ║      REVERSION STATISTICS      ║              //
//              ╚════════════════════════════════╝              //
 
var array<ReversionSlot> slots = array.new<ReversionSlot>()
 
if barstate.isfirst
    for i = 0 to 5
        array.push(slots, ReversionSlot.new(hits = array.new<int>(), bars = array.new<int>(), adverses = array.new<float>()))
 
if barstate.isconfirmed and not na(basis) and bandUnit > 0
    for i = 0 to 5
        ReversionSlot s = array.get(slots, i)
        bool isUpper   = i < 3
        float m        = bandMult(i % 3)
        float band     = isUpper ? basis + m * bandUnit : basis - m * bandUnit
        float bandPrev = isUpper ? basis[1] + m * bandUnit[1] : basis[1] - m * bandUnit[1]
        if s.startBar >= 0
            float adv = isUpper ? (high - s.entry) / s.entry * 100.0 : (s.entry - low) / s.entry * 100.0
            s.adverse := math.max(s.adverse, adv)
            float probe  = isUpper ? (touchInput == "Wick" ? low : close) : (touchInput == "Wick" ? high : close)
            bool touched = isUpper ? probe <= basis : probe >= basis
            int age      = bar_index - s.startBar
            if touched or age >= horizonInput
                int hit = touched ? 1 : 0
                if array.size(s.hits) >= maxEventsInput
                    int dropped = array.shift(s.hits)
                    array.shift(s.bars)
                    array.shift(s.adverses)
                    s.hitCount := s.hitCount - dropped
                array.push(s.hits, hit)
                array.push(s.bars, age)
                array.push(s.adverses, s.adverse)
                s.hitCount := s.hitCount + hit
                s.startBar := -1
                s.adverse  := 0.0
        if s.startBar < 0
            bool crossed = isUpper ? close > band and close[1] <= bandPrev : close < band and close[1] >= bandPrev
            if crossed
                s.startBar := bar_index
                s.entry    := close
                s.adverse  := 0.0
 
//              ╔════════════════════════════════╗              //
//              ║          SIGNAL ENGINE         ║              //
//              ╚════════════════════════════════╝              //
 
ReversionSlot upperInner = array.get(slots, 0)
ReversionSlot lowerInner = array.get(slots, 3)
float upperRate     = slotRate(upperInner)
float lowerRate     = slotRate(lowerInner)
bool upperQualified = minRateInput <= 0.0 or (slotCount(upperInner) >= minSampleInput and upperRate >= minRateInput)
bool lowerQualified = minRateInput <= 0.0 or (slotCount(lowerInner) >= minSampleInput and lowerRate >= minRateInput)
 
bool upperStretch = barstate.isconfirmed and close > up1 and close[1] <= up1[1]
bool lowerStretch = barstate.isconfirmed and close < dn1 and close[1] >= dn1[1]
bool bearSetup    = barstate.isconfirmed and close <= up1 and close[1] > up1[1] and upperQualified
bool bullSetup    = barstate.isconfirmed and close >= dn1 and close[1] < dn1[1] and lowerQualified
 
//              ╔════════════════════════════════╗              //
//              ║          VISUALIZATION         ║              //
//              ╚════════════════════════════════╝              //
 
pUp1 = plot(up1, "Upper Inner", color.new(bearText, 60), 1, display = display.all - display.price_scale)
pUp2 = plot(up2, "Upper Middle", color.new(bearText, 40), 1, display = display.all - display.price_scale)
pUp3 = plot(up3, "Upper Outer", color.new(bearText, 15), 2, display = display.all - display.price_scale)
plot(basis, "Mean", meanText, 2, display = display.all - display.price_scale)
pDn1 = plot(dn1, "Lower Inner", color.new(bullText, 60), 1, display = display.all - display.price_scale)
pDn2 = plot(dn2, "Lower Middle", color.new(bullText, 40), 1, display = display.all - display.price_scale)
pDn3 = plot(dn3, "Lower Outer", color.new(bullText, 15), 2, display = display.all - display.price_scale)
fill(pUp1, pUp2, color.new(bearFill, fillsInput ? 92 : 100), "Upper Inner Zone")
fill(pUp2, pUp3, color.new(bearFill, fillsInput ? 82 : 100), "Upper Outer Zone")
fill(pDn1, pDn2, color.new(bullFill, fillsInput ? 92 : 100), "Lower Inner Zone")
fill(pDn2, pDn3, color.new(bullFill, fillsInput ? 82 : 100), "Lower Outer Zone")
plotshape(signalsInput and bearSetup, "Bearish Reversion Setup", shape.triangledown, location.abovebar, bearText, size = size.small, display = display.pane)
plotshape(signalsInput and bullSetup, "Bullish Reversion Setup", shape.triangleup, location.belowbar, bullText, size = size.small, display = display.pane)
 
var array<label> bandLabels = array.new<label>()
 
if barstate.islast
    for lbl in bandLabels
        label.delete(lbl)
    array.clear(bandLabels)
    if bandLabelsInput
        for i = 0 to 5
            float level = i == 0 ? up1 : i == 1 ? up2 : i == 2 ? up3 : i == 3 ? dn1 : i == 4 ? dn2 : dn3
            array.push(bandLabels, label.new(bar_index + 1, level, bandTag(i % 3), style = label.style_label_left, color = color.new(chart.bg_color, 100), textcolor = i < 3 ? bearText : bullText, size = textSize))
 
//              ╔════════════════════════════════╗              //
//              ║            DASHBOARD           ║              //
//              ╚════════════════════════════════╝              //
 
string tablePos = switch tablePosInput
    "Top Center"    => position.top_center
    "Top Right"     => position.top_right
    "Middle Left"   => position.middle_left
    "Middle Center" => position.middle_center
    "Middle Right"  => position.middle_right
    "Bottom Left"   => position.bottom_left
    "Bottom Center" => position.bottom_center
    "Bottom Right"  => position.bottom_right
    => position.top_left
 
var table dash = tableInput ? table.new(tablePos, 6, 7, border_width = 1, border_color = color.new(chart.fg_color, 85), frame_width = 1, frame_color = color.new(chart.fg_color, 70)) : na
 
if barstate.islast and not na(dash)
    color hdrBg  = color.new(chart.fg_color, 85)
    color cellBg = color.new(chart.bg_color, 10)
    color txt    = chart.fg_color
    table.cell(dash, 0, 0, "Band", text_color = txt, bgcolor = hdrBg, text_size = textSize, text_halign = text.align_left, tooltip = "Each band by side and distance from the mean, in units of the Band Width Basis.")
    table.cell(dash, 1, 0, "Events", text_color = txt, bgcolor = hdrBg, text_size = textSize, tooltip = "Completed excursions beyond the band, keeping the most recent Max Events per Band.")
    table.cell(dash, 2, 0, "Reverted (" + countText(horizonInput, "Bar") + ")", text_color = txt, bgcolor = hdrBg, text_size = textSize, tooltip = "Share of the completed excursions that reached the mean within the Reversion Horizon, shaded more strongly as the share rises.")
    table.cell(dash, 3, 0, "Median Bars", text_color = txt, bgcolor = hdrBg, text_size = textSize, tooltip = "Median number of bars the reverted excursions took to reach the mean.")
    table.cell(dash, 4, 0, "Avg Adverse", text_color = txt, bgcolor = hdrBg, text_size = textSize, tooltip = "Average of the largest move against the reversion during each excursion, as a percentage of its first close beyond the band.")
    table.cell(dash, 5, 0, "Status", text_color = txt, bgcolor = hdrBg, text_size = textSize, tooltip = "Age in bars of the band's open excursion, which stays open until price reaches the mean or the Reversion Horizon passes and then joins the statistics.")
    for i = 0 to 5
        ReversionSlot s = array.get(slots, i)
        color sideText  = i < 3 ? bearText : bullText
        color sideFill  = i < 3 ? bearFill : bullFill
        int n           = slotCount(s)
        bool enough     = n >= minSampleInput
        float rate      = slotRate(s)
        float medBars   = slotMedianBars(s)
        float avgAdv    = slotAvgAdverse(s)
        string rateText = enough ? str.tostring(rate, "#.#") + "%" : "n < " + str.tostring(minSampleInput)
        string medText  = enough and not na(medBars) ? str.tostring(medBars, "#.#") : "-"
        string advText  = enough and not na(avgAdv) ? fmtAdverse(avgAdv) : "-"
        string status   = s.startBar >= 0 ? "Open (" + str.tostring(bar_index - s.startBar) + ")" : ""
        color rateBg    = enough ? color.from_gradient(rate, 0.0, 100.0, color.new(sideFill, 92), color.new(sideFill, 45)) : cellBg
        int row = i + 1
        table.cell(dash, 0, row, slotName(i), text_color = sideText, bgcolor = cellBg, text_size = textSize, text_halign = text.align_left)
        table.cell(dash, 1, row, str.tostring(n), text_color = txt, bgcolor = cellBg, text_size = textSize)
        table.cell(dash, 2, row, rateText, text_color = txt, bgcolor = rateBg, text_size = textSize)
        table.cell(dash, 3, row, medText, text_color = txt, bgcolor = cellBg, text_size = textSize)
        table.cell(dash, 4, row, advText, text_color = txt, bgcolor = cellBg, text_size = textSize)
        table.cell(dash, 5, row, status, text_color = sideText, bgcolor = cellBg, text_size = textSize)
 
//              ╔════════════════════════════════╗              //
//              ║             ALERTS             ║              //
//              ╚════════════════════════════════╝              //
 
string symbolText = syminfo.prefix + ":" + syminfo.ticker + " - " + timeframe.period
 
alertcondition(upperStretch, title = "Upper Band Stretch", message = "Reversion Probability Bands: UPPER band stretch with a close above the upper inner band on {{exchange}}:{{ticker}} - {{interval}}")
alertcondition(lowerStretch, title = "Lower Band Stretch", message = "Reversion Probability Bands: LOWER band stretch with a close below the lower inner band on {{exchange}}:{{ticker}} - {{interval}}")
alertcondition(bearSetup, title = "Bearish Reversion Setup", message = "Reversion Probability Bands: BEARISH reversion setup with a close back under the upper inner band on {{exchange}}:{{ticker}} - {{interval}}")
alertcondition(bullSetup, title = "Bullish Reversion Setup", message = "Reversion Probability Bands: BULLISH reversion setup with a close back above the lower inner band on {{exchange}}:{{ticker}} - {{interval}}")
alertcondition(bearSetup or bullSetup, title = "Any Reversion Setup", message = "Reversion Probability Bands: REVERSION setup with a close back inside an inner band on {{exchange}}:{{ticker}} - {{interval}}")
 
if barstate.isrealtime and upperStretch
    alert("Reversion Probability Bands: upper band stretch with a close above the upper " + bandTag(0) + " band on " + symbolText + ". " + statsText(upperInner, 0) + ". Mean at " + str.tostring(basis, format.mintick) + ".", alert.freq_once_per_bar_close)
if barstate.isrealtime and lowerStretch
    alert("Reversion Probability Bands: lower band stretch with a close below the lower " + bandTag(0) + " band on " + symbolText + ". " + statsText(lowerInner, 3) + ". Mean at " + str.tostring(basis, format.mintick) + ".", alert.freq_once_per_bar_close)
if barstate.isrealtime and bearSetup
    alert("Reversion Probability Bands: bearish reversion setup with a close back under the upper " + bandTag(0) + " band on " + symbolText + ". " + statsText(upperInner, 0) + ". Mean at " + str.tostring(basis, format.mintick) + ".", alert.freq_once_per_bar_close)
if barstate.isrealtime and bullSetup
    alert("Reversion Probability Bands: bullish reversion setup with a close back above the lower " + bandTag(0) + " band on " + symbolText + ". " + statsText(lowerInner, 3) + ". Mean at " + str.tostring(basis, format.mintick) + ".", alert.freq_once_per_bar_close)
 
//              ╔════════════════════════════════╗              //
//              ║           CREATED BY           ║              //
//              ╚════════════════════════════════╝              //
 
// ██████╗ ██╗   ██╗ █████╗ ███╗   ██╗████████╗     █████╗ ██╗      ██████╗  ██████╗ 
//██╔═══██╗██║   ██║██╔══██╗████╗  ██║╚══██╔══╝    ██╔══██╗██║     ██╔════╝ ██╔═══██╗
//██║   ██║██║   ██║███████║██╔██╗ ██║   ██║       ███████║██║     ██║  ███╗██║   ██║
//██║▄▄ ██║██║   ██║██╔══██║██║╚██╗██║   ██║       ██╔══██║██║     ██║   ██║██║   ██║
//╚██████╔╝╚██████╔╝██║  ██║██║ ╚████║   ██║       ██║  ██║███████╗╚██████╔╝╚██████╔╝
// ╚══▀▀═╝  ╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═══╝   ╚═╝       ╚═╝  ╚═╝╚══════╝ ╚═════╝  ╚═════╝

← 返回列表