Reversal Z-Score Bands (Black-Chart)

Black-Chart · study · 450 行 · 点赞 27 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the Mozilla Public License 2.0.
// © Black-Chart
//@version=6
indicator("Reversal Z-Score Bands (Black-Chart)", shorttitle = "Reversal Z-Bands", overlay = false, max_lines_count = 500, max_labels_count = 50)
 
color cObsidian = color.new(#08090d, 0)
color cCharcoal = color.new(#121418, 8)
color cGraphite = color.new(#1a1c22, 8)
color cSlate    = color.new(#2a2d35, 0)
color cGhost    = color.new(#3a3d45, 0)
color cChrome   = color.new(#c8c8cc, 0)
color cSilver   = color.new(#8a8a8e, 0)
color cSteel    = color.new(#484a50, 0)
color cAccBuy   = color.new(#4FC3F7, 0)
color cAccSell  = color.new(#CE93D8, 0)
 
string S_SOLID  = "Solid"
string S_DASH   = "Dashed"
string S_DOT    = "Dotted"
string M_EXP    = "Exponential (EMA weights)"
string M_WIN    = "Fixed window (last N bars)"
string P_CANDLE = "Candles"
string P_LINE   = "Line"
 
string G_EMA  = "EMA & Deviation"
string G_SLP  = "EMA Slope"
string G_BND  = "Bands"
string G_PANE = "Oscillator Pane"
string G_SIG  = "Signals"
string G_BG   = "Volatility Background"
string G_TCH  = "First Touch Level"
string G_LIQ  = "Liquidity Levels"
string G_DB   = "Dashboard"
 
string TT_LEN   = "With the «Exponential» Deviation Method the source cannot move further than √((N−1)/2) σ from the EMA: about 2σ with 9, 3σ with 20, 10σ with 200, 22σ with 999. Bands beyond that value are never reached by a close, and the same cap applies to the volume z-score."
string TT_DEV   = "Exponential: the deviation weights the bars with the same weights as the EMA, the way VWAP weights by volume. Fixed window: deviation from the EMA over the last N bars, all weighted equally. N = Length."
string TT_CHART = "Also draws on the price chart the EMA (coloured by slope), the enabled bands and the Volatility Background. Triangles, diamonds and fills stay in the pane only."
string TT_SLP   = "Colours the EMA (and the pane's zero line) Rising or Falling when it has moved more than Flat Threshold σ over the window: Window × Length (EMA 200 and 0.25 → 50 bars). Window and Flat Threshold also apply to «Only with Flat EMA» and to the dashboard EMA row, even with the colouring off."
string TT_BAND  = "× σ: distance of the band from the EMA, in standard deviations. Fill: in the pane, shades the area between zero (the EMA) and the level with the band colour. Above and Below: band colour above and below the EMA."
string TT_PANE  = "Candles: open, high, low and close as distance from the EMA in σ, wicks included. Line: the Source only, in σ."
string TT_Z     = "Distance from the EMA in standard deviations: (price − EMA) ÷ σ. In the pane the zero line is the EMA and the horizontal lines are the enabled bands."
string TT_K     = "Level in σ used by Re-entry Triangles, Extreme Volume Diamonds and Volatility Background."
string TT_RE    = "Triangle in the From Above / From Below colours: the close comes back inside the first-touch level, i.e. the price where the ±kσ band stood at the first close outside it (see First Touch Level). The signal is the price coming back, not the touch. Re-entry alerts fire when the z-score comes back inside ±kσ, including when it was the band that moved back."
string TT_BRE   = "Grey triangle: the z-score is back inside ±kσ but the close is still beyond the first-touch level. The band came back, by widening or moving toward price; the price did not."
string TT_REF   = "Marks re-entries only while the EMA is flat at that moment (see EMA Slope)."
string TT_VOL   = "Diamond on the bar whose high (or low) reaches beyond ±kσ with abnormal volume: volume as a z-score against its mean, with the Deviation Method weights and the EMA Length."
string TT_ATR   = "Shades the background while the close (Source) is beyond ±kσ. Short ATR ÷ ATR over the EMA Length: above Expansion Threshold the bars are widening (Expansion), below it they are not (Stable)."
string TT_TCH   = "At the first close (Source) beyond ±kσ, fixes the price of the band at that moment. On Price Chart: a horizontal line that no longer moves. In Pane: the same price measured in the current σ, which moves because the EMA and σ move while the level's price stays fixed. Ends when the close comes back inside that price or reaches the EMA."
string TT_LIQ   = "High and low of the previous day (PDH, PDL), previous week (PWH, PWL) and previous month (PMH, PML), with their current distance from the EMA in σ. In Pane: a short segment to the right of the last bar at the level's height in σ (day, then week, then month, left to right) and a label with name and σ; levels less than 0.25σ apart share one label. On Price Chart: lines from the start of the current period, with price and σ. Day, Week and Month switch each period on or off (only Day by default). Day, week and month follow the symbol's session."
string TT_TAB   = "Dashboard: EMA slope on three timeframes and the volatility regime. The square on the left is filled (▪) when the computed timeframes agree, or when the ATR is above the minimum; empty (▫) otherwise."
string TT_COLS  = "EMA row: slope of the dashboard EMA on each timeframe (▲ BULL, ▼ BEAR or FLAT), with Window and Flat Threshold from EMA Slope. «—» = not enough bars yet."
string TT_ATD   = "ATR(14) divided by its mean over the last 24 hours, counted in chart bars: 1,440 on 1 minute, 288 on 5 minutes, 96 on 15 minutes. OK from this minimum up, LOW below it: the market is moving less than usual."
string TT_TFS   = "Timeframes of the three columns. Empty = chart timeframe. Timeframes higher than the chart use the last CLOSED bar of that timeframe, so they do not repaint. A timeframe lower than the chart is not computed (BELOW TF)."
 
int    emaLen    = input.int(200, "Length", minval = 1, group = G_EMA, tooltip = TT_LEN)
float  src       = input.source(close, "Source", group = G_EMA)
string devMode   = input.string(M_EXP, "Deviation Method", options = [M_EXP, M_WIN], group = G_EMA, tooltip = TT_DEV)
bool   emaShow   = input.bool(true, "Show EMA", inline = "e1", group = G_EMA)
color  emaCol    = input.color(#2962FF, "", inline = "e1", group = G_EMA, active = emaShow)
int    emaW      = input.int(2, "Width", minval = 1, maxval = 4, inline = "e2", group = G_EMA, active = emaShow)
string emaSt     = input.string(S_SOLID, "Style", options = [S_SOLID, S_DASH, S_DOT], inline = "e2", group = G_EMA, active = emaShow)
bool   showChart = input.bool(false, "Also on Price Chart", group = G_EMA, tooltip = TT_CHART)
int    offs      = input.int(0, "Offset", minval = -500, maxval = 500, group = G_EMA, display = display.none)
 
bool   slpOn  = input.bool(true, "Color EMA by Slope", group = G_SLP, tooltip = TT_SLP)
color  slpUpC = input.color(#26A69A, "Rising", inline = "s1", group = G_SLP, active = slpOn)
color  slpDnC = input.color(#EF5350, "Falling", inline = "s1", group = G_SLP, active = slpOn)
float  slpWin = input.float(0.25, "Window (× Length)", minval = 0.01, maxval = 1.0, step = 0.05, group = G_SLP)
float  slpThr = input.float(0.5, "Flat Threshold (σ)", minval = 0.0, step = 0.1, group = G_SLP)
 
bool   b1Show = input.bool(true, "Band 1", inline = "b1a", group = G_BND, tooltip = TT_BAND)
float  b1Mult = input.float(1.0, "× σ", minval = 0.01, step = 0.25, inline = "b1a", group = G_BND, active = b1Show)
bool   b1Fill = input.bool(false, "Fill", inline = "b1a", group = G_BND, active = b1Show)
color  b1Up   = input.color(#26A69A, "Above", inline = "b1b", group = G_BND, active = b1Show)
color  b1Dn   = input.color(#26A69A, "Below", inline = "b1b", group = G_BND, active = b1Show)
int    b1W    = input.int(1, "Width", minval = 1, maxval = 4, inline = "b1b", group = G_BND, active = b1Show)
string b1St   = input.string(S_DOT, "Style", options = [S_SOLID, S_DASH, S_DOT], inline = "b1b", group = G_BND, active = b1Show)
bool   b2Show = input.bool(true, "Band 2", inline = "b2a", group = G_BND)
float  b2Mult = input.float(2.0, "× σ", minval = 0.01, step = 0.25, inline = "b2a", group = G_BND, active = b2Show)
bool   b2Fill = input.bool(false, "Fill", inline = "b2a", group = G_BND, active = b2Show)
color  b2Up   = input.color(#FFB300, "Above", inline = "b2b", group = G_BND, active = b2Show)
color  b2Dn   = input.color(#FFB300, "Below", inline = "b2b", group = G_BND, active = b2Show)
int    b2W    = input.int(1, "Width", minval = 1, maxval = 4, inline = "b2b", group = G_BND, active = b2Show)
string b2St   = input.string(S_DOT, "Style", options = [S_SOLID, S_DASH, S_DOT], inline = "b2b", group = G_BND, active = b2Show)
bool   b3Show = input.bool(true, "Band 3", inline = "b3a", group = G_BND)
float  b3Mult = input.float(3.0, "× σ", minval = 0.01, step = 0.25, inline = "b3a", group = G_BND, active = b3Show)
bool   b3Fill = input.bool(false, "Fill", inline = "b3a", group = G_BND, active = b3Show)
color  b3Up   = input.color(#FF7043, "Above", inline = "b3b", group = G_BND, active = b3Show)
color  b3Dn   = input.color(#FF7043, "Below", inline = "b3b", group = G_BND, active = b3Show)
int    b3W    = input.int(1, "Width", minval = 1, maxval = 4, inline = "b3b", group = G_BND, active = b3Show)
string b3St   = input.string(S_DOT, "Style", options = [S_SOLID, S_DASH, S_DOT], inline = "b3b", group = G_BND, active = b3Show)
bool   b4Show = input.bool(false, "Band 4", inline = "b4a", group = G_BND)
float  b4Mult = input.float(4.0, "× σ", minval = 0.01, step = 0.25, inline = "b4a", group = G_BND, active = b4Show)
bool   b4Fill = input.bool(false, "Fill", inline = "b4a", group = G_BND, active = b4Show)
color  b4Up   = input.color(#EF5350, "Above", inline = "b4b", group = G_BND, active = b4Show)
color  b4Dn   = input.color(#EF5350, "Below", inline = "b4b", group = G_BND, active = b4Show)
int    b4W    = input.int(1, "Width", minval = 1, maxval = 4, inline = "b4b", group = G_BND, active = b4Show)
string b4St   = input.string(S_DOT, "Style", options = [S_SOLID, S_DASH, S_DOT], inline = "b4b", group = G_BND, active = b4Show)
bool   b5Show = input.bool(false, "Band 5", inline = "b5a", group = G_BND)
float  b5Mult = input.float(5.0, "× σ", minval = 0.01, step = 0.25, inline = "b5a", group = G_BND, active = b5Show)
bool   b5Fill = input.bool(false, "Fill", inline = "b5a", group = G_BND, active = b5Show)
color  b5Up   = input.color(#AB47BC, "Above", inline = "b5b", group = G_BND, active = b5Show)
color  b5Dn   = input.color(#AB47BC, "Below", inline = "b5b", group = G_BND, active = b5Show)
int    b5W    = input.int(1, "Width", minval = 1, maxval = 4, inline = "b5b", group = G_BND, active = b5Show)
string b5St   = input.string(S_DOT, "Style", options = [S_SOLID, S_DASH, S_DOT], inline = "b5b", group = G_BND, active = b5Show)
int    fillTr = input.int(90, "Fill Transparency", minval = 0, maxval = 100, group = G_BND)
 
string paneStyle = input.string(P_LINE, "Pane View", options = [P_CANDLE, P_LINE], group = G_PANE, tooltip = TT_PANE)
bool   zShow     = input.bool(true, "Show Z-score", inline = "z1", group = G_PANE, tooltip = TT_Z)
color  zCol      = input.color(#E0E0E0, "", inline = "z1", group = G_PANE, active = zShow and paneStyle == P_LINE)
int    zW        = input.int(1, "Line Width", minval = 1, maxval = 4, group = G_PANE, active = zShow and paneStyle == P_LINE)
color  cUpC      = input.color(#D1D4DC, "Up Candle", inline = "c1", group = G_PANE, active = zShow and paneStyle == P_CANDLE)
color  cDnC      = input.color(#5D606B, "Down Candle", inline = "c1", group = G_PANE, active = zShow and paneStyle == P_CANDLE)
 
float  kLev     = input.float(2.0, "Signal Level k (σ)", minval = 0.1, step = 0.25, group = G_SIG, tooltip = TT_K)
bool   reOn     = input.bool(true, "Re-entry Triangles", group = G_SIG, tooltip = TT_RE)
color  reUpC    = input.color(#FF5252, "From Above", inline = "r1", group = G_SIG, active = reOn)
color  reDnC    = input.color(#00E676, "From Below", inline = "r1", group = G_SIG, active = reOn)
bool   bandReOn = input.bool(true, "Band Re-entry", inline = "r2", group = G_SIG, active = reOn)
color  bandReC  = input.color(#9E9E9E, "", inline = "r2", group = G_SIG, active = reOn and bandReOn, tooltip = TT_BRE)
bool   reFlat   = input.bool(false, "Only with Flat EMA", group = G_SIG, active = reOn, tooltip = TT_REF)
bool   volOn    = input.bool(true, "Extreme Volume Diamonds", group = G_SIG, tooltip = TT_VOL)
float  volThr   = input.float(3.0, "Volume Threshold (z)", minval = 0.1, step = 0.5, group = G_SIG, active = volOn)
color  volUpC   = input.color(#FFD600, "Above", inline = "v1", group = G_SIG, active = volOn)
color  volDnC   = input.color(#FFD600, "Below", inline = "v1", group = G_SIG, active = volOn)
 
bool   atrOn   = input.bool(true, "Show Background", group = G_BG, tooltip = TT_ATR)
int    atrFast = input.int(14, "Short ATR (bars)", minval = 1, group = G_BG, active = atrOn)
float  atrThr  = input.float(1.5, "Expansion Threshold (×)", minval = 0.1, step = 0.1, group = G_BG, active = atrOn)
color  atrExpC = input.color(color.new(#FF9800, 85), "Expansion", inline = "a1", group = G_BG, active = atrOn)
color  atrStbC = input.color(color.new(#2962FF, 85), "Stable", inline = "a1", group = G_BG, active = atrOn)
 
bool   tchPane  = input.bool(true, "In Pane", inline = "p0", group = G_TCH, tooltip = TT_TCH)
bool   tchChart = input.bool(true, "On Price Chart", inline = "p0", group = G_TCH)
color  tchCol   = input.color(#00BCD4, "Color", inline = "p1", group = G_TCH, active = tchPane or tchChart)
int    tchW     = input.int(1, "Width", minval = 1, maxval = 4, inline = "p1", group = G_TCH, active = tchPane or tchChart)
string tchSt    = input.string(S_DASH, "Style", options = [S_SOLID, S_DASH, S_DOT], inline = "p1", group = G_TCH, active = tchPane or tchChart)
 
bool   liqPane  = input.bool(true, "In Pane", inline = "l0", group = G_LIQ, tooltip = TT_LIQ)
bool   liqChart = input.bool(false, "On Price Chart", inline = "l0", group = G_LIQ)
bool   liqDOn   = input.bool(true, "Day", inline = "l1", group = G_LIQ, active = liqPane or liqChart)
color  liqDC    = input.color(#FFFFFF, "", inline = "l1", group = G_LIQ, active = (liqPane or liqChart) and liqDOn)
bool   liqWOn   = input.bool(false, "Week", inline = "l2", group = G_LIQ, active = liqPane or liqChart)
color  liqWC    = input.color(#F06292, "", inline = "l2", group = G_LIQ, active = (liqPane or liqChart) and liqWOn)
bool   liqMOn   = input.bool(false, "Month", inline = "l3", group = G_LIQ, active = liqPane or liqChart)
color  liqMC    = input.color(#B388FF, "", inline = "l3", group = G_LIQ, active = (liqPane or liqChart) and liqMOn)
 
bool   tabOn    = input.bool(true, "Show Dashboard", group = G_DB, tooltip = TT_TAB)
string dbPos    = input.string("bottom_right", "Position", options = ["top_right", "top_left", "bottom_right", "bottom_left"], group = G_DB, active = tabOn)
string dbSize   = input.string("Medium", "Dashboard Size", options = ["Small", "Medium", "Large"], group = G_DB, active = tabOn)
bool   colEma   = input.bool(true, "EMA Row", group = G_DB, active = tabOn, tooltip = TT_COLS)
string tf1      = input.timeframe("", "Timeframe 1", group = G_DB, active = tabOn, tooltip = TT_TFS)
string tf2      = input.timeframe("15", "Timeframe 2", group = G_DB, active = tabOn)
string tf3      = input.timeframe("60", "Timeframe 3", group = G_DB, active = tabOn)
int    tEmaLen  = input.int(200, "Dashboard EMA Length", minval = 2, group = G_DB, active = tabOn and colEma)
bool   atdTab   = input.bool(true, "ATR ÷ Day Mean", inline = "k2", group = G_DB, active = tabOn, tooltip = TT_ATD)
float  atdMin   = input.float(0.64, "Min", minval = 0.0, maxval = 5.0, step = 0.01, inline = "k2", group = G_DB, active = tabOn and atdTab)
 
string szData = dbSize == "Large" ? size.normal : dbSize == "Medium" ? size.small : size.tiny
string szSect = dbSize == "Large" ? size.small : size.tiny
string szHead = dbSize == "Large" ? size.normal : dbSize == "Medium" ? size.small : size.tiny
 
float emaV   = ta.ema(src, emaLen)
max_bars_back(emaV, 5000)
float varExp = ta.ema(src * src, emaLen) - emaV * emaV
float varWin = math.sum(math.pow(src - emaV, 2), emaLen) / emaLen
float sd     = math.sqrt(math.max(devMode == M_EXP ? varExp : varWin, 0.0))
float sdOk   = sd > 0 ? sd : na
 
float z   = (src - emaV) / sdOk
float zHi = (high - emaV) / sdOk
float zLo = (low - emaV) / sdOk
float zOp = (open - emaV) / sdOk
float zCl = (close - emaV) / sdOk
 
int   slpLen = math.min(math.max(1, math.round(emaLen * slpWin)), 4999)
float slope  = (emaV - emaV[slpLen]) / sdOk
bool  isFlat = math.abs(slope) <= slpThr
 
float vMeanE = ta.ema(volume, emaLen)
float vSdE   = math.sqrt(math.max(ta.ema(volume * volume, emaLen) - vMeanE * vMeanE, 0.0))
float vMeanW = ta.sma(volume, emaLen)
float vSdW   = ta.stdev(volume, emaLen)
float vMean  = devMode == M_EXP ? vMeanE : vMeanW
float vSd    = devMode == M_EXP ? vSdE : vSdW
float vz     = vSd > 0 ? (volume - vMean) / vSd : na
 
float atrRatio = ta.atr(atrFast) / ta.atr(emaLen)
float atr14    = ta.atr(14)
int   dayLen   = math.min(5000, math.max(1, math.round(86400.0 / timeframe.in_seconds())))
float atrDay   = ta.sma(atr14, dayLen)
float atdRatio = not na(atrDay) and atrDay > 0 ? atr14 / atrDay : na
 
[pdh, pdl, dT] = request.security(syminfo.tickerid, "D", [high[1], low[1], time], lookahead = barmerge.lookahead_on)
[pwh, pwl, wT] = request.security(syminfo.tickerid, "W", [high[1], low[1], time], lookahead = barmerge.lookahead_on)
[pmh, pml, mT] = request.security(syminfo.tickerid, "M", [high[1], low[1], time], lookahead = barmerge.lookahead_on)
bool  atrExp   = atrRatio >= atrThr
 
bool zReUp   = z[1] > kLev and z <= kLev
bool zReDn   = z[1] < -kLev and z >= -kLev
bool flatOk  = not reFlat or isFlat
bool reUp    = zReUp and flatOk
bool reDn    = zReDn and flatOk
bool clUp    = zHi >= kLev and vz >= volThr
bool clDn    = zLo <= -kLev and vz >= volThr
bool outside = math.abs(z) >= kLev
 
var int   tSide = 0
var float tLvl  = na
var line  tLine = na
 
int   side0  = tSide
float tDraw  = na
bool  pRe    = false
bool  bRe    = false
 
if side0 != 0
    tDraw := tLvl
    bool pBack = side0 > 0 ? src <= tLvl : src >= tLvl
    bool eBack = side0 > 0 ? src <= emaV : src >= emaV
    pRe := pBack
    bRe := not pBack and (side0 > 0 ? zReUp : zReDn)
    if not na(tLine)
        line.set_x2(tLine, time)
    if pBack or eBack
        tSide := 0
else if not na(z) and math.abs(z) > kLev
    tSide := z > 0 ? 1 : -1
    tLvl  := emaV + tSide * kLev * sd
    tDraw := tLvl
    tLine := na
    if tchChart
        tLine := line.new(time, tLvl, time, tLvl, xloc = xloc.bar_time, color = tchCol, width = tchW, style = tchSt == S_DASH ? line.style_dashed : tchSt == S_DOT ? line.style_dotted : line.style_solid, force_overlay = true)
 
bool triUp = flatOk and side0 > 0 and (pRe or (bandReOn and bRe))
bool triDn = flatOk and side0 < 0 and (pRe or (bandReOn and bRe))
 
bool  isCandle = paneStyle == P_CANDLE
float yUp      = isCandle ? zHi : z
float yDn      = isCandle ? zLo : z
color emaNow   = slpOn and not na(slope) and not isFlat ? (slope > 0 ? slpUpC : slpDnC) : emaCol
color candleC  = zCl >= zOp ? cUpC : cDnC
 
plot(emaV, "EMA", color = emaNow, linewidth = emaW, linestyle = emaSt == S_DASH ? plot.linestyle_dashed : emaSt == S_DOT ? plot.linestyle_dotted : plot.linestyle_solid, offset = offs, display = showChart and emaShow ? display.all : display.none, force_overlay = true)
 
plot(emaV + sd * b1Mult, "Band 1 upper", color = b1Up, linewidth = b1W, linestyle = b1St == S_DASH ? plot.linestyle_dashed : b1St == S_DOT ? plot.linestyle_dotted : plot.linestyle_solid, offset = offs, display = showChart and b1Show ? display.all : display.none, force_overlay = true)
plot(emaV - sd * b1Mult, "Band 1 lower", color = b1Dn, linewidth = b1W, linestyle = b1St == S_DASH ? plot.linestyle_dashed : b1St == S_DOT ? plot.linestyle_dotted : plot.linestyle_solid, offset = offs, display = showChart and b1Show ? display.all : display.none, force_overlay = true)
plot(emaV + sd * b2Mult, "Band 2 upper", color = b2Up, linewidth = b2W, linestyle = b2St == S_DASH ? plot.linestyle_dashed : b2St == S_DOT ? plot.linestyle_dotted : plot.linestyle_solid, offset = offs, display = showChart and b2Show ? display.all : display.none, force_overlay = true)
plot(emaV - sd * b2Mult, "Band 2 lower", color = b2Dn, linewidth = b2W, linestyle = b2St == S_DASH ? plot.linestyle_dashed : b2St == S_DOT ? plot.linestyle_dotted : plot.linestyle_solid, offset = offs, display = showChart and b2Show ? display.all : display.none, force_overlay = true)
plot(emaV + sd * b3Mult, "Band 3 upper", color = b3Up, linewidth = b3W, linestyle = b3St == S_DASH ? plot.linestyle_dashed : b3St == S_DOT ? plot.linestyle_dotted : plot.linestyle_solid, offset = offs, display = showChart and b3Show ? display.all : display.none, force_overlay = true)
plot(emaV - sd * b3Mult, "Band 3 lower", color = b3Dn, linewidth = b3W, linestyle = b3St == S_DASH ? plot.linestyle_dashed : b3St == S_DOT ? plot.linestyle_dotted : plot.linestyle_solid, offset = offs, display = showChart and b3Show ? display.all : display.none, force_overlay = true)
plot(emaV + sd * b4Mult, "Band 4 upper", color = b4Up, linewidth = b4W, linestyle = b4St == S_DASH ? plot.linestyle_dashed : b4St == S_DOT ? plot.linestyle_dotted : plot.linestyle_solid, offset = offs, display = showChart and b4Show ? display.all : display.none, force_overlay = true)
plot(emaV - sd * b4Mult, "Band 4 lower", color = b4Dn, linewidth = b4W, linestyle = b4St == S_DASH ? plot.linestyle_dashed : b4St == S_DOT ? plot.linestyle_dotted : plot.linestyle_solid, offset = offs, display = showChart and b4Show ? display.all : display.none, force_overlay = true)
plot(emaV + sd * b5Mult, "Band 5 upper", color = b5Up, linewidth = b5W, linestyle = b5St == S_DASH ? plot.linestyle_dashed : b5St == S_DOT ? plot.linestyle_dotted : plot.linestyle_solid, offset = offs, display = showChart and b5Show ? display.all : display.none, force_overlay = true)
plot(emaV - sd * b5Mult, "Band 5 lower", color = b5Dn, linewidth = b5W, linestyle = b5St == S_DASH ? plot.linestyle_dashed : b5St == S_DOT ? plot.linestyle_dotted : plot.linestyle_solid, offset = offs, display = showChart and b5Show ? display.all : display.none, force_overlay = true)
 
bgcolor(showChart and atrOn and outside ? (atrExp ? atrExpC : atrStbC) : na, title = "Candle volatility", offset = offs, force_overlay = true)
 
bgcolor(atrOn and outside ? (atrExp ? atrExpC : atrStbC) : na, title = "Candle volatility (pane)", offset = offs)
plotcandle(zOp, zHi, zLo, zCl, "Candles in σ", color = candleC, wickcolor = candleC, bordercolor = candleC, display = zShow and isCandle ? display.pane + display.price_scale : display.none)
plot(z, "Z-score", color = zCol, linewidth = zW, offset = offs, display = zShow and not isCandle ? display.all : display.none)
plot(na(emaV) ? na : 0.0, "EMA (zero)", color = emaNow, linewidth = emaW, linestyle = emaSt == S_DASH ? plot.linestyle_dashed : emaSt == S_DOT ? plot.linestyle_dotted : plot.linestyle_solid, offset = offs, display = emaShow ? display.pane : display.none)
 
h0 = hline(0, "Zero", color = color.new(#787B86, 50), linestyle = hline.style_dotted)
h1u = hline(b1Mult, "Level 1 upper", color = b1Up, linewidth = b1W, linestyle = b1St == S_DASH ? hline.style_dashed : b1St == S_DOT ? hline.style_dotted : hline.style_solid, display = b1Show ? display.all : display.none)
h1d = hline(-b1Mult, "Level 1 lower", color = b1Dn, linewidth = b1W, linestyle = b1St == S_DASH ? hline.style_dashed : b1St == S_DOT ? hline.style_dotted : hline.style_solid, display = b1Show ? display.all : display.none)
h2u = hline(b2Mult, "Level 2 upper", color = b2Up, linewidth = b2W, linestyle = b2St == S_DASH ? hline.style_dashed : b2St == S_DOT ? hline.style_dotted : hline.style_solid, display = b2Show ? display.all : display.none)
h2d = hline(-b2Mult, "Level 2 lower", color = b2Dn, linewidth = b2W, linestyle = b2St == S_DASH ? hline.style_dashed : b2St == S_DOT ? hline.style_dotted : hline.style_solid, display = b2Show ? display.all : display.none)
h3u = hline(b3Mult, "Level 3 upper", color = b3Up, linewidth = b3W, linestyle = b3St == S_DASH ? hline.style_dashed : b3St == S_DOT ? hline.style_dotted : hline.style_solid, display = b3Show ? display.all : display.none)
h3d = hline(-b3Mult, "Level 3 lower", color = b3Dn, linewidth = b3W, linestyle = b3St == S_DASH ? hline.style_dashed : b3St == S_DOT ? hline.style_dotted : hline.style_solid, display = b3Show ? display.all : display.none)
h4u = hline(b4Mult, "Level 4 upper", color = b4Up, linewidth = b4W, linestyle = b4St == S_DASH ? hline.style_dashed : b4St == S_DOT ? hline.style_dotted : hline.style_solid, display = b4Show ? display.all : display.none)
h4d = hline(-b4Mult, "Level 4 lower", color = b4Dn, linewidth = b4W, linestyle = b4St == S_DASH ? hline.style_dashed : b4St == S_DOT ? hline.style_dotted : hline.style_solid, display = b4Show ? display.all : display.none)
h5u = hline(b5Mult, "Level 5 upper", color = b5Up, linewidth = b5W, linestyle = b5St == S_DASH ? hline.style_dashed : b5St == S_DOT ? hline.style_dotted : hline.style_solid, display = b5Show ? display.all : display.none)
h5d = hline(-b5Mult, "Level 5 lower", color = b5Dn, linewidth = b5W, linestyle = b5St == S_DASH ? hline.style_dashed : b5St == S_DOT ? hline.style_dotted : hline.style_solid, display = b5Show ? display.all : display.none)
 
fill(h0, h1u, color = b1Show and b1Fill ? color.new(b1Up, fillTr) : na, title = "Fill 1 upper (pane)")
fill(h0, h1d, color = b1Show and b1Fill ? color.new(b1Dn, fillTr) : na, title = "Fill 1 lower (pane)")
fill(h0, h2u, color = b2Show and b2Fill ? color.new(b2Up, fillTr) : na, title = "Fill 2 upper (pane)")
fill(h0, h2d, color = b2Show and b2Fill ? color.new(b2Dn, fillTr) : na, title = "Fill 2 lower (pane)")
fill(h0, h3u, color = b3Show and b3Fill ? color.new(b3Up, fillTr) : na, title = "Fill 3 upper (pane)")
fill(h0, h3d, color = b3Show and b3Fill ? color.new(b3Dn, fillTr) : na, title = "Fill 3 lower (pane)")
fill(h0, h4u, color = b4Show and b4Fill ? color.new(b4Up, fillTr) : na, title = "Fill 4 upper (pane)")
fill(h0, h4d, color = b4Show and b4Fill ? color.new(b4Dn, fillTr) : na, title = "Fill 4 lower (pane)")
fill(h0, h5u, color = b5Show and b5Fill ? color.new(b5Up, fillTr) : na, title = "Fill 5 upper (pane)")
fill(h0, h5d, color = b5Show and b5Fill ? color.new(b5Dn, fillTr) : na, title = "Fill 5 lower (pane)")
 
plotshape(triUp ? yUp + 0.4 : na, "Re-entry from above (pane)", shape.triangledown, location.absolute, pRe ? reUpC : bandReC, size = size.small, offset = offs, display = reOn ? display.pane : display.none)
plotshape(triDn ? yDn - 0.4 : na, "Re-entry from below (pane)", shape.triangleup, location.absolute, pRe ? reDnC : bandReC, size = size.small, offset = offs, display = reOn ? display.pane : display.none)
plot((tDraw - emaV) / sdOk, "First touch level (pane)", color = tchCol, linewidth = tchW, style = plot.style_linebr, linestyle = tchSt == S_DASH ? plot.linestyle_dashed : tchSt == S_DOT ? plot.linestyle_dotted : plot.linestyle_solid, offset = offs, display = tchPane ? display.pane : display.none)
plotshape(clUp ? zHi : na, "Extreme volume above (pane)", shape.diamond, location.absolute, volUpC, size = size.tiny, offset = offs, display = volOn ? display.pane : display.none)
plotshape(clDn ? zLo : na, "Extreme volume below (pane)", shape.diamond, location.absolute, volDnC, size = size.tiny, offset = offs, display = volOn ? display.pane : display.none)
 
plot(slope, "EMA slope (σ)", color = #2962FF, display = slpOn ? display.status_line + display.data_window : display.none)
plot(vz, "Volume (z)", color = #FFD600, display = volOn ? display.status_line + display.data_window : display.none)
plot(atrRatio, "Short ÷ long ATR", color = #FF9800, display = atrOn ? display.status_line + display.data_window : display.none)
 
f_emaSlope(simple int eLen, simple float sWin, simple float sThr) =>
    float e  = ta.ema(close, eLen)
    float s  = math.sqrt(math.max(ta.ema(close * close, eLen) - e * e, 0.0))
    int   w  = math.min(math.max(1, math.round(eLen * sWin)), 4999)
    float sl = s > 0 ? (e - e[w]) / s : na
    int   eS = na(sl) ? 9 : sl > sThr ? 1 : sl < -sThr ? -1 : 0
    [eS, eS[1]]
 
f_tfN(simple string tf) =>
    tf == "" ? timeframe.period : tf
 
f_tfName(simple string tf) =>
    string t = f_tfN(tf)
    float  m = str.tonumber(t)
    na(m) ? t : m < 60 ? str.tostring(m) + "m" : m % 60 == 0 ? str.tostring(m / 60) + "h" : str.tostring(m) + "m"
 
[e1, e1p] = request.security(syminfo.tickerid, tf1, f_emaSlope(tEmaLen, slpWin, slpThr), lookahead = barmerge.lookahead_on)
[e2, e2p] = request.security(syminfo.tickerid, tf2, f_emaSlope(tEmaLen, slpWin, slpThr), lookahead = barmerge.lookahead_on)
[e3, e3p] = request.security(syminfo.tickerid, tf3, f_emaSlope(tEmaLen, slpWin, slpThr), lookahead = barmerge.lookahead_on)
 
f_row_bg(int _i) =>
    _i % 2 == 0 ? cCharcoal : cGraphite
 
get_table_pos(string _pos) =>
    switch _pos
        "top_left"    => position.top_left
        "top_right"   => position.top_right
        "bottom_left" => position.bottom_left
        => position.bottom_right
 
f_agree(bool v1, int x1, bool v2, int x2, bool v3, int x3) =>
    int ref = v1 ? x1 : v2 ? x2 : v3 ? x3 : 0
    ref != 0 and (not v1 or x1 == ref) and (not v2 or x2 == ref) and (not v3 or x3 == ref)
 
f_emTxt(bool low, int em) =>
    low ? "BELOW TF" : em == 9 ? "—" : em > 0 ? "▲ BULL" : em < 0 ? "▼ BEAR" : "FLAT"
 
f_emCol(bool low, int em) =>
    low ? cSteel : em == 1 ? cAccBuy : em == -1 ? cAccSell : em == 0 ? cSilver : cSteel
 
var table tb = table.new(get_table_pos(dbPos), 5, 7, bgcolor = cObsidian, border_width = 1, border_color = cGhost, frame_width = 1, frame_color = cGhost)
 
if tabOn and barstate.islast
    table.clear(tb, 0, 0, 4, 6)
    bool lw1 = timeframe.in_seconds(f_tfN(tf1)) < timeframe.in_seconds()
    bool lw2 = timeframe.in_seconds(f_tfN(tf2)) < timeframe.in_seconds()
    bool lw3 = timeframe.in_seconds(f_tfN(tf3)) < timeframe.in_seconds()
    bool s1  = timeframe.in_seconds(f_tfN(tf1)) == timeframe.in_seconds()
    bool s2  = timeframe.in_seconds(f_tfN(tf2)) == timeframe.in_seconds()
    bool s3  = timeframe.in_seconds(f_tfN(tf3)) == timeframe.in_seconds()
    int em1 = s1 ? e1 : e1p
    int em2 = s2 ? e2 : e2p
    int em3 = s3 ? e3 : e3p
    table.cell(tb, 0, 0, "REVERSAL Z-SCORE BANDS v2.3", text_color = cChrome, bgcolor = cObsidian, text_size = szHead, text_halign = text.align_left)
    table.merge_cells(tb, 0, 0, 4, 0)
    int r = 1
    if colEma
        table.cell(tb, 0, r, "EMA SLOPE", text_color = cSilver, bgcolor = cObsidian, text_size = szSect, text_halign = text.align_left)
        table.merge_cells(tb, 0, r, 1, r)
        table.cell(tb, 2, r, f_tfName(tf1), text_color = cSilver, bgcolor = cObsidian, text_size = szSect, text_halign = text.align_right)
        table.cell(tb, 3, r, f_tfName(tf2), text_color = cSilver, bgcolor = cObsidian, text_size = szSect, text_halign = text.align_right)
        table.cell(tb, 4, r, f_tfName(tf3), text_color = cSilver, bgcolor = cObsidian, text_size = szSect, text_halign = text.align_right)
        r += 1
        bool ok = f_agree(not lw1, em1 == 9 ? 0 : em1, not lw2, em2 == 9 ? 0 : em2, not lw3, em3 == 9 ? 0 : em3)
        color bg = f_row_bg(0)
        table.cell(tb, 0, r, ok ? "▪" : "▫", text_color = ok ? cChrome : cSteel, bgcolor = bg, text_size = szData, text_halign = text.align_center, tooltip = "▪ = the EMA is rising (or falling) on all computed timeframes")
        table.cell(tb, 1, r, "EMA " + str.tostring(tEmaLen), text_color = cSilver, bgcolor = bg, text_size = szData, text_halign = text.align_left)
        table.cell(tb, 2, r, f_emTxt(lw1, em1), text_color = f_emCol(lw1, em1), bgcolor = bg, text_size = szData, text_halign = text.align_right)
        table.cell(tb, 3, r, f_emTxt(lw2, em2), text_color = f_emCol(lw2, em2), bgcolor = bg, text_size = szData, text_halign = text.align_right)
        table.cell(tb, 4, r, f_emTxt(lw3, em3), text_color = f_emCol(lw3, em3), bgcolor = bg, text_size = szData, text_halign = text.align_right)
        r += 1
    if atdTab
        table.cell(tb, 0, r, "VOLATILITY", text_color = cSilver, bgcolor = cObsidian, text_size = szSect, text_halign = text.align_left)
        table.merge_cells(tb, 0, r, 1, r)
        table.cell(tb, 2, r, "──────", text_color = cGhost, bgcolor = cObsidian, text_size = szSect, text_halign = text.align_right)
        table.merge_cells(tb, 2, r, 4, r)
        r += 1
        bool atdOk = not na(atdRatio) and atdRatio >= atdMin
        color bg = f_row_bg(0)
        table.cell(tb, 0, r, atdOk ? "▪" : "▫", text_color = atdOk ? cChrome : cSteel, bgcolor = bg, text_size = szData, text_halign = text.align_center, tooltip = "▪ = ATR ÷ day mean ≥ " + str.tostring(atdMin))
        table.cell(tb, 1, r, "ATR ÷ DAY", text_color = cSilver, bgcolor = bg, text_size = szData, text_halign = text.align_left)
        table.cell(tb, 2, r, na(atdRatio) ? "—" : str.tostring(100.0 * atdRatio, "#") + " %", text_color = atdOk ? cChrome : cSteel, bgcolor = bg, text_size = szData, text_halign = text.align_right)
        table.merge_cells(tb, 2, r, 3, r)
        table.cell(tb, 4, r, na(atdRatio) ? "NEEDS " + str.tostring(dayLen) + " BARS" : atdOk ? "OK" : "LOW", text_color = atdOk ? cChrome : cSteel, bgcolor = bg, text_size = szData, text_halign = text.align_right)
 
var array<line>  liqLn = array.new<line>()
var array<label> liqLb = array.new<label>()
 
if barstate.islast
    while array.size(liqLn) > 0
        line.delete(array.pop(liqLn))
    while array.size(liqLb) > 0
        label.delete(array.pop(liqLb))
    int ext = 12 * timeframe.in_seconds() * 1000
    array<float>  lv = array.from(pdh, pdl, pwh, pwl, pmh, pml)
    array<string> nm = array.from("PDH", "PDL", "PWH", "PWL", "PMH", "PML")
    array<float>  zs = array.new<float>()
    array<int>    ix = array.new<int>()
    for i = 0 to 5
        float v  = array.get(lv, i)
        color c  = i < 2 ? liqDC : i < 4 ? liqWC : liqMC
        int   t0 = i < 2 ? dT : i < 4 ? wT : mT
        bool  on = i < 2 ? liqDOn : i < 4 ? liqWOn : liqMOn
        float zv = (v - emaV) / sdOk
        string zt = na(zv) ? "" : (zv >= 0 ? "+" : "−") + str.tostring(math.abs(zv), "0.0") + "σ"
        if on and not na(v)
            if liqChart
                array.push(liqLn, line.new(na(t0) ? time : t0, v, time + ext, v, xloc = xloc.bar_time, color = c, style = line.style_dotted, width = 1, force_overlay = true))
                array.push(liqLb, label.new(time + ext, v, array.get(nm, i) + " " + str.tostring(v, format.mintick) + " · " + zt, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(#000000, 100), textcolor = c, size = size.small, force_overlay = true))
            if liqPane and not na(zv)
                int x0 = bar_index + 1 + 5 * int(math.floor(i / 2))
                array.push(liqLn, line.new(x0, zv, x0 + 4, zv, color = c, style = line.style_solid, width = 2))
                array.push(zs, zv)
                array.push(ix, i)
    int m = array.size(zs)
    if m > 1
        for a = 0 to m - 2
            for b = a + 1 to m - 1
                if array.get(zs, b) < array.get(zs, a)
                    float tz = array.get(zs, a)
                    array.set(zs, a, array.get(zs, b))
                    array.set(zs, b, tz)
                    int ti = array.get(ix, a)
                    array.set(ix, a, array.get(ix, b))
                    array.set(ix, b, ti)
    if m > 0
        string txt  = ""
        float  ySum = 0.0
        int    yN   = 0
        color  c0   = na
        float  prev = na
        for k = 0 to m - 1
            float  zk    = array.get(zs, k)
            int    ik    = array.get(ix, k)
            string piece = array.get(nm, ik) + " " + (zk >= 0 ? "+" : "−") + str.tostring(math.abs(zk), "0.0") + "σ"
            if not na(prev) and zk - prev < 0.25
                txt  := txt + " · " + piece
                ySum += zk
                yN   += 1
            else
                if txt != ""
                    array.push(liqLb, label.new(bar_index + 17, ySum / yN, txt, style = label.style_label_left, color = color.new(#000000, 100), textcolor = c0, size = size.small))
                txt  := piece
                ySum := zk
                yN   := 1
                c0   := ik < 2 ? liqDC : ik < 4 ? liqWC : liqMC
            prev := zk
        if txt != ""
            array.push(liqLb, label.new(bar_index + 17, ySum / yN, txt, style = label.style_label_left, color = color.new(#000000, 100), textcolor = c0, size = size.small))
 
alertcondition(reUp, "Re-entry below +kσ", "Reversal Z-Score Bands: close back below the +kσ band")
alertcondition(reDn, "Re-entry above −kσ", "Reversal Z-Score Bands: close back above the −kσ band")
alertcondition(clUp, "Abnormal volume beyond +kσ", "Reversal Z-Score Bands: abnormal volume with the high beyond +kσ")
alertcondition(clDn, "Abnormal volume beyond −kσ", "Reversal Z-Score Bands: abnormal volume with the low beyond −kσ")

← 返回列表