本页源码来自 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("Confluence Dual Oscillator", overlay = false, precision = 1, max_labels_count = 500, max_lines_count = 500, max_bars_back = 500, explicit_plot_zorder = true)
// DESCRIPTION
// Two scores (−100..+100) built from the same four categories: Trend, Momentum, Volume and Structure.
// • SLOW score – trend direction (blocks by default).
// • FAST score – entry timing (line by default).
// Trend signals ◆ : direction from the slow score; entry from the fast score (Pullback mode) or a break of a level by the slow score (Breakout mode).
// Counter-trend signals ▲▼ : the fast score returns from the overbought / oversold zone.
// Divergences: price vs the fast score.
// CONSTANTS
const int BANDS = 10
const int NORM_LEN = 100
const float EQ_GAIN = 0.75
const float EMA_ZONE = 0.25
const float LR_ZONE = 0.5
// TOOLTIPS
// ① General
const string TT_W_TREND = "Trend – the direction and stability of price movement.\nSlow score: fast / slow EMA alignment, +DI / −DI dominance and the direction of the linear regression slope.\nFast score: distance of price from the fast EMA.\n\n↑ Higher weight: scores hold the trend direction longer and pullbacks move them less.\n↓ Lower weight: faster reaction to reversals, more frequent direction changes.\n0 = category excluded."
const string TT_W_MOM = "Momentum – strength and acceleration of the move.\nSlow score: price change over the last N bars.\nFast score: RSI and MACD histogram.\n\n↑ Higher weight: earlier signals, but more false ones in ranges.\n↓ Lower weight: smoother scores, later signals."
const string TT_W_VOL = "Volume – whether the price move is backed by capital flow.\nSlow score: longer-period Chaikin Money Flow and OBV relative to its average.\nFast score: shorter-period Chaikin Money Flow.\n\n↑ Higher weight: moves without volume produce weaker scores and fewer signals on hollow breakouts.\nWhether the category is used is set by 'Volume mode' in section ⑦."
const string TT_W_STR = "Structure – the sequence of swing highs and lows.\nSlow score: whether higher highs and lows (HH / HL) or lower ones (LH / LL) are forming, and where price sits relative to the last major swing. Price moving above the swing high or below the swing low (break of structure) shifts the score strongly.\nFast score: position of price within the most recent minor swing.\n\n↑ Higher weight: moves against market structure produce signals less often."
const string TT_CLOSE = "Signals, divergences and alerts appear only after the bar closes, so they never disappear intrabar.\nBlocks, line and table update in real time.\nDisabled: a signal may appear during the bar and disappear before it closes."
// ② Trend signals
const string TT_TSHOW = "Diamonds ◆ – entries in the direction of the slow score.\nDisabling hides the diamonds on the chart. Alerts are configured independently in section ⑪."
const string TT_TMODE = "Pullback: the trend is in place (slow score beyond the trend threshold), price pulls back (fast score drops below the pullback depth), then the pullback ends (fast score crosses back through the entry trigger). Long in an uptrend, Short in a downtrend.\nUsually an earlier entry at a better price, but no pullback means no signal.\n\nBreakout: signal when the slow score crosses the breakout level. Catches the start of a strong move, but the entry comes later."
const string TT_TCTX = "Pullback mode: how strong the slow score must be for the trend to count as in place. Long only above +value, Short only below −value.\n↑ Higher = only clear trends, fewer signals.\n↓ Lower = more signals, including in weak trends."
const string TT_PULL = "Pullback mode: how far the fast score must move against the trend to count as a pullback (Long: below −value, Short: above +value).\nEach pullback allows at most one signal.\n↑ Deeper = only clear pullbacks, fewer signals."
const string TT_TRIG = "Pullback mode: the level the fast score must cross back through for the pullback to count as finished (Long: up through +value, Short: down through −value).\n0 = cross back through zero.\n↑ Higher = confirmation by a stronger rebound, but a later entry."
const string TT_TLVL = "Breakout mode: the level the slow score must cross.\n↑ Higher = only strong moves, later entry.\n↓ Lower = earlier entry, but more false starts."
const string TT_REARM = "Breakout mode: after a Long signal, the next Long is allowed only once the slow score falls back to this level (Short mirrored). Prevents a series of signals while the score oscillates around the breakout level.\n0 = the score must return to zero."
const string TT_AGREE = "How many categories (Trend, Momentum, Volume, Structure) of the slow score must clearly point in the signal direction: up for Long, down for Short.\n1 = a single category is enough. 4 = all must agree.\nDisabled categories (weight 0 or volume off) are not counted – if only 3 are active, a setting of 4 behaves like 3.\n↑ More = fewer signals, confirmed by more categories."
const string TT_TADX = "Trend signals only when ADX is at or above the given level, i.e. the market shows clear trend strength."
const string TT_TOBOS = "Blocks a trend signal when the fast score is already in the zone on the signal side: Long while it is overbought, Short while it is oversold. Prevents entering an overextended move.\nThe zone level is set in section ③."
// ③ Counter-trend signals
const string TT_CSHOW = "Triangles ▲▼ – entries against the current move when the fast score returns from the overbought (Sell) or oversold (Buy) zone.\nDisabling hides the triangles, B / S labels and zones. Alerts are configured independently in section ⑪."
const string TT_OBOS = "Overbought / oversold level of the fast score (±). Also used for divergences and for the zone filter of trend signals.\n↑ Higher = only extreme readings, fewer signals.\n↓ Lower = more signals, including on ordinary pullbacks."
const string TT_CBARS = "How many consecutive bars the fast score must stay in the zone before leaving it produces a signal.\n1 = a single bar is enough.\nMore = signals only after prolonged overextension, which more often ends in a reversal."
const string TT_CFILT = "When to block counter-trend signals:\nSlow score: when the slow score is strong in the direction of the current move (Sell blocked in a strong uptrend, Buy in a strong downtrend).\nADX: when ADX is above the threshold, i.e. the market is trending.\nNone: no signals are blocked."
const string TT_CCTX = "'Slow score' filter: Sell is blocked when the slow score is above +value, Buy when it is below −value.\n↓ Lower = the filter blocks more signals."
const string TT_CADX = "'ADX' filter: signals pass only when ADX is below this value.\n↓ Lower = only clear ranges, fewer signals."
const string TT_FADED = "Show signals blocked by the filter in a faded color, to see what the filter removes.\nRight field: transparency of faded markers."
const string TT_DIVSIG = "How counter-trend signals are combined with divergences:\nIgnore: signals and divergences are independent.\nMark: when a signal and a divergence in the same direction occur close together, an additional B or S label appears.\nRequire: only divergence-confirmed signals (B / S) are shown on the chart."
const string TT_DIVWIN = "Maximum number of bars between a counter-trend signal and a divergence for them to count as one event (B / S).\nA divergence is usually confirmed a few bars after the signal – the label then appears on the confirmation bar."
const string TT_DIVBYP = "A divergence-confirmed signal (B / S) appears even when the filter blocked the plain signal. Divergences often form while the trend is still strong."
// ④ Divergences
const string TT_DIV = "Divergence between price and the fast score.\nBullish: price makes a lower low while the score makes a higher low.\nBearish: price makes a higher high while the score makes a lower high.\nIndicates a weakening move and a possible reversal.\nDisabling hides only the lines – B / S labels, alerts and the table keep working."
const string TT_DIVLB = "Number of bars on each side that must confirm a score high or low. Divergences appear with this delay, but do not change afterwards.\n↓ Fewer = faster, but more weak divergences."
const string TT_DIVGAP = "Left field: minimum number of bars between the two highs (lows) – rejects two ticks of the same peak.\nRight field: maximum – too large a value links peaks from different market phases."
const string TT_DIVPULL = "How many points the score must retrace between the two highs (lows) for them to count as separate waves.\n↑ More = only clear two-wave patterns."
const string TT_DIVDIFF = "Minimum score difference between the first and second high (low). A difference of a few points is noise, not a weakening move."
const string TT_DIVZONE = "Bullish: the first score low must be in the oversold zone.\nBearish: the first score high must be in the overbought zone."
const string TT_DIVCLN = "Between the two highs (lows) the score must not cross the divergence line. Rejects patterns interrupted by a move in between."
const string TT_DIVZERO = "Bullish: the second score low must be below zero.\nBearish: the second score high must be above zero.\nA divergence carries more weight while the move is still pronounced."
// ⑤–⑧ Components
const string TT_EMA = "Fast and slow EMA.\nFast score: distance of price from the fast EMA.\nSlow score: alignment only – fast EMA above the slow one (+) or below it (−). The score passes smoothly through zero at a crossover, and a spread wider than about 0.25 ATR does not increase it, since a wide EMA spread more often precedes a pullback than it confirms trend strength.\nShorter = trend detected sooner, but reverses more often."
const string TT_ATR = "ATR period used to measure price distances, making scores comparable across instruments and timeframes. Has little effect on signals."
const string TT_LR = "Number of bars used for the linear regression slope (slow score). Only the direction of the slope counts – steepness beyond about 0.5 ATR over the full window does not increase the score.\n↑ More = more stable direction, slower reaction to reversals."
const string TT_ADXLEN = "Period for +DI / −DI (slow score) and ADX (signal filters).\nShorter = faster reaction. Longer = more stable, but later."
const string TT_RSI = "RSI period (fast score).\nShorter = faster and more often extreme."
const string TT_MACD = "The MACD histogram (fast score) shows acceleration and deceleration of the move – often the first to signal fading momentum."
const string TT_ROC = "Number of bars used for price change (slow score).\n↑ More = measures the momentum of the whole wave, slower reaction."
const string TT_VOLMODE = "Auto: volume is used on instruments with real volume. It is skipped on Forex and CFDs, where volume usually reflects tick count rather than traded volume.\nAlways: used whenever the instrument reports any volume.\nOff: category excluded."
const string TT_CMF = "Chaikin Money Flow: whether bars close near their highs (accumulation) or lows (distribution), weighted by volume.\nLeft field: period for the fast score. Right field: for the slow score."
const string TT_OBV = "OBV relative to its average over this many bars (slow score): whether volume is flowing in faster than usual.\n↑ More = slower, more stable reaction."
const string TT_PIV = "Major swing (slow score): how many bars to the left and right must be lower than the high (higher than the low).\nA high or low is confirmed only after the 'right' number of bars and does not change afterwards.\n↑ More = only significant swings, slower structure."
const string TT_IPIV = "Minor swing (fast score): how many bars on each side confirm a high or low.\n↓ Fewer = faster, but noisier reaction."
const string TT_SMOOTH = "Score smoothing. 1 = none.\nLeft field: fast score. Right field: slow score.\n↑ More = fewer false signals, but all signals appear later."
// ⑨ Display
const string TT_BLK = "Which score the blocks display. The other one is drawn as a line.\nSlow on blocks: the blocks show trend direction and strength, the line shows entry timing.\nOverbought / oversold zones and divergences always refer to the fast score."
const string TT_LINE = "Line of the second score. Divergence lines connect highs and lows of the fast score."
const string TT_ZONE = "Highlighting of the fast score's overbought and oversold zones."
const string TT_DYNZ = "The zone is nearly invisible while the fast score is far from it and becomes more pronounced as the score approaches."
const string TT_FART = "Zone transparency while the fast score is far from it (100 = invisible)."
const string TT_INT = "Zone transparency while the fast score is inside it (0 = full color)."
const string TT_DIM = "Dim the blocks when categories point in different directions.\nFull color = categories agree. Faded = the score is driven by one or two categories.\nRight field: maximum dimming."
const string TT_LVL = "Zero line and trend signal levels (trend threshold in Pullback mode or breakout level in Breakout mode)."
const string TT_OBOSL = "Lines at the overbought and oversold zone boundaries."
const string TT_BARS = "Price bars colored like the highest lit block. When no block is lit – neutral color."
const string TT_TBL = "Table: category readings for both scores, agreement, ADX, last signal and last divergence.\nFields alongside: position and size."
const string TT_GLOW = "Glow on the price chart in the block color: below the bars when bulls dominate, above the bars when bears dominate. With a score near zero it stays on its current side."
const string TT_GATR = "ATR period for the glow width. Longer = more stable width."
const string TT_GWID = "Glow width as a multiple of ATR."
const string TT_GTR = "Left field: transparency at price. Right field: at the outer edge."
// ⑩ Colors
const string TT_PAL_BU = "Bullish block colors: from the block closest to zero (weak) to the highest one (strong)."
const string TT_PAL_BE = "Bearish block colors: from the block closest to zero (weak) to the lowest one (strong)."
// ⑪ Alerts
const string TT_ALERT = "Setup: on the chart choose Create alert → Condition: Confluence Dual Oscillator → 'Any alert() function call'. A single alert covers all signal types checked here.\nAlerts work regardless of whether signals are shown on the chart."
const string TT_ACON = "Counter-trend signals that passed the filter from section ③."
const string TT_ABS = "Divergence-confirmed counter-trend signals (B / S), including when 'Ignore' is selected in section ③."
// SETTINGS
grpW = "① General"
wTrend = input.float(1.0, "Weight: Trend", minval = 0, step = 0.25, group = grpW, tooltip = TT_W_TREND)
wMom = input.float(1.0, "Weight: Momentum", minval = 0, step = 0.25, group = grpW, tooltip = TT_W_MOM)
wVol = input.float(1.0, "Weight: Volume", minval = 0, step = 0.25, group = grpW, tooltip = TT_W_VOL)
wStr = input.float(1.0, "Weight: Structure", minval = 0, step = 0.25, group = grpW, tooltip = TT_W_STR)
onClose = input.bool(true, "Signals on bar close only", group = grpW, tooltip = TT_CLOSE)
grpS = "② Trend signals ◆"
showTrend = input.bool(true, "Show trend signals ◆", group = grpS, tooltip = TT_TSHOW)
trendMode = input.string("Breakout", "Mode", options = ["Pullback", "Breakout"], group = grpS, tooltip = TT_TMODE)
bool inPull = trendMode == "Pullback"
ctxTrend = input.float(30, "Pullback: trend threshold – slow (±)", minval = 0, maxval = 100, group = grpS, tooltip = TT_TCTX, active = inPull)
pullDepth = input.float(20, "Pullback: depth – fast (±)", minval = 0, maxval = 100, group = grpS, tooltip = TT_PULL, active = inPull)
trigLvl = input.float(0, "Pullback: entry trigger – fast (±)", minval = -100, maxval = 100, group = grpS, tooltip = TT_TRIG, active = inPull)
sigLevel = input.float(30, "Breakout: level – slow (±)", minval = 0, maxval = 100, group = grpS, tooltip = TT_TLVL, active = not inPull)
rearmLvl = input.float(0, "Breakout: re-arm after return to (±)", minval = -100, maxval = 100, group = grpS, tooltip = TT_REARM, active = not inPull)
minCat = input.int(2, "Min. agreeing categories (1–4)", minval = 1, maxval = 4, group = grpS, tooltip = TT_AGREE)
trendAdxOn = input.bool(false, "ADX filter: only when ADX ≥", inline = "tadx", group = grpS, tooltip = TT_TADX)
trendAdxThr = input.float(20, "", minval = 0, inline = "tadx", group = grpS, active = trendAdxOn)
trendObosOn = input.bool(true, "Zone filter: fast score not overbought / oversold", group = grpS, tooltip = TT_TOBOS)
grpK = "③ Counter-trend signals ▲▼"
showContra = input.bool(true, "Show counter-trend signals ▲▼", group = grpK, tooltip = TT_CSHOW)
obosLevel = input.float(60, "Overbought / oversold level – fast (±)", minval = 1, maxval = 99, group = grpK, tooltip = TT_OBOS)
contraMinBars = input.int(1, "Min. bars in zone", minval = 1, group = grpK, tooltip = TT_CBARS)
contraFilter = input.string("Slow score", "Filter", options = ["Slow score", "ADX", "None"], group = grpK, tooltip = TT_CFILT)
ctxContra = input.float(30, "Slow score: block beyond (±)", minval = 0, maxval = 100, group = grpK, tooltip = TT_CCTX, active = contraFilter == "Slow score")
contraAdxThr = input.float(20, "ADX: allow below", minval = 0, group = grpK, tooltip = TT_CADX, active = contraFilter == "ADX")
divSigMode = input.string("Require", "Divergence link", options = ["Ignore", "Mark", "Require"], group = grpK, tooltip = TT_DIVSIG)
divValid = input.int(15, "Divergence link window (bars)", minval = 1, group = grpK, tooltip = TT_DIVWIN)
divBypass = input.bool(true, "Divergence bypasses filter", group = grpK, tooltip = TT_DIVBYP, active = contraFilter != "None")
showFiltered = input.bool(true, "Show blocked (faded) / transparency", inline = "flt", group = grpK, tooltip = TT_FADED, active = contraFilter != "None" and divSigMode != "Require")
fadedT = input.int(55, "", minval = 0, maxval = 95, inline = "flt", group = grpK, active = contraFilter != "None" and divSigMode != "Require" and showFiltered)
grpDv = "④ Divergences"
showDiv = input.bool(true, "Draw divergence lines", group = grpDv, tooltip = TT_DIV)
divLB = input.int(3, "High / low confirmation (bars)", minval = 1, maxval = 20, group = grpDv, tooltip = TT_DIVLB)
divMinGap = input.int(5, "Peak spacing min / max (bars)", minval = 2, inline = "dgap", group = grpDv, tooltip = TT_DIVGAP)
divMaxGap = input.int(60, "", minval = 5, maxval = 450, inline = "dgap", group = grpDv)
divMinPull = input.float(15, "Min. score retrace between peaks", minval = 0, group = grpDv, tooltip = TT_DIVPULL)
divMinDiff = input.float(10, "Min. score difference between peaks", minval = 0, group = grpDv, tooltip = TT_DIVDIFF)
divZoneOnly = input.bool(true, "First high / low inside the zone", group = grpDv, tooltip = TT_DIVZONE)
divCleanLine = input.bool(true, "Line must not cross the score", group = grpDv, tooltip = TT_DIVCLN)
divZeroSide = input.bool(true, "Second high / low on the correct side of zero", group = grpDv, tooltip = TT_DIVZERO)
grpT = "⑤ Components: Trend"
emaFastLen = input.int(20, "EMA fast / slow", minval = 1, inline = "ema", group = grpT, tooltip = TT_EMA)
emaSlowLen = input.int(50, "", minval = 1, inline = "ema", group = grpT)
lrLen = input.int(50, "Regression slope (bars)", minval = 5, group = grpT, tooltip = TT_LR)
adxLen = input.int(14, "DMI / ADX", minval = 2, group = grpT, tooltip = TT_ADXLEN)
atrLen = input.int(14, "ATR (distance scale)", minval = 1, group = grpT, tooltip = TT_ATR)
grpM = "⑥ Components: Momentum"
rsiLen = input.int(14, "RSI", minval = 2, group = grpM, tooltip = TT_RSI)
macdFast = input.int(12, "MACD fast / slow / signal", minval = 1, inline = "macd", group = grpM, tooltip = TT_MACD)
macdSlow = input.int(26, "", minval = 1, inline = "macd", group = grpM)
macdSig = input.int(9, "", minval = 1, inline = "macd", group = grpM)
rocLen = input.int(20, "Price change (bars)", minval = 2, group = grpM, tooltip = TT_ROC)
grpV = "⑦ Components: Volume"
volMode = input.string("Auto", "Volume mode", options = ["Auto", "Always", "Off"], group = grpV, tooltip = TT_VOLMODE)
bool volIn = volMode != "Off"
cmfLen = input.int(14, "CMF fast / slow", minval = 2, inline = "cmf", group = grpV, tooltip = TT_CMF, active = volIn)
cmfSlowLen = input.int(50, "", minval = 2, inline = "cmf", group = grpV, active = volIn)
obvLen = input.int(50, "OBV – average (bars)", minval = 2, group = grpV, tooltip = TT_OBV, active = volIn)
grpX = "⑧ Components: Structure & smoothing"
pivLeft = input.int(5, "Major swing: bars left / right", minval = 1, inline = "piv", group = grpX, tooltip = TT_PIV)
pivRight = input.int(5, "", minval = 1, inline = "piv", group = grpX)
intLen = input.int(2, "Minor swing: bars on each side", minval = 1, group = grpX, tooltip = TT_IPIV)
smoothF = input.int(2, "Smoothing: fast / slow", minval = 1, inline = "sm", group = grpX, tooltip = TT_SMOOTH)
smoothS = input.int(3, "", minval = 1, inline = "sm", group = grpX)
grpD = "⑨ Display"
blockSrc = input.string("Slow", "Blocks show score", options = ["Slow", "Fast"], group = grpD, tooltip = TT_BLK)
showLine = input.bool(true, "Second score line", group = grpD, tooltip = TT_LINE)
dimByAgree = input.bool(true, "Dim blocks on weak agreement / max", inline = "dm", group = grpD, tooltip = TT_DIM)
dimMax = input.int(60, "", minval = 0, maxval = 90, inline = "dm", group = grpD, active = dimByAgree)
showLevels = input.bool(true, "Level lines", group = grpD, tooltip = TT_LVL)
zoneFill = input.bool(true, "Overbought / oversold zones", group = grpD, tooltip = TT_ZONE, active = showContra)
useDynZone = input.bool(true, " Dynamic zone intensity", group = grpD, tooltip = TT_DYNZ, active = showContra and zoneFill)
farT = input.int(90, " Transparency: far from zone", minval = 0, maxval = 100, group = grpD, tooltip = TT_FART, active = showContra and zoneFill and useDynZone)
inT = input.int(75, " Transparency: inside zone", minval = 0, maxval = 100, group = grpD, tooltip = TT_INT, active = showContra and zoneFill)
showObosLines = input.bool(false, " Zone boundary lines", group = grpD, tooltip = TT_OBOSL, active = showContra)
colorBars = input.bool(true, "Color bars like blocks", group = grpD, tooltip = TT_BARS)
showTable = input.bool(true, "Table", inline = "tb", group = grpD, tooltip = TT_TBL)
tblPosStr = input.string("Top right", "", options = ["Top right", "Top left", "Bottom right", "Bottom left", "Top center", "Bottom center"], inline = "tb", group = grpD, active = showTable)
tblSizeStr = input.string("Small", "", options = ["Tiny", "Small", "Normal"], inline = "tb", group = grpD, active = showTable)
showGlow = input.bool(true, "Glow on price chart", group = grpD, tooltip = TT_GLOW)
glowAtrLen = input.int(100, " Glow: ATR", minval = 1, maxval = 500, group = grpD, tooltip = TT_GATR, active = showGlow)
glowWidth = input.float(3.0, " Glow: width (x ATR)", minval = 0.1, maxval = 10.0, step = 0.1, group = grpD, tooltip = TT_GWID, active = showGlow)
glowNearT = input.int(80, " Glow: transparency at price / at edge", minval = 0, maxval = 100, inline = "gt", group = grpD, tooltip = TT_GTR, active = showGlow)
glowFarT = input.int(100, "", minval = 0, maxval = 100, inline = "gt", group = grpD, active = showGlow)
grpC = "⑩ Colors"
cBu1 = input.color(#9BE7FF, "Bull: weak → medium → strong", inline = "bu", group = grpC, tooltip = TT_PAL_BU)
cBu2 = input.color(#2F7BEA, "", inline = "bu", group = grpC)
cBu3 = input.color(#16247A, "", inline = "bu", group = grpC)
cBe1 = input.color(#FFE135, "Bear: weak → medium → strong", inline = "be", group = grpC, tooltip = TT_PAL_BE)
cBe2 = input.color(#FF8C1A, "", inline = "be", group = grpC)
cBe3 = input.color(#E8172B, "", inline = "be", group = grpC)
cOBLine = input.color(#E8172B8C, "Zone boundary lines: overbought / oversold", inline = "lv", group = grpC)
cOSLine = input.color(#16247A8C, "", inline = "lv", group = grpC)
cLine = input.color(#787B86, "Score line", group = grpC)
cNeu = input.color(#787B86, "Neutral (bars and glow near zero)", group = grpC)
grpA = "⑪ Alerts"
alertTrend = input.bool(true, "Trend signals ◆", group = grpA, tooltip = TT_ALERT)
alertContra = input.bool(true, "Counter-trend signals ▲▼", group = grpA, tooltip = TT_ACON)
alertDivSig = input.bool(true, "Divergence signals B / S", group = grpA, tooltip = TT_ABS)
// HELPER FUNCTIONS
f_tanh(float x) =>
float y = math.max(-20.0, math.min(20.0, x))
float e = math.exp(2.0 * y)
(e - 1.0) / (e + 1.0)
// Scales a component to −1..+1 relative to its typical magnitude (root mean square over NORM_LEN bars).
// RMS rather than standard deviation, so the scale does not collapse towards zero in a long trend.
f_eq(float x) =>
float rms = math.sqrt(ta.sma(x * x, NORM_LEN))
float r = na
if not na(x) and not na(rms) and rms > 0
r := f_tanh(EQ_GAIN * x / rms)
r
f_avg(array<float> a) =>
float sum = 0.0
int cnt = 0
for v in a
if not na(v)
sum += v
cnt += 1
cnt > 0 ? sum / cnt : na
// Weighted category average (−100..+100) and agreement (share of weight aligned with the score direction)
f_agg(array<float> s, array<float> w) =>
float num = 0.0
float den = 0.0
float wBu = 0.0
float wBe = 0.0
for i = 0 to s.size() - 1
float v = s.get(i)
float wi = w.get(i)
if not na(v) and wi > 0
num += v * wi
den += wi
if v > 0.1
wBu += wi
else if v < -0.1
wBe += wi
float raw = den > 0 ? num / den * 100 : na
float agr = den > 0 ? (nz(raw) >= 0 ? wBu : wBe) / den : 0.0
[raw, agr]
// Number of active categories clearly pointing up / down
f_count(array<float> s, array<float> w) =>
int nBu = 0
int nBe = 0
int nAc = 0
for i = 0 to s.size() - 1
float v = s.get(i)
float wi = w.get(i)
if not na(v) and wi > 0
nAc += 1
if v > 0.1
nBu += 1
else if v < -0.1
nBe += 1
[nBu, nBe, nAc]
// Three-point gradient: t = 0 → c1, 0.5 → c2, 1 → c3
f_grad3(float t, color c1, color c2, color c3) =>
t < 0.5 ? color.from_gradient(t, 0.0, 0.5, c1, c2) : color.from_gradient(t, 0.5, 1.0, c2, c3)
// Price position within a swing range: middle → 0, edges → ±0.76, beyond the range further towards ±1
f_rangePos(float hi, float lo) =>
not na(hi) and not na(lo) and hi > lo ? f_tanh((close - (hi + lo) / 2) / ((hi - lo) / 2)) : na
// CATEGORIES – fast (*F) and slow (*S) components
float atr = ta.atr(atrLen)
// 1. Trend
float emaF = ta.ema(close, emaFastLen)
float emaS = ta.ema(close, emaSlowLen)
[diP, diM, adx] = ta.dmi(adxLen, adxLen)
float lrSlope = ta.linreg(close, lrLen, 0) - ta.linreg(close, lrLen, 1)
float tFast = f_eq((close - emaF) / atr)
// EMA alignment and regression direction – direction only, extension is not rewarded
float tCross = f_tanh((emaF - emaS) / (EMA_ZONE * atr))
float tDmi = f_eq((diP + diM) > 0 ? (diP - diM) / (diP + diM) : 0.0)
float tSlope = f_tanh(lrSlope * lrLen / (LR_ZONE * atr))
float trendF = tFast
float trendS = f_avg(array.from(tCross, tDmi, tSlope))
// 2. Momentum
[macdL, macdS, macdH] = ta.macd(close, macdFast, macdSlow, macdSig)
float mRsi = f_eq(ta.rsi(close, rsiLen) - 50)
float mMacd = f_eq(macdH)
float mRoc = f_eq((close - close[rocLen]) / atr)
float momF = f_avg(array.from(mRsi, mMacd))
float momS = mRoc
// 3. Volume
bool hasVol = ta.cum(nz(volume)) > 0
bool realVolTy = syminfo.type != "cfd" and syminfo.type != "forex"
bool useVolCat = volMode == "Always" ? hasVol : volMode == "Auto" ? hasVol and realVolTy : false
float mfv = high != low ? ((close - low) - (high - close)) / (high - low) * nz(volume) : 0.0
float mfvSumF = math.sum(mfv, cmfLen)
float mfvSumS = math.sum(mfv, cmfSlowLen)
float vSumF = math.sum(nz(volume), cmfLen)
float vSumS = math.sum(nz(volume), cmfSlowLen)
float cmfF = vSumF > 0 ? mfvSumF / vSumF : 0.0
float cmfS = vSumS > 0 ? mfvSumS / vSumS : 0.0
float obvV = ta.cum(math.sign(nz(ta.change(close))) * nz(volume))
float vCmfF = f_eq(cmfF)
float vCmfS = f_eq(cmfS)
float vObv = f_eq(obvV - ta.ema(obvV, obvLen))
float volF = useVolCat ? vCmfF : na
float volS = useVolCat ? f_avg(array.from(vCmfS, vObv)) : na
// 4. Structure – major swing (slow)
float pvH = ta.pivothigh(high, pivLeft, pivRight)
float pvL = ta.pivotlow(low, pivLeft, pivRight)
var float swH1 = na // latest swing high
var float swH0 = na // previous swing high
var float swL1 = na // latest swing low
var float swL0 = na // previous swing low
var float hSeq = na // HH (+) / LH (−), size in ATR
var float lSeq = na // HL (+) / LL (−), size in ATR
var string hiType = "—"
var string loType = "—"
if not na(pvH)
swH0 := swH1
swH1 := pvH
if not na(swH0)
hSeq := f_tanh(EQ_GAIN * (swH1 - swH0) / atr)
hiType := swH1 > swH0 ? "HH" : swH1 < swH0 ? "LH" : "EQH"
if not na(pvL)
swL0 := swL1
swL1 := pvL
if not na(swL0)
lSeq := f_tanh(EQ_GAIN * (swL1 - swL0) / atr)
loType := swL1 > swL0 ? "HL" : swL1 < swL0 ? "LL" : "EQL"
float sSeq = f_avg(array.from(hSeq, lSeq))
float sRange = f_rangePos(swH1, swL1)
// Minor swing (fast)
float ipH = ta.pivothigh(high, intLen, intLen)
float ipL = ta.pivotlow(low, intLen, intLen)
var float iH = na
var float iL = na
if not na(ipH)
iH := ipH
if not na(ipL)
iL := ipL
float strF = f_rangePos(iH, iL)
float strS = f_avg(array.from(sSeq, sRange))
// SCORES
array<float> catW = array.from(wTrend, wMom, wVol, wStr)
array<float> catS = array.from(trendS, momS, volS, strS)
array<float> catF = array.from(trendF, momF, volF, strF)
[rawS, agrS] = f_agg(catS, catW)
[rawF, agrF] = f_agg(catF, catW)
[nBuS, nBeS, nAcS] = f_count(catS, catW)
[nBuF, nBeF, nAcF] = f_count(catF, catW)
float scoreS = ta.ema(rawS, smoothS)
float scoreF = ta.ema(rawF, smoothF)
float agreeS = nz(ta.ema(agrS, smoothS))
float agreeF = nz(ta.ema(agrF, smoothF))
int needCat = math.min(minCat, nAcS)
bool catBu = nAcS > 0 and nBuS >= needCat
bool catBe = nAcS > 0 and nBeS >= needCat
bool barClosed = not onClose or barstate.isconfirmed
// TREND SIGNALS
bool trendAdxOK = not trendAdxOn or adx >= trendAdxThr
// Pullback mode: direction from the slow score, entry from the fast score
var bool pbLong = false // a downward pullback has occurred since the last trigger
var bool pbShort = false // an upward pullback has occurred since the last trigger
if scoreF <= -pullDepth
pbLong := true
if scoreF >= pullDepth
pbShort := true
bool fUp = ta.crossover(scoreF, trigLvl)
bool fDn = ta.crossunder(scoreF, -trigLvl)
bool ctxBu = scoreS >= ctxTrend and catBu
bool ctxBe = scoreS <= -ctxTrend and catBe
bool pullLong = inPull and fUp and pbLong and ctxBu
bool pullShort = inPull and fDn and pbShort and ctxBe
// Each pullback allows one signal – the first trigger cross consumes it
if fUp and barClosed
pbLong := false
if fDn and barClosed
pbShort := false
// Breakout mode: the slow score crosses the ±level
var bool longArmed = true
var bool shortArmed = true
if scoreS <= rearmLvl
longArmed := true
if scoreS >= -rearmLvl
shortArmed := true
bool sUp = ta.crossover(scoreS, sigLevel)
bool sDn = ta.crossunder(scoreS, -sigLevel)
bool brkLong = not inPull and sUp and longArmed and catBu
bool brkShort = not inPull and sDn and shortArmed and catBe
// Zone filter: no Long while the fast score is overbought, no Short while it is oversold
bool trendObOK = not trendObosOn or nz(scoreF) < obosLevel
bool trendOsOK = not trendObosOn or nz(scoreF) > -obosLevel
bool trendLong = barClosed and trendAdxOK and trendObOK and (pullLong or brkLong)
bool trendShort = barClosed and trendAdxOK and trendOsOK and (pullShort or brkShort)
if trendLong and not inPull
longArmed := false
if trendShort and not inPull
shortArmed := false
// COUNTER-TREND SIGNALS (fast score)
var int obCnt = 0
var int osCnt = 0
bool backFromOB = false
bool backFromOS = false
if not na(scoreF)
if scoreF >= obosLevel
obCnt += 1
else
backFromOB := obCnt >= contraMinBars
obCnt := 0
if scoreF <= -obosLevel
osCnt += 1
else
backFromOS := osCnt >= contraMinBars
osCnt := 0
bool passBuy = contraFilter == "None" or (contraFilter == "ADX" ? adx < contraAdxThr : nz(scoreS) > -ctxContra)
bool passSell = contraFilter == "None" or (contraFilter == "ADX" ? adx < contraAdxThr : nz(scoreS) < ctxContra)
bool rawBuy = barClosed and backFromOS
bool rawSell = barClosed and backFromOB
bool contraLong = rawBuy and passBuy
bool contraShort = rawSell and passSell
bool contraLongX = rawBuy and not passBuy // blocked by the filter
bool contraShortX = rawSell and not passSell
// DIVERGENCES (price vs fast score)
// Scan of the score between two extremes:
// ok – the score stays on the correct side of the divergence line
// ext – extreme of the retrace in between
// post – extreme of the wave after the retrace (the second point must be the true extreme of its wave)
f_divScan(int idx1, float v1, int idx2, float v2, bool above) =>
bool ok = true
float ext = na
int extI = na
float post = na
int gap = idx2 - idx1
if not na(v1) and not na(v2) and gap > 1 and gap <= divMaxGap
for i = 1 to gap - 1
float ov = scoreF[bar_index - (idx1 + i)]
float lv = v1 + (v2 - v1) * i / gap
if above ? ov < lv : ov > lv
ok := false
if na(ext) or (above ? ov > ext : ov < ext)
ext := ov
extI := i
if not na(extI) and extI < gap - 1
for i = extI + 1 to gap - 1
float ov = scoreF[bar_index - (idx1 + i)]
post := na(post) ? ov : above ? math.min(post, ov) : math.max(post, ov)
[ok, ext, post]
var float divBotOsc = na
var float divBotPrc = na
var int divBotIdx = na
var float divTopOsc = na
var float divTopPrc = na
var int divTopIdx = na
var int lastBullDivBar = na
var int lastBearDivBar = na
float pl = ta.pivotlow(scoreF, divLB, divLB)
float ph = ta.pivothigh(scoreF, divLB, divLB)
[botClean, botMid, botPost] = f_divScan(divBotIdx, divBotOsc, bar_index - divLB, pl, true)
[topClean, topMid, topPost] = f_divScan(divTopIdx, divTopOsc, bar_index - divLB, ph, false)
bool bullDiv = false
if not na(pl) and barClosed
int pIdx = bar_index - divLB
float pPrc = low[divLB]
bool shapeOK = not na(divBotOsc) and pIdx - divBotIdx >= divMinGap and pIdx - divBotIdx <= divMaxGap
bool sizeOK = pl - divBotOsc >= divMinDiff and not na(botMid) and botMid - math.max(pl, divBotOsc) >= divMinPull and (na(botPost) or botPost >= pl)
if shapeOK and sizeOK and pPrc < divBotPrc and (not divZoneOnly or divBotOsc <= -obosLevel) and (not divZeroSide or pl < 0) and (not divCleanLine or botClean)
bullDiv := true
lastBullDivBar := bar_index
if showDiv
line.new(divBotIdx, divBotOsc, pIdx, pl, color = cBu3, width = 1)
// New reference point: a deeper low of the same wave or a low of a new wave
bool newWaveB = not na(divBotOsc) and not na(botMid) and botMid - math.max(pl, divBotOsc) >= divMinPull
bool betterB = na(divBotOsc) or pl <= divBotOsc or newWaveB or pIdx - divBotIdx > divMaxGap
if (not divZoneOnly or pl <= -obosLevel) and betterB
divBotOsc := pl
divBotPrc := pPrc
divBotIdx := pIdx
bool bearDiv = false
if not na(ph) and barClosed
int pIdx = bar_index - divLB
float pPrc = high[divLB]
bool shapeOK = not na(divTopOsc) and pIdx - divTopIdx >= divMinGap and pIdx - divTopIdx <= divMaxGap
bool sizeOK = divTopOsc - ph >= divMinDiff and not na(topMid) and math.min(ph, divTopOsc) - topMid >= divMinPull and (na(topPost) or topPost <= ph)
if shapeOK and sizeOK and pPrc > divTopPrc and (not divZoneOnly or divTopOsc >= obosLevel) and (not divZeroSide or ph > 0) and (not divCleanLine or topClean)
bearDiv := true
lastBearDivBar := bar_index
if showDiv
line.new(divTopIdx, divTopOsc, pIdx, ph, color = cBe3, width = 1)
bool newWaveT = not na(divTopOsc) and not na(topMid) and math.min(ph, divTopOsc) - topMid >= divMinPull
bool betterT = na(divTopOsc) or ph >= divTopOsc or newWaveT or pIdx - divTopIdx > divMaxGap
if (not divZoneOnly or ph >= obosLevel) and betterT
divTopOsc := ph
divTopPrc := pPrc
divTopIdx := pIdx
// Combining counter-trend signals with a divergence in the same direction (B / S)
var int lastBuySig = na
var int lastSellSig = na
var bool buyDivDone = false
var bool sellDivDone = false
var int usedBullDivBar = na // divergence already linked to a signal
var int usedBearDivBar = na
bool buyForDiv = divBypass or contraFilter == "None" ? rawBuy : contraLong
bool sellForDiv = divBypass or contraFilter == "None" ? rawSell : contraShort
if buyForDiv
lastBuySig := bar_index
buyDivDone := false
lastSellSig := na
if sellForDiv
lastSellSig := bar_index
sellDivDone := false
lastBuySig := na
bool recentBuySig = not na(lastBuySig) and bar_index - lastBuySig <= divValid
bool recentSellSig = not na(lastSellSig) and bar_index - lastSellSig <= divValid
bool recentBullDiv = not na(lastBullDivBar) and bar_index - lastBullDivBar <= divValid and (na(usedBullDivBar) or lastBullDivBar != usedBullDivBar)
bool recentBearDiv = not na(lastBearDivBar) and bar_index - lastBearDivBar <= divValid and (na(usedBearDivBar) or lastBearDivBar != usedBearDivBar)
bool buyDivSignal = not buyDivDone and recentBuySig and recentBullDiv
bool sellDivSignal = not sellDivDone and recentSellSig and recentBearDiv
if buyDivSignal
buyDivDone := true
usedBullDivBar := lastBullDivBar
if sellDivSignal
sellDivDone := true
usedBearDivBar := lastBearDivBar
// What is visible on the chart
bool showTrendMk = showTrend
bool showPlainMk = showContra and divSigMode != "Require"
bool showBSMk = showContra and divSigMode != "Ignore"
// Latest visible events (table)
var string lastSig = "—"
var int lastSigBar = na
string tName = inPull ? "Pullback" : "Breakout"
if trendLong and showTrendMk
lastSig := tName + " ▲"
lastSigBar := bar_index
if trendShort and showTrendMk
lastSig := tName + " ▼"
lastSigBar := bar_index
if contraLong and showPlainMk
lastSig := "Counter ▲"
lastSigBar := bar_index
if contraShort and showPlainMk
lastSig := "Counter ▼"
lastSigBar := bar_index
if buyDivSignal and showBSMk
lastSig := "Counter ▲ + Div"
lastSigBar := bar_index
if sellDivSignal and showBSMk
lastSig := "Counter ▼ + Div"
lastSigBar := bar_index
var int lastDivBar = na
var int lastDivDir = 0
if bullDiv
lastDivBar := bar_index
lastDivDir := 1
if bearDiv
lastDivBar := bar_index
lastDivDir := -1
// DRAWING
bool blkSlow = blockSrc == "Slow"
float blk = blkSlow ? scoreS : scoreF
float lineV = blkSlow ? scoreF : scoreS
float agreeB = blkSlow ? agreeS : agreeF
float unit = 100.0 / BANDS
float sc = nz(blk)
int upLvl = sc > 0 ? math.min(BANDS, int(math.floor(sc / unit))) : 0
int dnLvl = sc < 0 ? math.min(BANDS, int(math.floor(-sc / unit))) : 0
float litT = dimByAgree ? dimMax * (1.0 - agreeB) : 0.0
// Level lines
color cTrL = showLevels and showTrend ? color.new(color.gray, 45) : color.new(color.gray, 100)
color cZeL = showLevels ? color.new(color.gray, 40) : color.new(color.gray, 100)
hline(0, "Zero", cZeL, hline.style_solid)
hline(inPull ? ctxTrend : sigLevel, "Trend level +", cTrL, hline.style_dotted)
hline(inPull ? -ctxTrend : -sigLevel, "Trend level −", cTrL, hline.style_dotted)
// Overbought / oversold zones (fast score)
f_remap(float v, float inMin, float inMax, float outMin, float outMax) =>
outMin + (v - inMin) * (outMax - outMin) / (inMax - inMin)
float fz = nz(scoreF)
float obT = useDynZone ? math.round(f_remap(math.max(0, math.min(obosLevel - fz, obosLevel)), 0, obosLevel, inT, farT)) : inT
float osT = useDynZone ? math.round(f_remap(math.max(0, math.min(fz + obosLevel, obosLevel)), 0, obosLevel, inT, farT)) : inT
bool zOn = showContra and showObosLines
bool zf = showContra and zoneFill
hOB = hline(obosLevel, "Overbought boundary", cOBLine, hline.style_solid, display = zOn ? display.all : display.none)
hOS = hline(-obosLevel, "Oversold boundary", cOSLine, hline.style_solid, display = zOn ? display.all : display.none)
hTop = hline(100, "Edge +100", color.new(color.gray, 100), editable = false)
hBot = hline(-100, "Edge −100", color.new(color.gray, 100), editable = false)
fill(hTop, hOB, zf ? color.new(cBe2, obT) : color.new(cBe2, 100), title = "Overbought zone")
fill(hOS, hBot, zf ? color.new(cBu2, osT) : color.new(cBu2, 100), title = "Oversold zone")
// Color of block k (1 = nearest to zero); unlit blocks are invisible
f_block(int k, bool bull) =>
int lvl = bull ? upLvl : dnLvl
float t = (k - 1.0) / (BANDS - 1.0)
color base = bull ? f_grad3(t, cBu1, cBu2, cBu3) : f_grad3(t, cBe1, cBe2, cBe3)
k <= lvl ? color.new(base, litT) : color(na)
// Bullish blocks
plot(1 * unit, "Bull 1", f_block(1, true), style = plot.style_columns, histbase = 0 * unit, editable = false, display = display.pane)
plot(2 * unit, "Bull 2", f_block(2, true), style = plot.style_columns, histbase = 1 * unit, editable = false, display = display.pane)
plot(3 * unit, "Bull 3", f_block(3, true), style = plot.style_columns, histbase = 2 * unit, editable = false, display = display.pane)
plot(4 * unit, "Bull 4", f_block(4, true), style = plot.style_columns, histbase = 3 * unit, editable = false, display = display.pane)
plot(5 * unit, "Bull 5", f_block(5, true), style = plot.style_columns, histbase = 4 * unit, editable = false, display = display.pane)
plot(6 * unit, "Bull 6", f_block(6, true), style = plot.style_columns, histbase = 5 * unit, editable = false, display = display.pane)
plot(7 * unit, "Bull 7", f_block(7, true), style = plot.style_columns, histbase = 6 * unit, editable = false, display = display.pane)
plot(8 * unit, "Bull 8", f_block(8, true), style = plot.style_columns, histbase = 7 * unit, editable = false, display = display.pane)
plot(9 * unit, "Bull 9", f_block(9, true), style = plot.style_columns, histbase = 8 * unit, editable = false, display = display.pane)
plot(10 * unit, "Bull 10", f_block(10, true), style = plot.style_columns, histbase = 9 * unit, editable = false, display = display.pane)
// Bearish blocks
plot(-1 * unit, "Bear 1", f_block(1, false), style = plot.style_columns, histbase = -0 * unit, editable = false, display = display.pane)
plot(-2 * unit, "Bear 2", f_block(2, false), style = plot.style_columns, histbase = -1 * unit, editable = false, display = display.pane)
plot(-3 * unit, "Bear 3", f_block(3, false), style = plot.style_columns, histbase = -2 * unit, editable = false, display = display.pane)
plot(-4 * unit, "Bear 4", f_block(4, false), style = plot.style_columns, histbase = -3 * unit, editable = false, display = display.pane)
plot(-5 * unit, "Bear 5", f_block(5, false), style = plot.style_columns, histbase = -4 * unit, editable = false, display = display.pane)
plot(-6 * unit, "Bear 6", f_block(6, false), style = plot.style_columns, histbase = -5 * unit, editable = false, display = display.pane)
plot(-7 * unit, "Bear 7", f_block(7, false), style = plot.style_columns, histbase = -6 * unit, editable = false, display = display.pane)
plot(-8 * unit, "Bear 8", f_block(8, false), style = plot.style_columns, histbase = -7 * unit, editable = false, display = display.pane)
plot(-9 * unit, "Bear 9", f_block(9, false), style = plot.style_columns, histbase = -8 * unit, editable = false, display = display.pane)
plot(-10 * unit, "Bear 10", f_block(10, false), style = plot.style_columns, histbase = -9 * unit, editable = false, display = display.pane)
// Bar color = color of the highest lit block
color barC = upLvl > 0 ? f_grad3((upLvl - 1.0) / (BANDS - 1.0), cBu1, cBu2, cBu3) : dnLvl > 0 ? f_grad3((dnLvl - 1.0) / (BANDS - 1.0), cBe1, cBe2, cBe3) : cNeu
barcolor(colorBars ? barC : na, title = "Bar color", editable = false)
// Glow on the price chart: the center follows HL2
float gAtr = ta.atr(glowAtrLen)
float gMid = hl2
// Side: bullish → below the bars, bearish → above the bars, neutral → unchanged
var int gSide = 0
if upLvl > 0
gSide := -1
else if dnLvl > 0
gSide := 1
bool gOn = showGlow and not na(gAtr)
float gW = nz(gAtr) * glowWidth
color gNear = color.new(barC, glowNearT)
color gFar = color.new(barC, glowFarT)
color gOff = color.new(barC, 100)
bool gUp = gSide > 0
bool gDn = gSide < 0
pGMid = plot(gOn ? gMid : na, "Glow – center", color.new(color.gray, 100), editable = false, display = display.none, force_overlay = true)
pGUp = plot(gOn ? gMid + gW : na, "Glow – upper", color.new(color.gray, 100), editable = false, display = display.none, force_overlay = true)
pGDn = plot(gOn ? gMid - gW : na, "Glow – lower", color.new(color.gray, 100), editable = false, display = display.none, force_overlay = true)
fill(pGUp, pGMid, gMid + gW, gMid, gUp ? gFar : gOff, gUp ? gNear : gOff, title = "Glow – above bars", editable = false)
fill(pGMid, pGDn, gMid, gMid - gW, gDn ? gNear : gOff, gDn ? gFar : gOff, title = "Glow – below bars", editable = false)
// Second score line
plot(showLine ? lineV : na, "Score (line)", cLine, linewidth = 2, display = display.pane)
// Signal markers (invisible ±110 lines keep the pane scale)
hline(110, "Scale +110", color.new(color.gray, 100), editable = false)
hline(-110, "Scale −110", color.new(color.gray, 100), editable = false)
float offC = 10.0
float offBS = 20.0
float yEdge = 104.0
bool drawBuy = showPlainMk and (contraLong or (showFiltered and contraFilter != "None" and contraLongX))
bool drawSell = showPlainMk and (contraShort or (showFiltered and contraFilter != "None" and contraShortX))
color cBuyMk = contraLong ? cBu3 : color.new(cBu2, fadedT)
color cSellMk = contraShort ? cBe3 : color.new(cBe3, fadedT)
plotshape(drawBuy ? -obosLevel - offC : na, "Counter Buy", shape.triangleup, location.absolute, cBuyMk, size = size.tiny, display = display.pane)
plotshape(drawSell ? obosLevel + offC : na, "Counter Sell", shape.triangledown, location.absolute, cSellMk, size = size.tiny, display = display.pane)
if buyDivSignal and showBSMk
label.new(bar_index, -obosLevel - offBS, "B", style = label.style_label_up, color = cBu3, textcolor = color.white, size = size.tiny)
if sellDivSignal and showBSMk
label.new(bar_index, obosLevel + offBS, "S", style = label.style_label_down, color = cBe3, textcolor = color.white, size = size.tiny)
plotshape(trendLong and showTrendMk ? -yEdge : na, "Trend Buy", shape.diamond, location.absolute, cBu2, size = size.tiny)
plotshape(trendShort and showTrendMk ? yEdge : na, "Trend Sell", shape.diamond, location.absolute, cBe2, size = size.tiny)
// TABLE
color T_BG = #131722
color T_HEAD = #1E2230
color T_LBL = #B2B5BE
color T_BULL = #4FC3F7
color T_BEAR = #FF6B6B
color T_NEUT = #D1D4DC
color T_DIM = #6A6E79
tblPos = switch tblPosStr
"Top left" => position.top_left
"Bottom right" => position.bottom_right
"Bottom left" => position.bottom_left
"Top center" => position.top_center
"Bottom center" => position.bottom_center
=> position.top_right
tblSize = switch tblSizeStr
"Tiny" => size.tiny
"Normal" => size.normal
=> size.small
f_fmt(float x) =>
na(x) ? "—" : (x > 0 ? "+" : "") + str.tostring(math.round(x * 100))
f_col(float x) =>
na(x) ? T_NEUT : x > 0.1 ? T_BULL : x < -0.1 ? T_BEAR : T_NEUT
f_ago(int b) =>
na(b) ? "" : str.tostring(bar_index - b) + " bars ago"
var table tbl = table.new(tblPos, 3, 10, bgcolor = T_BG, frame_color = #363A45, frame_width = 1, border_color = #2A2E39, border_width = 1)
f_row(int r, string lbl, string v1, color c1, string v2, color c2) =>
color bg = r % 2 == 0 ? T_BG : T_HEAD
table.cell(tbl, 0, r, lbl, text_color = T_LBL, text_size = tblSize, text_halign = text.align_left, bgcolor = bg)
table.cell(tbl, 1, r, v1, text_color = c1, text_size = tblSize, text_halign = text.align_right, bgcolor = bg)
table.cell(tbl, 2, r, v2, text_color = c2, text_size = tblSize, text_halign = text.align_right, bgcolor = bg)
if showTable and barstate.islast
color sigCol = str.contains(lastSig, "▲") ? T_BULL : str.contains(lastSig, "▼") ? T_BEAR : T_NEUT
string divTxt = na(lastDivBar) ? "—" : lastDivDir == 1 ? "Bullish" : "Bearish"
color divCol = lastDivDir == 1 ? T_BULL : lastDivDir == -1 ? T_BEAR : T_NEUT
f_row(0, "", "Slow", T_LBL, "Fast", T_LBL)
f_row(1, "Trend", f_fmt(trendS), f_col(trendS), f_fmt(trendF), f_col(trendF))
f_row(2, "Momentum", f_fmt(momS), f_col(momS), f_fmt(momF), f_col(momF))
f_row(3, "Volume", useVolCat ? f_fmt(volS) : "off", useVolCat ? f_col(volS) : T_DIM, useVolCat ? f_fmt(volF) : "off", useVolCat ? f_col(volF) : T_DIM)
f_row(4, "Structure " + hiType + "/" + loType, f_fmt(strS), f_col(strS), f_fmt(strF), f_col(strF))
f_row(5, "Score", f_fmt(scoreS / 100), f_col(scoreS / 100), f_fmt(scoreF / 100), f_col(scoreF / 100))
int zS = nz(scoreS) >= 0 ? nBuS : nBeS
int zF = nz(scoreF) >= 0 ? nBuF : nBeF
bool okS = nAcS > 0 and zS >= math.min(minCat, nAcS)
f_row(6, "Agreeing categories", str.tostring(zS) + "/" + str.tostring(nAcS), okS ? T_NEUT : T_DIM, str.tostring(zF) + "/" + str.tostring(nAcF), T_NEUT)
f_row(7, "ADX", str.tostring(math.round(adx)), T_NEUT, "", T_NEUT)
f_row(8, "Signal", lastSig, sigCol, f_ago(lastSigBar), T_DIM)
f_row(9, "Divergence", divTxt, divCol, f_ago(lastDivBar), T_DIM)
// ALERTS
// alert() is used instead of alertcondition(), which counts towards the 64-plot limit.
string aFreq = onClose ? alert.freq_once_per_bar_close : alert.freq_once_per_bar
string aPfx = "Confluence Dual Oscillator · " + syminfo.ticker + " " + timeframe.period + ": "
if alertTrend and trendLong
alert(aPfx + "Trend Long signal (" + tName + ")", aFreq)
if alertTrend and trendShort
alert(aPfx + "Trend Short signal (" + tName + ")", aFreq)
if alertContra and contraLong
alert(aPfx + "Counter-trend Buy signal", aFreq)
if alertContra and contraShort
alert(aPfx + "Counter-trend Sell signal", aFreq)
if alertDivSig and buyDivSignal
alert(aPfx + "B – counter-trend Buy confirmed by bullish divergence", aFreq)
if alertDivSig and sellDivSignal
alert(aPfx + "S – counter-trend Sell confirmed by bearish divergence", aFreq)