本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Uncle_the_shooter
//@version=6
indicator('Structure Break Pressure Oscillator', shorttitle = 'SBPO', overlay = false, precision = 1, max_labels_count = 500)
// Main
grpM = '1. Main'
preset = input.string('Standard', 'Structure scale profile', options = ['Fast', 'Standard', 'Slow', 'Custom'], group = grpM, tooltip = 'Defines how large the price swings taken into account are. The indicator tracks highs and lows on 6 scales at once – from minor swings to the main structure – and measures which side breaks them more often and with more force.\n\n• Fast (3–30): 1–5 min charts, scalping\n• Standard (5–50): most timeframes\n• Slow (10–100): 4H and higher, swing trading\n• Custom: scales set in the "Custom scales" section\n\nThe scale number is how many bars on each side must be lower (for a high) or higher (for a low).\nExample: a scale-20 high is the highest high among the 20 bars before it and the 20 bars after it. The indicator registers it 20 bars later – once it is confirmed – so historical values never change.')
// Signals
grpS = '2. Signals (ChoCh markers)'
markerMinLen = input.int(10, 'Show ChoCh from scale', minval = 1, group = grpS, tooltip = 'A triangle marks a ChoCh (Change of Character): price breaks a high during a downtrend, or a low during an uptrend – a potential start of a reversal.\n\nMarkers are shown only for scales at or above this value.\nExample: with 10 on the Standard profile, a ChoCh on scale 5 produces no marker, while scales 10, 15, 20, 30 and 50 do.\n\nSmaller scales still contribute to the SBPO line; they are excluded from signals only because they are noisy.')
minStrength = input.float(0.0, 'Min. signal strength (×)', minval = 0.0, step = 0.1, group = grpS, tooltip = 'Hides weak signals. Strength compares a ChoCh with the typical break on this chart:\n• 1.0× – an average break\n• 2.0× – twice as strong (larger swing, larger scale, close far beyond the level)\n\nExample: at 1.5, markers and alerts appear only for ChoCh events with strength of 1.5× or more.\n0 = show all.')
markerSide = input.bool(false, 'Counter-dominance signals only', group = grpS, tooltip = 'Shows only signals that go against the prevailing side, i.e. potential reversals.\n\nExample: a bullish marker appears only if SBPO was below zero (sellers in control). A bullish ChoCh with SBPO above zero is skipped. The same applies in reverse to bearish markers.')
showLbl = input.bool(true, 'Marker labels', group = grpS, tooltip = 'Text next to each marker.\nExample "P20,30 / 1.8×": the ChoCh occurred on scales 20 and 30, with a strength of 1.8× the typical break.')
// Table and display
grpT = '3. Table and display'
showTbl = input.bool(true, 'Status table', group = grpT, tooltip = 'Table with the current readings. Hover over a row to see its explanation.')
tblSizeS = input.string('Normal', 'Table text size', options = ['Tiny', 'Small', 'Normal', 'Large'], group = grpT)
tblPosS = input.string('Top right', 'Table position', options = ['Top right', 'Bottom right', 'Top left', 'Bottom left'], group = grpT)
showEff = input.bool(true, 'Efficiency line', group = grpT, tooltip = 'A 0–100 line showing whether breaks are one-sided:\n• 80–100 – nearly all in the same direction, a clean trend\n• 35–65 – breaks in both directions, with a slight edge for one side\n• 0–35 – as many up as down, no direction\n\nThe line does not show direction – SBPO does.')
showBg = input.bool(true, 'Trend background', group = grpT, tooltip = 'A background in the bull or bear color marks a trend. It appears when all of the following hold:\n• breaks are mostly one-sided (efficiency above the threshold in the "Advanced" section)\n• the market is active rather than idle\n• SBPO is on the same side of zero\n\nNo background = no clear trend.')
sigLen = input.int(0, 'EMA line (0 = off)', minval = 0, group = grpT, tooltip = 'A smoothed SBPO line – an EMA over the given number of bars. It uses the bull color above zero and the bear color below. It shows which side is in control without the minor fluctuations of the main line.\n\nExample: 10 = an average of roughly the last 10 bars. Higher values give a smoother, slower line.\n0 = off.')
showGap = input.bool(true, 'Mark gaps', group = grpT, tooltip = 'A dot on the zero line marks a gap: the bar opened above the previous high or below the previous low, leaving an empty area on the chart.\nExample: an opening gap at the start of an exchange session.')
colorBars = input.bool(true, 'Color bars by SBPO', group = grpT, tooltip = 'Colors price bars by the SBPO value – a smooth transition from the bear color (−100) to the bull color (+100).')
markerLvl = input.float(80.0, 'Marker height', minval = 0.0, step = 5.0, group = grpT, tooltip = 'Vertical position of the markers in the pane: bullish at −value, bearish at +value.\nExample: 100 = at the edges of the −100…+100 range. Lower it if labels extend beyond the pane.')
lblSizeS = input.string('Small', 'Signal label size', options = ['Tiny', 'Small', 'Normal'], group = grpT)
fillMode = input.string('Gradient', 'SBPO fill', options = ['Gradient', 'Columns', 'None'], group = grpT, tooltip = '• Gradient – fill intensity increases with distance from zero\n• Columns – classic histogram\n• None – line only')
fillOpac = input.int(100, 'Gradient opacity (%)', minval = 0, maxval = 100, group = grpT, tooltip = 'Fill opacity at ±100. It fades automatically toward zero.\nExample: 50 = the fill is half transparent at ±100.')
showLvls = input.bool(true, 'Dominance levels ±', inline = 'lv', group = grpT)
lvlVal = input.float(50.0, '', minval = 1.0, maxval = 99.0, step = 5.0, inline = 'lv', group = grpT, tooltip = 'Reference lines at +/− this value.\nExample: at 50, the table describes SBPO above +50 as "strong bull dominance" and below −50 as "strong bear dominance".\nThis is a guideline, not a signal.')
colBull = input.color(color.rgb(6, 162, 47), 'Colors: bull / bear / efficiency', inline = 'c', group = grpT)
colBear = input.color(color.rgb(207, 23, 23), '', inline = 'c', group = grpT)
colEff = input.color(color.gray, '', inline = 'c', group = grpT)
colZero = input.color(color.new(color.gray, 50), 'Zero line and gap color', group = grpT)
// Advanced
grpA = '4. Advanced'
tau = input.float(30.0, 'Memory (bars)', minval = 1.0, step = 1.0, group = grpA, tooltip = 'How long a break keeps influencing SBPO. The influence fades gradually rather than disappearing at once.\n\nExample for 30:\n• after 30 bars about 1/3 of the influence remains\n• after 60 bars – about 1/7\n• after 90 bars – about 1/20\n\nLower values = the line reacts faster and switches sides more often. Higher values = a calmer but slower line.')
effTrend = input.float(65.0, 'Trend background threshold (efficiency)', minval = 0, maxval = 100, group = grpA, tooltip = 'Efficiency level from which the background marks a trend.\n\nExample: at 65 the background appears when about 4/5 of the points from recent breaks belong to one side. At 80, about 9/10 are required.\n\nHigher values = the background appears less often, only in pronounced trends.')
gapOn = input.bool(true, 'Ignore levels skipped by a gap', group = grpA, tooltip = 'When price jumps over a high or low with a gap, the break earns no points and no ChoCh signal, because no trading took place at that level. The structure direction is still updated.\n\nExample: a stock closes at 100 with a high at 102, and the next session opens at 105. The 102 high was skipped – no points.\n\nUseful for stocks and futures. Gaps are rare on forex and crypto.')
gapMute = input.int(0, 'Mute breaks after a gap (bars)', minval = 0, group = grpA, tooltip = 'Ignores all breaks for the given number of bars, counting from the gap bar. Useful for volatile session opens.\n\nExample: 3 = the gap bar and the next two bars produce no points or signals.\n0 = off.')
useVol = input.bool(false, 'Use volume', group = grpA, tooltip = 'Breaks on high volume earn more points, breaks on low volume fewer.\n\nExample: a bar with 2× average volume earns 2× the points (up to 3×), and a bar with half the average volume earns half.\n\nDisable on forex and CFDs, where volume data can be unreliable.')
// Custom scales
grpP = '5. Custom scales ("Custom" profile)'
bool custom = preset == 'Custom'
cEn1 = input.bool(true, 'Scale 1', inline = 'l1', group = grpP, active = custom)
cLen1 = input.int(5, '', minval = 1, inline = 'l1', group = grpP, active = custom, tooltip = 'Active only with the "Custom" profile. An unchecked scale is ignored entirely.\n\nExample: 5, 10, 20, 40, 80, 160 – from minor swings to very large ones. Values do not need to be in ascending order.')
cEn2 = input.bool(true, 'Scale 2', inline = 'l2', group = grpP, active = custom)
cLen2 = input.int(10, '', minval = 1, inline = 'l2', group = grpP, active = custom)
cEn3 = input.bool(true, 'Scale 3', inline = 'l3', group = grpP, active = custom)
cLen3 = input.int(15, '', minval = 1, inline = 'l3', group = grpP, active = custom)
cEn4 = input.bool(true, 'Scale 4', inline = 'l4', group = grpP, active = custom)
cLen4 = input.int(20, '', minval = 1, inline = 'l4', group = grpP, active = custom)
cEn5 = input.bool(true, 'Scale 5', inline = 'l5', group = grpP, active = custom)
cLen5 = input.int(30, '', minval = 1, inline = 'l5', group = grpP, active = custom)
cEn6 = input.bool(true, 'Scale 6', inline = 'l6', group = grpP, active = custom)
cLen6 = input.int(50, '', minval = 1, inline = 'l6', group = grpP, active = custom)
// Fixed model parameters
const int MAX_PENDING = 20 // unbroken levels kept per scale and side; oldest evicted first
const int ATR_LEN = 14 // ATR period (high−low average, gap-free)
const float SWING_CAP = 5.0 // swing factor clamp: 0.25 … SWING_CAP (in ATR)
const float BREAK_CAP = 2.0 // break factor: 1 + min(close distance beyond level in ATR, BREAK_CAP)
const float VOL_CAP = 3.0 // relative volume clamp: 0.25 … VOL_CAP
const int VOL_LEN = 20 // volume SMA period
const float CHOCH_BONUS = 1.5 // score multiplier for ChoCh vs BoS
const float CHOCH_RESET = 0.5 // max share of the opposite accumulation removed on ChoCh
const float GAP_MIN = 0.1 // minimum gap size in ATR
const int NORM_LEN = 300 // window for RMS normalization and activity average
const float NORM_SCALE = 1.5 // tanh scale: higher = ±100 reached less often
const float ACT_TREND = 0.5 // minimum activity required for the trend regime
// Scale lengths
int len1 = preset == 'Fast' ? 3 : preset == 'Standard' ? 5 : preset == 'Slow' ? 10 : cLen1
int len2 = preset == 'Fast' ? 5 : preset == 'Standard' ? 10 : preset == 'Slow' ? 20 : cLen2
int len3 = preset == 'Fast' ? 8 : preset == 'Standard' ? 15 : preset == 'Slow' ? 30 : cLen3
int len4 = preset == 'Fast' ? 12 : preset == 'Standard' ? 20 : preset == 'Slow' ? 50 : cLen4
int len5 = preset == 'Fast' ? 20 : preset == 'Standard' ? 30 : preset == 'Slow' ? 75 : cLen5
int len6 = preset == 'Fast' ? 30 : preset == 'Standard' ? 50 : preset == 'Slow' ? 100 : cLen6
bool en1 = custom ? cEn1 : true
bool en2 = custom ? cEn2 : true
bool en3 = custom ? cEn3 : true
bool en4 = custom ? cEn4 : true
bool en5 = custom ? cEn5 : true
bool en6 = custom ? cEn6 : true
// Longest enabled scale: reference for the ChoCh reset ratio and the signal length fallback.
int maxEnLen = math.max(en1 ? len1 : 0, en2 ? len2 : 0, en3 ? len3 : 0, en4 ? len4 : 0, en5 ? len5 : 0, en6 ? len6 : 0)
array<int> lensArr = array.from(len1, len2, len3, len4, len5, len6)
f_lenTxt(bool e, int l) =>
e ? str.tostring(l) : '–'
string lensTxt = f_lenTxt(en1, len1) + '·' + f_lenTxt(en2, len2) + '·' + f_lenTxt(en3, len3) + '·' + f_lenTxt(en4, len4) + '·' + f_lenTxt(en5, len5) + '·' + f_lenTxt(en6, len6)
// Helpers
// tanh with input clamping to avoid exp() overflow.
f_tanh(float x) =>
float xc = math.max(math.min(x, 20.0), -20.0)
float e = math.exp(2.0 * xc)
(e - 1.0) / (e + 1.0)
// Linear scale weight: a length-50 break weighs 10× a length-5 break.
f_weight(int len) =>
len / 5.0
// Score of a single structure break. All distances are expressed in ATR units.
f_score(float brkDist, float swingSize, float atrv, float rvol, float w, bool isChoch) =>
float a = math.max(atrv, syminfo.mintick)
float swingF = na(swingSize) ? 1.0 : math.min(math.max(swingSize / a, 0.25), SWING_CAP)
float brkF = 1.0 + math.min(math.max(brkDist, 0.0) / a, BREAK_CAP)
float volF = useVol ? rvol : 1.0
float chF = isChoch ? CHOCH_BONUS : 1.0
w * swingF * brkF * volF * chF
// Returns [length, value] of the longest scale with a positive value.
// Disabled or inactive scales must be passed as 0. Ties on equal lengths resolve to the larger value.
f_longest(array<int> lens, array<float> vals) =>
int bestLen = 0
float bestVal = 0.0
for i = 0 to array.size(lens) - 1
float v = array.get(vals, i)
int l = array.get(lens, i)
if v > 0
if l > bestLen
bestLen := l
bestVal := v
else if l == bestLen
bestVal := math.max(bestVal, v)
[bestLen, bestVal]
// Returns [length, value] of the scale with the highest positive value.
// Disabled or inactive scales must be passed as 0. Ties resolve to the longer scale.
f_best(array<int> lens, array<float> vals) =>
int bestLen = 0
float bestVal = 0.0
for i = 0 to array.size(lens) - 1
float v = array.get(vals, i)
int l = array.get(lens, i)
if v > bestVal or (v > 0 and v == bestVal and l > bestLen)
bestLen := l
bestVal := v
[bestLen, bestVal]
// Structure tracking for one pivot length. Each call site keeps its own `var` state.
// Returns the best up/down break score on the current bar and ChoCh flags for this scale.
f_struct(int len, float w, float atrv, float rvol, bool isGap, float gLo, float gHi, bool mute) =>
// Pending (unbroken) levels with per-level metadata, kept index-aligned:
// *Ext – running extreme on the opposite side since the pivot bar (correction depth)
// *Opp – last confirmed opposite pivot before this one (origin of the building impulse)
var array<float> hiLvl = array.new_float()
var array<float> hiExt = array.new_float()
var array<float> hiOpp = array.new_float()
var array<float> loLvl = array.new_float()
var array<float> loExt = array.new_float()
var array<float> loOpp = array.new_float()
var float lastPH = na
var float lastPL = na
var int dir = 0
float ph = ta.pivothigh(high, len, len)
float pl = ta.pivotlow(low, len, len)
// Extremes from the pivot bar through the current bar (pivot + len confirmation bars).
float lowSincePiv = ta.lowest(low, len + 1)
float highSincePiv = ta.highest(high, len + 1)
// Update correction depth of already pending levels with the current bar.
// Must run before new pivots are pushed: their initial extreme already includes this bar.
int nHe = array.size(hiExt)
if nHe > 0
for i = 0 to nHe - 1
array.set(hiExt, i, math.min(array.get(hiExt, i), low))
int nLe = array.size(loExt)
if nLe > 0
for i = 0 to nLe - 1
array.set(loExt, i, math.max(array.get(loExt, i), high))
// All pivots share the same confirmation lag, so lastPL/lastPH always precede the new pivot in time.
if not na(ph)
array.push(hiLvl, ph)
array.push(hiExt, lowSincePiv)
array.push(hiOpp, lastPL)
lastPH := ph
if array.size(hiLvl) > MAX_PENDING
array.shift(hiLvl)
array.shift(hiExt)
array.shift(hiOpp)
if not na(pl)
array.push(loLvl, pl)
array.push(loExt, highSincePiv)
array.push(loOpp, lastPH)
lastPL := pl
if array.size(loLvl) > MAX_PENDING
array.shift(loLvl)
array.shift(loExt)
array.shift(loOpp)
int prevDir = dir
float upScore = 0.0
float dnScore = 0.0
bool upBrk = false
bool dnBrk = false
bool upSilent = false
bool dnSilent = false
// Iterate backwards so removals do not shift unvisited indices.
int nH = array.size(hiLvl)
if nH > 0
for i = nH - 1 to 0
float lvl = array.get(hiLvl, i)
if close > lvl
bool jumped = mute or (isGap and lvl > gLo and lvl <= gHi)
if jumped
upSilent := true
else
// ChoCh: depth of the move being reclaimed. BoS: impulse that built the level;
// falls back to depth when no opposite pivot exists yet.
bool ch = prevDir == -1
float opp = array.get(hiOpp, i)
float depth = lvl - array.get(hiExt, i)
float swing = ch or na(opp) ? depth : math.abs(lvl - opp)
float s = f_score(close - lvl, swing, atrv, rvol, w, ch)
upScore := math.max(upScore, s)
upBrk := true
array.remove(hiLvl, i)
array.remove(hiExt, i)
array.remove(hiOpp, i)
int nL = array.size(loLvl)
if nL > 0
for i = nL - 1 to 0
float lvl = array.get(loLvl, i)
if close < lvl
bool jumped = mute or (isGap and lvl >= gLo and lvl < gHi)
if jumped
dnSilent := true
else
bool ch = prevDir == 1
float opp = array.get(loOpp, i)
float depth = array.get(loExt, i) - lvl
float swing = ch or na(opp) ? depth : math.abs(opp - lvl)
float s = f_score(lvl - close, swing, atrv, rvol, w, ch)
dnScore := math.max(dnScore, s)
dnBrk := true
array.remove(loLvl, i)
array.remove(loExt, i)
array.remove(loOpp, i)
bool upChoch = upBrk and prevDir == -1
bool dnChoch = dnBrk and prevDir == 1
// Direction update. Scored breaks take precedence; silent (gap/muted) breaks only update direction.
if upBrk and dnBrk
dir := upScore >= dnScore ? 1 : -1
else if upBrk
dir := 1
else if dnBrk
dir := -1
else if upSilent and not dnSilent
dir := 1
else if dnSilent and not upSilent
dir := -1
[upScore, dnScore, upChoch, dnChoch]
// Opposite-side reduction on ChoCh, scaled by the ChoCh scale length relative to the longest enabled scale.
// Applied once per bar from the longest ChoCh scale only, so reductions never compound across scales.
f_resetMult(int lCh, int lMax) =>
lCh > 0 and lMax > 0 ? 1.0 - CHOCH_RESET * float(lCh) / float(lMax) : 1.0
f_addLen(string s, bool cond, int len) =>
cond ? (s == '' ? str.tostring(len) : s + ',' + str.tostring(len)) : s
// Core
// Gap-free ATR: average high−low range, so session gaps do not inflate volatility.
float atrv = ta.rma(high - low, ATR_LEN)
float volSma = ta.sma(volume, VOL_LEN)
float rvol = na(volume) or na(volSma) or volSma <= 0 ? 1.0 : math.max(math.min(volume / volSma, VOL_CAP), 0.25)
// Classic gap: candle ranges do not overlap. Detection is independent of the level filter,
// so post-gap muting and gap markers work with the filter disabled.
float minGap = GAP_MIN * nz(atrv[1], atrv)
bool gapUp = not na(high[1]) and low > high[1] and low - high[1] >= minGap
bool gapDn = not na(low[1]) and high < low[1] and low[1] - high >= minGap
bool gapAny = gapUp or gapDn
bool isGap = gapOn and gapAny
// Empty price area: gapUp → high[1]…low, gapDn → high…low[1]
float gLo = gapUp ? high[1] : gapDn ? high : na
float gHi = gapUp ? low : gapDn ? low[1] : na
int bsg = ta.barssince(gapAny)
bool mute = gapMute > 0 and not na(bsg) and bsg < gapMute
float w1 = f_weight(len1)
float w2 = f_weight(len2)
float w3 = f_weight(len3)
float w4 = f_weight(len4)
float w5 = f_weight(len5)
float w6 = f_weight(len6)
[u1, d1, uc1, dc1] = f_struct(len1, w1, atrv, rvol, isGap, gLo, gHi, mute)
[u2, d2, uc2, dc2] = f_struct(len2, w2, atrv, rvol, isGap, gLo, gHi, mute)
[u3, d3, uc3, dc3] = f_struct(len3, w3, atrv, rvol, isGap, gLo, gHi, mute)
[u4, d4, uc4, dc4] = f_struct(len4, w4, atrv, rvol, isGap, gLo, gHi, mute)
[u5, d5, uc5, dc5] = f_struct(len5, w5, atrv, rvol, isGap, gLo, gHi, mute)
[u6, d6, uc6, dc6] = f_struct(len6, w6, atrv, rvol, isGap, gLo, gHi, mute)
// One score per bar and direction: the maximum across scales. A pivot of length N is also a pivot of every
// shorter length, so summing would count the same break several times. Scale rank enters through the weight.
[upLen, upSum] = f_best(lensArr, array.from(en1 ? u1 : 0.0, en2 ? u2 : 0.0, en3 ? u3 : 0.0, en4 ? u4 : 0.0, en5 ? u5 : 0.0, en6 ? u6 : 0.0))
[dnLen, dnSum] = f_best(lensArr, array.from(en1 ? d1 : 0.0, en2 ? d2 : 0.0, en3 ? d3 : 0.0, en4 ? d4 : 0.0, en5 ? d5 : 0.0, en6 ? d6 : 0.0))
float decay = math.exp(-1.0 / tau)
var float bull = 0.0
var float bear = 0.0
bull *= decay
bear *= decay
// ChoCh erodes the opposite side's accumulation before the current bar's points are added.
// Flags (not scores) select the scale, so the reset does not depend on score magnitude.
[upChLen, upChFlag] = f_longest(lensArr, array.from(en1 and uc1 ? 1.0 : 0.0, en2 and uc2 ? 1.0 : 0.0, en3 and uc3 ? 1.0 : 0.0, en4 and uc4 ? 1.0 : 0.0, en5 and uc5 ? 1.0 : 0.0, en6 and uc6 ? 1.0 : 0.0))
[dnChLen, dnChFlag] = f_longest(lensArr, array.from(en1 and dc1 ? 1.0 : 0.0, en2 and dc2 ? 1.0 : 0.0, en3 and dc3 ? 1.0 : 0.0, en4 and dc4 ? 1.0 : 0.0, en5 and dc5 ? 1.0 : 0.0, en6 and dc6 ? 1.0 : 0.0))
bear *= f_resetMult(upChLen, maxEnLen)
bull *= f_resetMult(dnChLen, maxEnLen)
bull += upSum
bear += dnSum
// Regime accumulators without ChoCh reset. The reset suppresses one side by design, which would bias
// efficiency upwards; regime metrics therefore use the raw decayed sums.
var float bullR = 0.0
var float bearR = 0.0
bullR := bullR * decay + upSum
bearR := bearR * decay + dnSum
float netR = bullR - bearR
float grossR = bullR + bearR
float net = bull - bear
// Normalization: RMS of net over the window, squashed with tanh to −100…+100.
float rms = math.sqrt(ta.sma(net * net, NORM_LEN))
float osc = na(rms) ? na : rms > 0 ? 100.0 * f_tanh(net / (rms * NORM_SCALE)) : 0.0
float sigRaw = ta.ema(osc, math.max(sigLen, 1))
float sig = sigLen > 0 ? sigRaw : na
// Regime: efficiency = |netR| / grossR, activity = grossR relative to its average.
float grossAvg = ta.sma(grossR, NORM_LEN)
float activity = na(grossAvg) or grossAvg <= 0 ? na : grossR / grossAvg
float eff = grossR > 0 and not na(activity) and activity >= 0.1 ? 100.0 * math.abs(netR) / grossR : na
// Trend requires the raw break direction (netR) and the oscillator side (net) to agree.
// This keeps the background from contradicting the SBPO line right after a ChoCh reset.
bool trendBase = not na(eff) and eff >= effTrend and not na(activity) and activity >= ACT_TREND
bool trendUp = trendBase and netR > 0 and net > 0
bool trendDn = trendBase and netR < 0 and net < 0
bool isTrend = trendUp or trendDn
// Break strength
// Strength = score ÷ EMA of per-bar scores over recent break bars (~50 events).
// evRef is taken before the update so the current event does not dilute its own reference.
float evNow = math.max(upSum, dnSum)
var float evAvg = na
float evRef = na(evAvg) ? evNow : evAvg
if evNow > 0
evAvg := na(evAvg) ? evNow : evAvg + (evNow - evAvg) * 2.0 / 51.0
float upStr = evRef > 0 ? upSum / evRef : na
float dnStr = evRef > 0 ? dnSum / evRef : na
// ChoCh signals
// Length threshold with fallback to the longest enabled scale, so signals never disappear entirely.
int effMin = math.min(markerMinLen, maxEnLen)
bool q1 = en1 and len1 >= effMin
bool q2 = en2 and len2 >= effMin
bool q3 = en3 and len3 >= effMin
bool q4 = en4 and len4 >= effMin
bool q5 = en5 and len5 >= effMin
bool q6 = en6 and len6 >= effMin
bool upChochRaw = (q1 and uc1) or (q2 and uc2) or (q3 and uc3) or (q4 and uc4) or (q5 and uc5) or (q6 and uc6)
bool dnChochRaw = (q1 and dc1) or (q2 and dc2) or (q3 and dc3) or (q4 and dc4) or (q5 and dc5) or (q6 and dc6)
// Signal strength is restricted to qualifying ChoCh scales, consistent with the label contents.
[upSigLen, upSigVal] = f_best(lensArr, array.from(q1 and uc1 ? u1 : 0.0, q2 and uc2 ? u2 : 0.0, q3 and uc3 ? u3 : 0.0, q4 and uc4 ? u4 : 0.0, q5 and uc5 ? u5 : 0.0, q6 and uc6 ? u6 : 0.0))
[dnSigLen, dnSigVal] = f_best(lensArr, array.from(q1 and dc1 ? d1 : 0.0, q2 and dc2 ? d2 : 0.0, q3 and dc3 ? d3 : 0.0, q4 and dc4 ? d4 : 0.0, q5 and dc5 ? d5 : 0.0, q6 and dc6 ? d6 : 0.0))
float upChStr = evRef > 0 and upSigVal > 0 ? upSigVal / evRef : na
float dnChStr = evRef > 0 and dnSigVal > 0 ? dnSigVal / evRef : na
string upLens = f_addLen(f_addLen(f_addLen(f_addLen(f_addLen(f_addLen('', q1 and uc1, len1), q2 and uc2, len2), q3 and uc3, len3), q4 and uc4, len4), q5 and uc5, len5), q6 and uc6, len6)
string dnLens = f_addLen(f_addLen(f_addLen(f_addLen(f_addLen(f_addLen('', q1 and dc1, len1), q2 and dc2, len2), q3 and dc3, len3), q4 and dc4, len4), q5 and dc5, len5), q6 and dc6, len6)
// Signals on confirmed bars only: no intrabar markers or alerts that could vanish before the close.
bool upChochMark = barstate.isconfirmed and upChochRaw and (not markerSide or nz(osc[1]) < 0) and (minStrength <= 0 or nz(upChStr) >= minStrength)
bool dnChochMark = barstate.isconfirmed and dnChochRaw and (not markerSide or nz(osc[1]) > 0) and (minStrength <= 0 or nz(dnChStr) >= minStrength)
var string lastChTxt = '—'
var color lastChCol = chart.fg_color
if upChochMark
lastChTxt := '▲ bull · P' + upLens + ' · ' + str.tostring(upChStr, '0.0') + '×'
lastChCol := colBull
if dnChochMark
lastChTxt := '▼ bear · P' + dnLens + ' · ' + str.tostring(dnChStr, '0.0') + '×'
lastChCol := colBear
string lblSize = lblSizeS == 'Tiny' ? size.tiny : lblSizeS == 'Normal' ? size.normal : size.small
// Labels sit outside the markers (bull below, bear above) with transparent background to stay clear of the line.
if showLbl and upChochMark
label.new(bar_index, -markerLvl, 'P' + upLens + '\n' + str.tostring(upChStr, '0.0') + '×', yloc = yloc.price, style = label.style_label_up, color = color.new(colBull, 100), textcolor = colBull, size = lblSize, tooltip = 'Bullish ChoCh on scales: ' + upLens + '\nStrength: ' + str.tostring(upChStr, '0.0') + '× the typical break (strongest scale: ' + str.tostring(upSigLen) + ')')
if showLbl and dnChochMark
label.new(bar_index, markerLvl, 'P' + dnLens + '\n' + str.tostring(dnChStr, '0.0') + '×', yloc = yloc.price, style = label.style_label_down, color = color.new(colBear, 100), textcolor = colBear, size = lblSize, tooltip = 'Bearish ChoCh on scales: ' + dnLens + '\nStrength: ' + str.tostring(dnChStr, '0.0') + '× the typical break (strongest scale: ' + str.tostring(dnSigLen) + ')')
// Plots
color oscCol = color.from_gradient(nz(osc), -100, 100, colBear, colBull)
color sigCol = nz(sig) >= 0 ? colBull : colBear
hline(0, 'Zero', color = colZero, linestyle = hline.style_solid)
hline(lvlVal, 'Dominance level +', color = color.new(color.gray, 75), linestyle = hline.style_dotted, display = showLvls ? display.all : display.none)
hline(-lvlVal, 'Dominance level −', color = color.new(color.gray, 75), linestyle = hline.style_dotted, display = showLvls ? display.all : display.none)
// Fixed-scale gradient: full color at ±100, transparent at zero.
float oscV = nz(osc)
pPos = plot(math.max(oscV, 0.0), 'Fill +', display = display.none, editable = false)
pNeg = plot(math.min(oscV, 0.0), 'Fill −', display = display.none, editable = false)
pZero = plot(0.0, 'Fill zero', display = display.none, editable = false)
bool gradOn = fillMode == 'Gradient'
int fillT = 100 - fillOpac
fill(pPos, pZero, 100.0, 0.0, color.new(colBull, gradOn ? fillT : 100), color.new(colBull, 100), title = 'Bull gradient')
fill(pZero, pNeg, 0.0, -100.0, color.new(colBear, 100), color.new(colBear, gradOn ? fillT : 100), title = 'Bear gradient')
plot(fillMode == 'Columns' ? osc : na, 'SBPO columns', color = color.new(oscCol, 55), style = plot.style_columns)
plot(osc, 'SBPO (−100…+100)', color = oscCol, linewidth = 2)
plot(sig, 'EMA line', color = sigCol, linewidth = 1)
plot(showEff ? eff : na, 'Efficiency (0–100)', color = colEff, linewidth = 1)
plotshape(upChochMark ? -markerLvl : na, 'ChoCh Up', style = shape.triangleup, location = location.absolute, color = colBull, size = size.tiny)
plotshape(dnChochMark ? markerLvl : na, 'ChoCh Down', style = shape.triangledown, location = location.absolute, color = colBear, size = size.tiny)
plotshape(showGap and gapAny ? 0.0 : na, 'Gap', style = shape.circle, location = location.absolute, color = colZero, size = size.tiny)
bgcolor(showBg and isTrend ? color.new(trendUp ? colBull : colBear, 92) : na, title = 'Trend background')
barcolor(colorBars and not na(osc) ? oscCol : na)
// Data window values (hover over a bar).
plot(upStr, 'Bull break strength (× typical)', display = display.data_window)
plot(dnStr, 'Bear break strength (× typical)', display = display.data_window)
plot(activity, 'Activity (× average)', display = display.data_window)
plot(bull, 'Bull points (raw)', display = display.data_window)
plot(bear, 'Bear points (raw)', display = display.data_window)
// Table
string tblPos = tblPosS == 'Top right' ? position.top_right : tblPosS == 'Bottom right' ? position.bottom_right : tblPosS == 'Top left' ? position.top_left : position.bottom_left
string tblSize = tblSizeS == 'Tiny' ? size.tiny : tblSizeS == 'Small' ? size.small : tblSizeS == 'Large' ? size.large : size.normal
var table tbl = table.new(tblPos, 2, 6, bgcolor = color.new(chart.bg_color, 10), frame_color = color.new(color.gray, 60), frame_width = 1, border_color = color.new(color.gray, 80), border_width = 1)
// Row explanation is attached as a cell tooltip.
f_row(int r, string name, string val, color valCol, string tip) =>
table.cell(tbl, 0, r, name + ' ⓘ', text_color = chart.fg_color, text_size = tblSize, text_halign = text.align_left, tooltip = tip)
table.cell(tbl, 1, r, val, text_color = valCol, text_size = tblSize, text_halign = text.align_left, tooltip = tip)
if showTbl and barstate.islast
string oscTxt = na(osc) ? '—' : (osc > 0 ? '+' : '') + str.tostring(math.round(osc)) + (osc >= lvlVal ? ' strong bull dominance' : osc > 0 ? ' bull dominance' : osc <= -lvlVal ? ' strong bear dominance' : osc < 0 ? ' bear dominance' : ' balanced')
string effTxt = na(eff) ? '—' : str.tostring(math.round(eff)) + (eff >= effTrend ? ' one-sided' : eff <= 35 ? ' two-sided' : ' mixed')
string actTxt = na(activity) ? '—' : str.tostring(activity, '0.0') + '×' + (activity < 0.5 ? ' quiet market' : activity > 1.5 ? ' high activity' : ' normal')
string regTxt = trendUp ? 'UPTREND' : trendDn ? 'DOWNTREND' : 'no trend'
color regCol = trendUp ? colBull : trendDn ? colBear : chart.fg_color
table.cell(tbl, 0, 0, 'SBPO · ' + preset + ' (P ' + lensTxt + ')', text_color = chart.fg_color, text_size = tblSize, text_halign = text.align_left, tooltip = 'Structure Break Pressure Oscillator – shows whether buyers or sellers break highs and lows more often and with more force, across 6 scales at once.\nP = scales (high/low lengths) of the current profile.')
table.cell(tbl, 1, 0, 'Now', text_color = chart.fg_color, text_size = tblSize, text_halign = text.align_left, tooltip = 'Values from the latest bar.')
f_row(1, 'SBPO', oscTxt, oscCol, 'Which side is winning structure breaks, on a scale from −100 to +100:\n• above 0 – buyers in control, below 0 – sellers\n• above +' + str.tostring(lvlVal) + ' / below −' + str.tostring(lvlVal) + ' – clear dominance\n• a zero cross – control changes sides\n\nBreaks of larger swings weigh more, and older breaks gradually lose significance.')
f_row(2, 'Efficiency', effTxt, colEff, 'Whether breaks are one-sided (0–100):\n• ' + str.tostring(effTrend) + ' and above – one-sided, trending\n• 35–' + str.tostring(effTrend) + ' – mixed\n• below 35 – breaks in both directions\n\nDoes not show direction – SBPO does.')
f_row(3, 'Activity', actTxt, chart.fg_color, 'How many breaks are occurring compared with the typical level.\n\nExample: 2.0× = twice as many as usual, 0.3× = the market is nearly idle.\nBelow 0.5× the trend background does not appear.')
f_row(4, 'Trend', regTxt, regCol, 'A trend means that all of the following hold:\n• breaks are mostly one-sided\n• the market is active\n• SBPO is on the same side of zero\n\nWithout a trend, ChoCh signals are less reliable.')
f_row(5, 'Last ChoCh', lastChTxt, lastChCol, 'The most recent marker.\n\nExample "▲ bull · P20,30 · 1.8×": bullish ChoCh on scales 20 and 30, strength 1.8× the typical break.\nStrength: about 1× – average, above 1.5× – strong, above 2.5× – very strong.')
// Alerts
bool oscUp = ta.crossover(osc, 0)
bool oscDn = ta.crossunder(osc, 0)
alertcondition(barstate.isconfirmed and oscUp, 'SBPO crosses above zero', 'SBPO: control shifts to bulls, close {{close}}')
alertcondition(barstate.isconfirmed and oscDn, 'SBPO crosses below zero', 'SBPO: control shifts to bears, close {{close}}')
alertcondition(upChochMark, 'SBPO bullish ChoCh', 'SBPO: bullish ChoCh, close {{close}}')
alertcondition(dnChochMark, 'SBPO bearish ChoCh', 'SBPO: bearish ChoCh, close {{close}}')
alertcondition(barstate.isconfirmed and isTrend and not isTrend[1], 'SBPO trend start', 'SBPO: trend started (efficiency above threshold), close {{close}}')