Multi-period Structure, Volume & Signal Review
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «indicator multi-period structure, volume & signal for tradingview.pine» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Этот индикатор TradingView на Pine Script v6 предназначен для анализа графика и отображения справочных уровней. Он рассчитывает технические показатели, запрашивает данные с других таймфреймов и выводит линии и отметки на графике. Индикатор также позволяет задавать условия для оповещений TradingView.
Пользователь может включать и отключать отдельные модули: профили объёма по завершённым свингам и календарным периодам, аналитические уровни по дневному, недельному и месячному диапазонам, линии Supertrend и контекст торговой сессии. Настройки позволяют менять оформление, пороги и параметры отображения.
Индикатор не является автоматическим советником или стратегией: он не симулирует сделки и не даёт гарантий доходности. Все расчёты и оповещения носят информационный характер.
Настройки программы
| Настройка | Описание |
|---|---|
| viewPreset | Выбирает предустановку оформления. |
| distance | Задаёт размер свинга в единицах ATR. |
| showSignals | Включает показ меток BUY / SELL с ценой закрытия. |
| showPOC | Включает показ подтверждённого POC свинга. |
| showCalendarPOC | Включает показ календарных уровней POC. |
| showDaily | Включает показ дневных аналитических уровней. |
| showWeekly | Включает показ недельных аналитических уровней. |
| showMonthly | Включает показ месячных аналитических уровней. |
| showSession | Включает расчёт контекста пользовательской сессии. |
| showST | Включает показ линии контекста Supertrend. |
| sendAlerts | Включает оповещения о разворотах. |
| costFilter | Включает требование, чтобы движение разворота превышало смоделированные издержки. |
| feePct | Задаёт комиссию за одну сторону в процентах. |
| spreadPct | Задаёт полный спред в процентах. |
| slipPct | Задаёт проскальзывание за одну сторону в процентах. |
| costBuffer | Задаёт множитель минимального порога для фильтра по издержкам. |
| jsonAlerts | Включает отправку оповещений в формате JSON для внешнего моста. |
| showProfile | Включает показ гистограммы объёма внутри завершённого свинга. |
| profileTF | Выбирает младший таймфрейм источника для профилей объёма. |
| profileRows | Задаёт количество ценовых строк для профилей объёма. |
| profileKeep | Задаёт количество сохраняемых завершённых профилей. |
| calSource | Выбирает таймфрейм источника для календарных профилей объёма. |
| calRows | Задаёт количество ценовых строк для календарных профилей объёма. |
| calDEnabled | Включает расчёт и отображение POC за предыдущий день по календарным данным. |
| calWEnabled | Включает расчёт и отображение POC за предыдущую неделю по календарным данным. |
| calMEnabled | Включает расчёт и отображение POC за предыдущий месяц по календарным данным. |
| showDevelopingPOC | Включает показ развивающихся календарных POC. |
| showDailyOpen | Включает показ открытия текущего дня. |
| showBodyRetrace | Включает показ коррекций тела предыдущего дня. |
| showBodyExtend | Включает показ расширений тела предыдущего дня. |
| showRangeTargets | Включает показ проекций дневного диапазона в обе стороны. |
| showWeeklyOpen | Включает показ открытия текущей недели. |
| showWeeklyRetrace | Включает показ коррекций тела предыдущей недели. |
| showWeeklyExtend | Включает показ расширений тела предыдущей недели. |
| showWeeklyRange | Включает показ проекций недельного диапазона в обе стороны. |
| showMonthlyOpen | Включает показ открытия текущего месяца. |
| showMonthlyRetrace | Включает показ коррекций тела предыдущего месяца. |
| showMonthlyExtend | Включает показ расширений тела предыдущего месяца. |
| showMonthlyRange | Включает показ проекций месячного диапазона в обе стороны. |
| minBodyRatio | Задаёт минимальное отношение тела свечи к диапазону периода. |
| showConfluence | Включает подсветку кластеров фиксированных справочных уровней. |
| confluenceATR | Задаёт максимальное расстояние между уровнями для объединения в кластер, выраженное в дневном ATR. |
| mapShowAll | Включает показ всех включённых уровней Фибоначчи. |
| mapSelection | Выбирает опорный уровень для карты справочных значений. |
| mapFocus | Включает фокусировку на ближайших календарных справочных уровнях. |
| mapFocusATR | Задаёт радиус фокуса в единицах подтверждённого дневного ATR. |
| showDailyLabels | Включает показ всех меток карты справочных уровней. |
| dailyLabelOffset | Задаёт смещение справочных меток вправо в барах. |
| mapMergeATR | Задаёт расстояние для объединения меток в единицах подтверждённого дневного ATR. |
| mapMaxZones | Задаёт максимальное количество зон слияния уровней. |
| sessionHours | Задаёт часы торговой сессии. |
| sessionDays | Задаёт дни торговой сессии. |
| sessionZone | Задаёт часовой пояс торговой сессии. |
| showSessionVWAP | Включает показ линии VWAP сессии. |
| showSessionLevels | Включает показ открытия сессии и предыдущих максимума и минимума. |
| stLength | Задаёт длину ATR для Supertrend. |
| stFactor | Задаёт множитель ATR для Supertrend. |
| earlyWarning | Включает показ предварительного предупреждения о развороте. |
| warningATR | Задаёт близость предупреждения в единицах ATR. |
| chopThreshold | Задаёт порог эффективности для классификации бокового движения. |
| shadeChop | Включает затенение бокового движения на всю высоту. |
| showQuality | Включает показ панели качества данных. |
| showSnapshots | Включает сохранение снимков подтверждённых сигналов. |
| snapshotKeep | Задаёт количество сохраняемых снимков. |
| snapshotBack | Выбирает снимок для просмотра: 0 — самый новый. |
| showReactions | Включает отслеживание первых подходящих касаний справочных уровней. |
| reactionSourceView | Выбирает источник для отображения реакций. |
| reactionApproachView | Выбирает направление подхода для отображения реакций. |
| reactionBars | Задаёт количество баров для оценки реакции после касания. |
| reactionMoveATR | Задаёт расстояние реакции в единицах ATR графика. |
| reactionFailATR | Задаёт расстояние отказа в единицах ATR графика. |
| reactionKeep | Задаёт количество сохраняемых разрешённых наблюдений. |
| showStats | Включает показ панели статистики. |
| statsWindow | Задаёт количество последних завершённых сделок для статистики. |
| signalHistory | Задаёт количество последних сделок с текстом BUY / SELL. |
| showWarningLabel | Включает показ плавающей метки раннего предупреждения. |
| historyFade | Задаёт прозрачность исторических свингов. |
| focusTrades | Задаёт количество последних сделок для выделения. |
| showLiveText | Включает показ текста цены развивающегося свинга. |
| cardPosition | Задаёт положение информационной панели на графике. |
| palette | Выбирает цветовую палитру оформления. |
| uiTheme | Выбирает тему оформления панели. |
| extremeHistory | Задаёт количество последних сделок с метками HIGH / LOW. |
| markerGap | Задаёт расстояние между метками сигналов в единицах ATR. |
| showSignalPrice | Включает печать цены внутри меток BUY / SELL. |
| showZone | Включает показ мягкой направленной зоны. |
| zigWidth | Задаёт ширину ZigZag. |
| history | Задаёт количество завершённых сделок для отображения. |
| showExtremes | Включает показ точных HIGH / LOW каждой сигнальной сделки. |
| showLevels | Включает показ последних уровней входа и подтверждения. |
| showGlow | Включает мягкое свечение ZigZag. |
| showJurik | Включает отображение ленты Jurik. |
| labelOffset | Задаёт смещение меток справа в барах. |
| showZZ | Включает показ подтверждённых сегментов ZigZag. |
| showLive | Включает показ развивающегося свинга. |
| showTrail | Включает показ порога разворота. |
| paintBars | Включает раскрашивание свечей. |
| showPanel | Включает показ панели статуса. |
| customUp | Задаёт цвет для отображения длинных сигналов. |
| customDown | Задаёт цвет для отображения коротких сигналов. |
Поиск по коду файла
indicator('Multi-period Structure, Volume & Signal Review', shorttitle = 'MTF Volume & Fib', overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 300)
gStart = '01 - Workspace'
viewPreset = input.string('Minimal', 'Presentation preset', options = ['Minimal', 'Analysis', 'Publication'], group = gStart, display = display.none, tooltip = 'Analysis shows enabled research panels. Minimal keeps a compact status card and hides profile histograms, map text and session H/L/open plots. Publication hides dashboards but retains chart annotations. All three use identical calculations, snapshots, reaction rules and BUY/SELL signals.')
distance = input.float(1.6, 'Swing size (ATR)', minval = 0.2, step = 0.1, group = gStart, display = display.none, tooltip = 'Higher = wider swings and usually longer holds. Lower = faster reversals and more noise. Not a broker stop.')
showSignals = input.bool(true, 'BUY / SELL labels with close price', group = gStart, display = display.none, tooltip = 'Shows confirmed signal markers. A leader connects each offset label to the actual confirmation-close dot.')
showPOC = input.bool(true, 'Confirmed swing POC', group = gStart, display = display.none, tooltip = 'Gold POC appears only when a signal-derived swing confirms. Its historical segment is retrospective; the live extension starts at confirmation. Independent of trade signals.')
showCalendarPOC = input.bool(true, 'Calendar POC levels', group = gStart, display = display.none, tooltip = 'Independent completed day/week/month distributions, never averages of lower-period POCs. Uses a separate source timeframe so short chart history need not prevent monthly coverage. Source-feed history must still contain a full period. First partial period is discarded.')
showDaily = input.bool(true, 'Daily analytical levels', group = gStart, inline = 'moduleDW', display = display.none, tooltip = 'Current day only, on chart timeframes up to 1D. Uses the symbol\'s daily-feed boundaries, not your display timezone. Never supplies order exits.')
showWeekly = input.bool(true, 'Weekly analytical levels', group = gStart, inline = 'moduleDW', display = display.none, tooltip = 'Uses the previous completed weekly candle and this week\'s open. Symbol/feed week boundaries; disabled above the weekly timeframe. Analytical references only.')
showMonthly = input.bool(true, 'Monthly analytical levels', group = gStart, inline = 'moduleDW', display = display.none, tooltip = 'Uses the previous completed monthly candle and this month\'s open. Calendar months follow the symbol/feed. Disabled above the monthly timeframe.')
showSession = input.bool(true, 'Calculate custom session context', group = gStart, display = display.none, tooltip = 'Session open, previous completed session high/low and closed-candle HLC3-volume VWAP. Standard intraday charts only. Requires aligned chart candles and observed full session boundaries; partial first sessions are rejected. Does not filter trades.')
showST = input.bool(true, 'Supertrend context line', group = gStart, display = display.none, tooltip = 'TradingView built-in Supertrend, latched on chart-candle close. Directional context only: never changes the existing reversal rules or creates an order.')
sendAlerts = input.bool(true, 'Enable reversal alerts', group = gStart, display = display.none, tooltip = 'Enable dynamic alert() messages. Create an Any alert() function call alert; existing TradingView alerts must be recreated after edits.')
gSignal = '02 - Signals and costs'
costFilter = input.bool(true, 'Require reversal movement beyond modeled costs', group = gSignal, display = display.none, tooltip = 'Applies to the pullback from the swing extreme, not to profit since entry. Can delay reversals. Zero cost inputs mean no additional filtering.')
feePct = input.float(0.0, 'Commission per side (%)', minval = 0, maxval = 5, step = 0.001, group = gSignal, inline = 'costs', display = display.none, tooltip = 'Enter your actual fee as percent of notional: 0.05 means 0.05%. No broker fee is assumed.')
spreadPct = input.float(0.0, 'Full spread (%)', minval = 0, maxval = 5, step = 0.001, group = gSignal, inline = 'costs', display = display.none, tooltip = 'Approximate full bid-ask spread expressed as percent of price, deducted once per modeled round trip.')
slipPct = input.float(0.0, 'Slippage per side (%)', minval = 0, maxval = 5, step = 0.001, group = gSignal, inline = 'costs', display = display.none, tooltip = 'Approximate slippage percent for each entry and exit. Actual fills can be worse.')
costBuffer = input.float(1.5, 'Cost floor multiplier', minval = 1, maxval = 3, step = 0.1, group = gSignal, display = display.none, tooltip = 'Only scales the reversal filter. Statistics deduct the unscaled cost estimate.')
jsonAlerts = input.bool(false, 'Generic bridge JSON (not PrimeXBT API format)', group = gSignal, display = display.none, tooltip = 'For a separately implemented execution bridge. This schema cannot be sent directly as a native PrimeXBT order.')
gVolume = '03 - Volume profiles'
showProfile = input.bool(true, 'Histogram inside completed swing', group = gVolume, display = display.none, tooltip = 'Uses full endpoint candles, including their entire volume. Adjacent profiles share the endpoint candle. Width indicates relative row volume, not elapsed trading time.')
profileTF = input.timeframe('1', 'Lower timeframe source', group = gVolume, display = display.none, tooltip = 'Choose below the chart timeframe. Missing, incomplete or non-lower requests use a chart-candle fallback. Provider volume is not broker volume.')
profileRows = input.int(32, 'Price rows', minval = 8, maxval = 64, group = gVolume, display = display.none, tooltip = 'POC is the midpoint of the maximum-volume row. More rows mean finer bins, not greater source-data accuracy.')
profileKeep = input.int(2, 'Completed profiles to retain', minval = 1, maxval = 4, group = gVolume, display = display.none, tooltip = 'Retains this many completed profiles; only the latest valid POC is extended right. This does not change signal history.')
calSource = input.timeframe('60', 'Calendar sampling timeframe', options = ['15', '30', '60'], group = gVolume, display = display.none, tooltip = '60m default gives roughly 250 calendar days of crypto coverage with 6000 requested source bars. 15m gives about 62 days and finer estimates. Actual provider history may be shorter. Use a chart timeframe at or below this source; other chart timeframes disable calendar POCs. Coarse source candles cannot reconstruct actual volume-at-price.')
calRows = input.int(48, 'Calendar price rows', minval = 8, maxval = 100, group = gVolume, display = display.none, tooltip = 'Uniform candle-volume overlap over the full observed period range. POC is the maximum row midpoint; exact ties choose the lowest row. An estimate, not built-in volume-profile parity.')
calDEnabled = input.bool(true, 'Previous day POC', group = gVolume, inline = 'cal', display = display.none, tooltip = 'Completed daily volume distribution from source candles, using symbol session boundaries.')
calWEnabled = input.bool(true, 'Previous week POC', group = gVolume, inline = 'cal', display = display.none, tooltip = 'Independent completed weekly distribution; not an average of daily POCs.')
calMEnabled = input.bool(true, 'Previous month POC', group = gVolume, inline = 'cal', display = display.none, tooltip = 'Independent completed monthly distribution. Missing full-month coverage is shown as unavailable, never extrapolated.')
showDevelopingPOC = input.bool(false, 'Developing calendar POCs', group = gVolume, display = display.none, tooltip = 'Dashed provisional profiles use closed source candles only. They are hidden at a new period until its first closed source sample arrives, change as the period develops, are delayed by the source interval, and are excluded from confluence. Enabling them increases computation.')
gReference = '04 - Reference map'
showDailyOpen = input.bool(true, 'Today\'s open', group = gReference, display = display.none, tooltip = 'Displays the current daily-feed open. It is fixed from the day\'s start, unlike an unfinished daily close.')
showBodyRetrace = input.bool(true, 'Previous-day body retracements', group = gReference, inline = 'daybody', display = display.none, tooltip = 'C-r*(C-O), r=0.382/0.5/0.618, using yesterday\'s confirmed open/close.')
showBodyExtend = input.bool(true, 'Previous-day body extensions', group = gReference, inline = 'daybody', display = display.none, tooltip = 'O+e*(C-O), e=1.272/1.618/2.0. Extensions continue yesterday\'s body direction; they are not ABC swing extensions.')
showRangeTargets = input.bool(true, 'Daily-range projections: both directions', group = gReference, display = display.none, tooltip = 'Today\'s open +/- yesterday\'s full high-low range * 0.618/1/1.618. Hypothetical distances, not predicted prices.')
showWeeklyOpen = input.bool(true, 'This week\'s open', group = gReference, display = display.none, tooltip = 'Fixed opening price of the current exchange/feed week. Does not use the unfinished weekly close.')
showWeeklyRetrace = input.bool(true, 'Previous-week body retracements', group = gReference, inline = 'weekbody', display = display.none, tooltip = 'Previous weekly C - ratio*(C-O), ratios .382/.5/.618. Signed body determines direction; small bodies are suppressed.')
showWeeklyExtend = input.bool(true, 'Previous-week body extensions', group = gReference, inline = 'weekbody', display = display.none, tooltip = 'Previous weekly O + ratio*(C-O), ratios 1.272/1.618/2. No three-pivot ABC pattern or predicted outcome is implied.')
showWeeklyRange = input.bool(true, 'Weekly-range projections: both directions', group = gReference, display = display.none, tooltip = 'This week\'s open +/- previous completed week\'s high-low range * .618/1/1.618. Fixed hypothetical distances, independent of body direction.')
showMonthlyOpen = input.bool(true, 'This month\'s open', group = gReference, display = display.none, tooltip = 'Fixed opening price of the current monthly feed candle. Does not use an unfinished monthly close.')
showMonthlyRetrace = input.bool(true, 'Previous-month body retracements', group = gReference, inline = 'monthbody', display = display.none, tooltip = 'Previous monthly C - ratio*(C-O), ratios .382/.5/.618. Suppresses small bodies using the shared minimum body/range threshold.')
showMonthlyExtend = input.bool(true, 'Previous-month body extensions', group = gReference, inline = 'monthbody', display = display.none, tooltip = 'Previous monthly O + ratio*(C-O), ratios 1.272/1.618/2. Analytical extensions, never automatic take-profit orders.')
showMonthlyRange = input.bool(true, 'Monthly-range projections: both directions', group = gReference, display = display.none, tooltip = 'This month\'s open +/- previous completed month\'s high-low range * .618/1/1.618. Can lie far from current price; compact display hides distant Fib levels.')
minBodyRatio = input.float(0.05, 'Minimum body / period range', minval = 0, maxval = 0.5, step = 0.01, group = gReference, display = display.none, tooltip = 'Suppresses body Fib levels on doji/small-body days; does not change range projections. A zero body is always suppressed.')
showConfluence = input.bool(true, 'Highlight fixed-reference clusters', group = gReference, display = display.none, tooltip = 'Clusters enabled fixed D/W/M body, range and POC families plus the latest valid swing POC. Multiple ratios from one family count once. Opens/developing POCs excluded. Geometric proximity, not probability.')
confluenceATR = input.float(0.1, 'Maximum distance / daily ATR', minval = 0.01, maxval = 0.5, step = 0.01, group = gReference, display = display.none, tooltip = 'Uses yesterday\'s confirmed daily ATR(14). Cluster membership uses fixed reference prices. Nearest displayed clusters follow the selected live/last-close anchor and visual focus radius.')
mapShowAll = input.bool(false, 'Show all enabled Fibonacci levels', group = gReference, display = display.none, tooltip = 'Off: shows the nearest two distinct Fib prices above and below price across D/W/M. Enabled opens and POCs stay visible within the optional focus radius. On: draws all enabled levels and bypasses focus. Calculations do not change.')
mapSelection = input.string('Last closed price', 'Reference selection anchor', options = ['Last closed price', 'Live price'], group = gReference, display = display.none, tooltip = 'Last closed price stabilizes nearest-level selection during an unfinished chart candle. Live price follows every tick. This changes only map selection and dashboard distances, never signal logic or underlying reference prices.')
mapFocus = input.bool(true, 'Focus nearby calendar references', group = gReference, display = display.none, tooltip = 'In compact mode, hides calendar/Fibonacci lines, labels and clusters outside the selected daily-ATR distance. Calculations and nearest-reference dashboard remain available. The latest swing POC is retained. Show all levels overrides this visual filter.')
mapFocusATR = input.float(3.0, 'Focus radius / confirmed daily ATR', minval = 0.25, maxval = 20, step = 0.25, group = gReference, display = display.none, tooltip = 'Visual radius around the selection anchor, using previous completed daily ATR(14). Missing ATR disables this filter. This is not a volatility forecast or trade filter.')
showDailyLabels = input.bool(true, 'All reference-map labels', group = gReference, display = display.none, tooltip = 'Shows merged labels for D/W/M references and swing POC. Hover for exact component prices; turn off to reduce text.')
dailyLabelOffset = input.int(28, 'Reference labels: bars to the right', minval = 1, maxval = 150, group = gReference, display = display.none, tooltip = 'Moves reference labels into the right margin; does not change availability or calculation prices.')
mapMergeATR = input.float(0.025, 'Merge label spacing / confirmed daily ATR', minval = 0, maxval = 0.25, step = 0.005, group = gReference, display = display.none, tooltip = 'Nearby label names are grouped to reduce overlap; original horizontal lines and exact prices remain unchanged and every price is listed in the tooltip. Group span is bounded, never chained across a wide range.')
mapMaxZones = input.int(3, 'Maximum confluence zones', minval = 0, maxval = 6, group = gReference, display = display.none, tooltip = 'Draws nearest qualifying fixed-reference clusters. A cluster needs two distinct source families, e.g. D Body + W POC. Multiple ratios of one family count once. Opens and developing POCs are excluded; geometric proximity is not probability.')
gContext = '05 - Session and context'
sessionHours = input.session('0000-0000', 'Session hours', group = gContext, display = display.none, tooltip = 'One continuous session. Equal start/end means 24 hours. Overnight intervals retain the same identity across midnight. Match your chart bar alignment to both session boundaries.')
sessionDays = input.string('1234567', 'Session days', options = ['1234567', '23456'], group = gContext, display = display.none, tooltip = 'TradingView session day notation: 1 Sunday through 7 Saturday. All days suits continuous markets; weekdays uses 23456. Overnight day membership follows TradingView session semantics.')
sessionZone = input.string('Etc/UTC', 'Session timezone', options = ['Etc/UTC', 'America/New_York', 'Europe/London', 'Europe/Bucharest', 'Asia/Tokyo', 'Exchange'], group = gContext, display = display.none, tooltip = 'Named IANA zones follow daylight-saving rules. Exchange uses the symbol timezone. This is independent of the chart display timezone.')
showSessionVWAP = input.bool(true, 'Session VWAP line', group = gContext, display = display.none, tooltip = 'Sum(HLC3*volume)/sum(volume) from full closed chart candles. Missing/negative volume invalidates the current session VWAP. Zero cumulative volume shows no value. Developing session VWAP can change after each candle close.')
showSessionLevels = input.bool(true, 'Session open and prior high/low', group = gContext, display = display.none, tooltip = 'Only fully observed sessions can produce prior-session high/low. Missing volume disables VWAP but does not by itself invalidate OHLC levels. Minimal preset hides these three plots.')
stLength = input.int(10, 'ATR length', minval = 1, maxval = 200, group = gContext, display = display.none, tooltip = 'ATR lookback for Supertrend context. Independent of the ZigZag reversal ATR.')
stFactor = input.float(3.0, 'ATR multiplier', minval = 0.1, maxval = 20, step = 0.1, group = gContext, display = display.none, tooltip = 'Larger values normally keep Supertrend farther from price. Agreement with ZigZag is context, not independent confirmation or a success probability.')
earlyWarning = input.bool(true, 'Show provisional reversal warning', group = gContext, display = display.none, tooltip = 'Provisional intrabar preview; can disappear. Does not trigger execution alerts.')
warningATR = input.float(0.25, 'Warning proximity (ATR)', minval = 0, maxval = 2, step = 0.05, group = gContext, display = display.none, tooltip = 'Amber preview near the reversal level when slope agrees. Intrabar only; can disappear. Never sends an execution alert.')
chopThreshold = input.float(0.25, 'Sideways: efficiency below', minval = 0.01, maxval = 0.8, step = 0.01, group = gContext, display = display.none, tooltip = 'Efficiency below this value is classified as sideways. Informational; does not block reversals.')
shadeChop = input.bool(false, 'Full-height sideways shading (optional)', group = gContext, display = display.none, tooltip = 'Optional full-height background shading. Off by default to keep the chart clean; dashboard warnings remain available.')
gEvidence = '06 - Research'
showQuality = input.bool(true, 'Data-quality panel', group = gEvidence, display = display.none, tooltip = 'Shows loaded-history chart-candle fallback and missing-volume counts, ring-buffer sample count, calendar source and POC availability. Counts are data diagnostics, not accuracy scores.')
showSnapshots = input.bool(true, 'Capture confirmed signal snapshots', group = gEvidence, display = display.none, tooltip = 'Copies values known on the BUY/SELL confirmation close: swing/calendar POCs, nearest enabled Fib above/below, Supertrend, session VWAP and quality flags. This is an audit record, not a hindsight target or broker fill.')
snapshotKeep = input.int(50, 'Snapshots retained', minval = 1, maxval = 100, group = gEvidence, display = display.none, tooltip = 'Bounded records from loaded chart history. Values freeze at each signal close. Reloading changed source data or inputs reconstructs the history; this is not permanent external storage.')
snapshotBack = input.int(0, 'Inspect snapshot: 0 = newest', minval = 0, maxval = 99, group = gEvidence, display = display.none, tooltip = 'Select an older retained snapshot in the research panel and Data Window. An unavailable index shows no record instead of substituting another signal.')
showReactions = input.bool(true, 'Track first eligible reference touches', group = gEvidence, display = display.none, tooltip = 'Tracks seven enabled reference streams: swing POC, D/W/M POC and D/W/M body retracement .618. One first eligible range-overlap touch per source-period/level identity. Counts overlapping observations, not independent trades or predictive probabilities.')
reactionSourceView = input.string('All', 'Reaction source', options = ['All', 'Swing POC', 'D POC', 'W POC', 'M POC', 'D RET .618', 'W RET .618', 'M RET .618'], group = gEvidence, display = display.none, tooltip = 'Selects a source subset of the same global rolling resolved window. It does not collect an independent N observations per source or change first-touch rules.')
reactionApproachView = input.string('Both', 'Reaction approach', options = ['Both', 'From above', 'From below'], group = gEvidence, display = display.none, tooltip = 'From above studies upward support reactions; From below studies downward resistance reactions. Counts remain overlapping observations, not trading win probabilities.')
reactionBars = input.int(12, 'Reaction evaluation bars after touch', minval = 1, maxval = 100, group = gEvidence, display = display.none, tooltip = 'Evaluate the NEXT 1..N closed chart candles; the touch candle is excluded because its extremes may precede contact. Existing observations retain their frozen level and thresholds even when reference sets change.')
reactionMoveATR = input.float(0.5, 'Reaction distance / chart ATR', minval = 0.05, maxval = 5, step = 0.05, group = gEvidence, inline = 'reactionDistance', display = display.none, tooltip = 'Freeze chart ATR at the touch candle close. Approach from above tests an upward reaction; approach from below tests a downward reaction. Requires previous close AND touch-bar open strictly on the same side. Gap-through returns and opening exactly at the level are excluded. Gaps without range overlap are not touches.')
reactionFailATR = input.float(0.5, 'Failure distance / chart ATR', minval = 0.05, maxval = 5, step = 0.05, group = gEvidence, inline = 'reactionDistance', display = display.none, tooltip = 'Freeze adverse distance at the touch candle close. If both reaction and failure thresholds occur within the same later candle, record AMBIGUOUS. No intrabar event order is assumed.')
reactionKeep = input.int(200, 'Resolved observations retained', minval = 20, maxval = 1000, group = gEvidence, display = display.none, tooltip = 'Rolling last N resolved observations in resolution order. R = reaction, F = failure, A = ambiguous, E = expired, X = invalid OHLC. Pending observations are separate. These counts do not include fees or represent trading returns.')
showStats = input.bool(true, 'Show statistics panel', group = gEvidence, display = display.none, tooltip = 'Displays modeled, unleveraged signal-trade statistics. Never verifies profitability or broker fills.')
statsWindow = input.int(200, 'Most recent completed trades', minval = 10, maxval = 1000, group = gEvidence, display = display.none, tooltip = 'Rolling sample of completed signal trades from loaded chart history, not a forward-tested broker record.')
gVisual = '07 - Appearance'
signalHistory = input.int(8, 'Recent trades with BUY / SELL text', minval = 1, maxval = 100, group = gVisual, display = display.none, tooltip = 'Limits BUY/SELL text only. Historical calculations and statistics are retained.')
showWarningLabel = input.bool(false, 'Floating early-warning label', group = gVisual, display = display.none, tooltip = 'Warning remains visible in the dashboard when this is off.')
historyFade = input.int(65, 'Historical swing transparency', minval = 0, maxval = 95, group = gVisual, display = display.none, tooltip = 'Transparency of older swing drawings. Higher values reduce historical clutter without changing calculations.')
focusTrades = input.int(2, 'Highlighted recent trades', minval = 1, maxval = 10, group = gVisual, display = display.none, tooltip = 'Number of recent trades kept bright. Older visual objects are faded according to historical transparency.')
showLiveText = input.bool(false, 'Show developing-swing price text', group = gVisual, display = display.none, tooltip = 'Optional text at the unconfirmed developing endpoint. Can change on every realtime update.')
cardPosition = input.string('Top right', 'Dashboard position', options = ['Top right', 'Bottom right', 'Top left', 'Bottom left'], group = gVisual, display = display.none, tooltip = 'Choose a chart corner for the dashboard. Visual placement only.')
palette = input.string('Emerald / Ruby', 'Palette', options = ['Emerald / Ruby', 'Ice / Coral', 'Custom'], group = gVisual, display = display.none, tooltip = 'Choose directional colors; Custom uses your Long/Short color inputs.')
uiTheme = input.string('Dark', 'Panel theme', options = ['Dark', 'Light'], group = gVisual, display = display.none, tooltip = 'Panel contrast for a dark or light chart background. Does not change the chart background itself.')
extremeHistory = input.int(2, 'Recent trades with HIGH / LOW text', minval = 1, maxval = 20, group = gVisual, display = display.none, tooltip = 'Older ZigZag endpoints remain visible; this limits price text to reduce clutter.')
markerGap = input.float(1.0, 'Signal label spacing (ATR)', minval = 0.1, maxval = 3, step = 0.1, group = gVisual, display = display.none, tooltip = 'Moves signal text away from candles; the leader/dot still marks the exact signal-close reference.')
showSignalPrice = input.bool(false, 'Print price inside BUY / SELL labels', group = gVisual, display = display.none, tooltip = 'Exact confirmation price always remains in the tooltip and on the signal dot.')
showZone = input.bool(false, 'Subtle directional zone', group = gVisual, display = display.none, tooltip = 'Optional translucent visual fill. Does not add a filter or an order condition.')
zigWidth = input.int(2, 'ZigZag width', minval = 1, maxval = 5, group = gVisual, display = display.none, tooltip = 'Width of the primary confirmed ZigZag line; the optional halo is wider and translucent.')
history = input.int(50, 'Completed trades to display', minval = 5, maxval = 100, group = gVisual, display = display.none, tooltip = 'Maximum visual history; has no effect on the rolling statistics window.')
showExtremes = input.bool(true, 'Exact HIGH / LOW of each signal trade', group = gVisual, display = display.none, tooltip = 'Measured from entry-signal close through exit-signal close. Entry candle\'s earlier wicks are excluded. Labels appear only after exit confirmation; these are not broker fills.')
showLevels = input.bool(true, 'Latest entry and confirmation levels', group = gVisual, display = display.none, tooltip = 'Latest signal entry-close and effective reversal threshold. These are not orders resting at a broker.')
showTradePath = input.bool(false, 'Dotted entry-to-exit connectors', group = gVisual, display = display.none, tooltip = 'Connects consecutive signal closes. Do not confuse these with the retrospective ZigZag extremes.')
showGlow = input.bool(true, 'Soft ZigZag halo', group = gVisual, display = display.none, tooltip = 'Adds a soft, transparent halo to swing segments. Turn off for a thinner technical drawing.')
showJurik = input.bool(false, 'Jurik ribbon', group = gVisual, display = display.none, tooltip = 'Displays the underlying smoother; visual toggle only, the filter continues calculating when hidden.')
labelOffset = input.int(8, 'Right-side label offset', minval = 1, maxval = 100, group = gVisual, display = display.none, tooltip = 'Horizontal offset for the latest entry, reversal and POC price tags. No lookahead is used in signal logic.')
showZZ = input.bool(true, 'Confirmed swing segments', group = gVisual, display = display.none, tooltip = 'Confirmed historical geometry appears after a reversal. Endpoints are retrospective, not executable hindsight trades.')
showLive = input.bool(true, 'Developing swing (can move)', group = gVisual, display = display.none, tooltip = 'Dotted developing geometry can move until confirmed. It never backdates a BUY or SELL.')
showTrail = input.bool(true, 'Reversal threshold', group = gVisual, display = display.none, tooltip = 'Displays the effective reversal threshold including the configured cost floor. Crossing still requires closed-bar confirmation.')
paintBars = input.bool(false, 'Color candles', group = gVisual, display = display.none, tooltip = 'Colors candles by the confirmed logical signal state; does not replace your chart\'s price data.')
showPanel = input.bool(true, 'Status panel', group = gVisual, display = display.none, tooltip = 'Displays state, cost assumptions, POC status and daily-level availability. Broker fills remain unverified.')
customUp = input.color(color.rgb(0, 220, 160), 'Long', group = gVisual, display = display.none, tooltip = 'Used for long/upward drawings only when Palette is Custom.')
customDown = input.color(color.rgb(255, 75, 100), 'Short', group = gVisual, display = display.none, tooltip = 'Used for short/downward drawings only when Palette is Custom.')
profileWidth = input.float(0.3, 'Histogram width / swing duration', minval = 0.1, maxval = 0.7, step = 0.05, group = gVisual, display = display.none, tooltip = 'Fraction of the completed swing\'s time span occupied by the largest volume row. Purely visual.')
profileOpacity = input.int(88, 'Histogram transparency', minval = 50, maxval = 98, group = gVisual, display = display.none, tooltip = 'Higher values make histogram rows fainter; the maximum-volume POC row remains emphasized.')
researchPosition = input.string('Bottom left', 'Research panel position', options = ['Top left', 'Bottom left', 'Top right', 'Bottom right'], group = gVisual, display = display.none, tooltip = 'Choose a different corner from the main status panel. Visible only in Analysis preset; calculations continue in all presets.')
gAdvanced = '08 - Advanced tuning'
src = input.source(ohlc4, 'Source', group = gAdvanced, display = display.none, tooltip = 'Price series for the Jurik-style filter. Source choice changes reversal timing.')
length = input.int(10, 'Smoother length', minval = 2, maxval = 200, group = gAdvanced, inline = 'shape', display = display.none, tooltip = 'Longer smooths more and usually delays turns; shorter reacts faster with more noise.')
phase = input.int(50, 'Phase', minval = -100, maxval = 100, group = gAdvanced, inline = 'shape', display = display.none, tooltip = 'Adjusts filter responsiveness/overshoot. This does not remove delay or make turning points predictable.')
power = input.float(2.0, 'Power', minval = 0.5, maxval = 5, step = 0.25, group = gAdvanced, inline = 'shape', display = display.none, tooltip = 'Controls the Jurik-style filter response. Keep fixed while evaluating other parameters.')
atrLen = input.int(14, 'ATR length', minval = 2, group = gAdvanced, display = display.none, tooltip = 'Volatility window for the reversal threshold; not a stop-loss order.')
adaptive = input.bool(true, 'Widen threshold in efficient trends', group = gAdvanced, display = display.none, tooltip = 'Widens the threshold in more efficient trends to tolerate pullbacks.')
erLen = input.int(10, 'Trend efficiency length', minval = 2, maxval = 100, group = gAdvanced, display = display.none, tooltip = 'Window used to measure net price movement relative to total movement.')
expansion = input.float(0.5, 'Maximum trend expansion', minval = 0, maxval = 2, step = 0.1, group = gAdvanced, display = display.none, tooltip = 'Maximum fractional expansion of ATR width at full trend efficiency.')
requireSlope = input.bool(true, 'Require smoother slope confirmation', group = gAdvanced, display = display.none, tooltip = 'Requires the smoother to slope toward the new direction unless strong-reversal bypass applies.')
fastBreak = input.bool(true, 'Strong reversal bypasses slope filter', group = gAdvanced, display = display.none, tooltip = 'Allows a sufficiently large close beyond the threshold to bypass slope confirmation; still waits for candle close.')
breakExtra = input.float(0.5, 'Strong reversal: extra ATR', minval = 0.1, step = 0.1, group = gAdvanced, display = display.none, tooltip = 'Extra ATR distance beyond the effective threshold needed for the slope bypass.')
profileCapacity = input.int(6000, 'Maximum stored volume samples', minval = 1000, maxval = 20000, step = 1000, group = gAdvanced, display = display.none, tooltip = 'Circular buffer. If a required boundary sample was overwritten, the whole profile is skipped. Bigger buffers use more memory/runtime.')
calCapacity = input.int(4000, 'Samples per calendar period', minval = 1000, maxval = 8000, step = 1000, group = gAdvanced, display = display.none, tooltip = 'Default supports a complete 31-day month of 15m candles. Overflow invalidates the entire period. New completed POCs are released after the first source candle of the following period closes, then mapped at the next source open. Trading-session gaps can delay availability further.')
upColor = palette == 'Custom' ? customUp : palette == 'Ice / Coral' ? color.rgb(54, 192, 238) : color.rgb(24, 209, 155)
dnColor = palette == 'Custom' ? customDown : palette == 'Ice / Coral' ? color.rgb(255, 115, 100) : color.rgb(242, 84, 119)
panelBg = uiTheme == 'Dark' ? color.rgb(15, 21, 31) : color.rgb(247, 249, 252)
panelHeader = uiTheme == 'Dark' ? color.rgb(26, 35, 49) : color.rgb(228, 234, 242)
textMain = uiTheme == 'Dark' ? color.rgb(231, 238, 247) : color.rgb(32, 44, 61)
textMuted = uiTheme == 'Dark' ? color.rgb(139, 154, 175) : color.rgb(98, 113, 132)
profileVisible = showProfile and viewPreset != 'Minimal'
mapLabelsVisible = showDailyLabels and viewPreset != 'Minimal'
fullPanel = showPanel and viewPreset == 'Analysis'
metricsVisible = showStats and viewPreset == 'Analysis'
roundTripCost = feePct * 2.0 + spreadPct + slipPct * 2.0
costsSet = roundTripCost > 0
amber = color.rgb(240, 184, 76)
f_threshold(_side, _trail, _extreme) =>
costDistance = math.abs(_extreme) * roundTripCost * costBuffer / 100.0
costLevel = _extreme - _side * costDistance
costFilter ? _side == 1 ? math.min(_trail, costLevel) : math.max(_trail, costLevel) : _trail
f_jma(_src, _len, _phase, _power) =>
pr = _phase / 100.0 + 1.5
beta = 0.45 * (_len - 1) / (0.45 * (_len - 1) + 2.0)
alpha = math.pow(beta, _power)
float e0 = na
float e1 = na
float e2 = na
float jm = na
e0 := (1.0 - alpha) * _src + alpha * nz(e0[1], _src)
e1 := (_src - e0) * (1.0 - beta) + beta * nz(e1[1], 0.0)
e2 := (e0 + pr * e1 - nz(jm[1], _src)) * math.pow(1.0 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1], 0.0)
jm := e2 + nz(jm[1], _src)
jm
jm = f_jma(src, length, phase, power)
atr = ta.atr(atrLen)
path = ta.sma(math.abs(ta.change(close)), erLen) * erLen
efficiency = not na(path) and path > 0 ? math.min(1.0, math.abs(close - close[erLen]) / path) : 0.0
width = math.max(syminfo.mintick, atr * distance * (adaptive ? 1.0 + expansion * efficiency : 1.0))
isChop = efficiency < chopThreshold
ready = close > 0 and bar_index >= math.max(length * 3, math.max(atrLen, erLen)) and not na(width) and not na(jm[1])
type VolumeSample
int parent
float hi
float lo
float vol
bool fallback
var array<VolumeSample> volumeSamples = array.new<VolumeSample>()
var int volumeHead = 0
var int droppedParent = na
var array<box> profileBoxes = array.new_box()
var array<int> profileBoxCounts = array.new_int()
var array<line> profileLines = array.new_line()
var array<label> profileTags = array.new_label()
var float latestPOC = na
var int latestPOCConfirmed = na
var string profileStatus = 'Waiting for two endpoints'
var line extendedPOC = na
var label extendedPOCTag = na
f_store_sample(int _head, VolumeSample _sample) =>
nextHead = _head
int removedParent = na
if array.size(volumeSamples) < profileCapacity
array.push(volumeSamples, _sample)
else
removedSample = array.get(volumeSamples, _head)
removedParent := removedSample.parent
array.set(volumeSamples, _head, _sample)
nextHead := (_head + 1) % profileCapacity
nextHead
[nextHead, removedParent]
var int diagBars = 0
var int diagFallback = 0
var int diagMissing = 0
var string diagSource = 'Waiting for closed candle'
[vpHigh, vpLow, vpVolume] = request.security_lower_tf(syminfo.tickerid, profileTF, [high, low, volume], ignore_invalid_timeframe = true)
if showPOC and barstate.isconfirmed
diagBars := diagBars + 1
diagMissing := diagMissing + (na(volume) or volume < 0 ? 1 : 0)
intrabars = array.size(vpHigh)
lowerOK = timeframe.in_seconds(profileTF) < timeframe.in_seconds() and intrabars > 0
float lowerVolume = 0.0
if lowerOK
for i = 0 to intrabars - 1 by 1
v = array.get(vpVolume, i)
if na(v) or v < 0 or na(array.get(vpHigh, i)) or na(array.get(vpLow, i)) or array.get(vpHigh, i) < array.get(vpLow, i)
lowerOK := false
lowerOK
lowerVolume := lowerVolume + nz(v)
lowerVolume
lowerOK := lowerOK and not na(volume) and math.abs(lowerVolume - volume) <= math.max(math.abs(volume) * 0.02, 0.00000001)
lowerOK
diagSource := lowerOK ? profileTF + ' TF intrabars' : 'Chart fallback'
diagFallback := diagFallback + (lowerOK ? 0 : 1)
if lowerOK
for i = 0 to intrabars - 1 by 1
[nextHead, removed] = f_store_sample(volumeHead, VolumeSample.new(time, array.get(vpHigh, i), array.get(vpLow, i), array.get(vpVolume, i), false))
volumeHead := nextHead
if not na(removed)
droppedParent := removed
droppedParent
else
[nextHead, removed] = f_store_sample(volumeHead, VolumeSample.new(time, high, low, volume, true))
volumeHead := nextHead
if not na(removed)
droppedParent := removed
droppedParent
var int side = 0
var float extreme = na
var int extremeTime = na
var int extremeIndex = na
var float trail = na
var float anchorPrice = na
var int anchorTime = na
var bool anchorConfirmed = false
var float entryPrice = na
var int entryTime = na
var int entryTimeClose = na
var int entryIndex = na
var float tradeHigh = na
var float tradeLow = na
var int highTime = na
var int lowTime = na
var int highIndex = na
var int lowIndex = na
var int lastDelay = na
var int tradeNumber = 0
var array<float> netResults = array.new_float()
var array<float> holdBars = array.new_float()
var array<float> holdMinutes = array.new_float()
var array<float> favorable = array.new_float()
var array<float> adverse = array.new_float()
var int wins = 0
var float winningSum = 0.0
var float losingSum = 0.0
var float lastNet = na
var float lastMFE = na
var float lastMAE = na
var int totalCompleted = 0
var array<line> drawings = array.new_line()
var array<color> drawingColors = array.new_color()
var array<int> drawingTrades = array.new_int()
var array<label> markers = array.new_label()
var array<color> markerColors = array.new_color()
var array<color> markerTextColors = array.new_color()
var array<int> markerTrades = array.new_int()
var array<bool> markerSignals = array.new_bool()
var array<label> extremeMarkers = array.new_label()
f_line(_x1, _y1, _x2, _y2, _color, _style, _width) =>
obj = line.new(_x1, _y1, _x2, _y2, xloc = xloc.bar_time, color = _color, style = _style, width = _width)
array.push(drawings, obj)
array.push(drawingColors, _color)
array.push(drawingTrades, tradeNumber)
obj
f_label(_x, _y, _text, _style, _color, _textColor, _size, _tooltip) =>
obj = label.new(_x, _y, _text, xloc = xloc.bar_time, yloc = yloc.price, style = _style, color = _color, textcolor = _textColor, size = _size, tooltip = _tooltip)
array.push(markers, obj)
array.push(markerColors, _color)
array.push(markerTextColors, _textColor)
array.push(markerTrades, tradeNumber)
array.push(markerSignals, _style == label.style_label_up or _style == label.style_label_down)
obj
f_extreme(_x, _y, _text, _style, _color, _tooltip) =>
obj = label.new(_x, _y, _text, xloc = xloc.bar_time, yloc = yloc.price, style = _style, color = color.new(_color, 100), textcolor = _color, size = size.small, tooltip = _tooltip)
array.push(extremeMarkers, obj)
while array.size(extremeMarkers) > extremeHistory * 2
label.delete(array.shift(extremeMarkers))
obj
f_price(_value) =>
na(_value) ? '--' : str.tostring(_value, format.mintick)
f_profile(int _start, int _end, int _confirmed) =>
float result = na
string status = 'Unavailable'
int stored = array.size(volumeSamples)
bool complete = stored > 0 and (na(droppedParent) or droppedParent < _start)
array<VolumeSample> selected = array.new<VolumeSample>()
float rangeLow = na
float rangeHigh = na
bool hasMissing = false
bool hasFallback = false
if complete
for i = 0 to stored - 1 by 1
idx = (volumeHead - 1 - i + stored * 2) % stored
idx := stored < profileCapacity ? stored - 1 - i : idx
rec = array.get(volumeSamples, idx)
if rec.parent < _start
break
if rec.parent <= _end
array.push(selected, rec)
rangeLow := na(rangeLow) ? rec.lo : math.min(rangeLow, rec.lo)
rangeHigh := na(rangeHigh) ? rec.hi : math.max(rangeHigh, rec.hi)
hasMissing := hasMissing or na(rec.vol) or rec.vol < 0 or na(rec.hi) or na(rec.lo)
hasFallback := hasFallback or rec.fallback
hasFallback
if not complete
status := 'Skipped: buffer too short'
status
else if array.size(selected) == 0 or hasMissing
status := 'Skipped: missing price/volume'
status
else
stepSize = math.max((rangeHigh - rangeLow) / profileRows, syminfo.mintick)
bottom = rangeHigh == rangeLow ? rangeLow - stepSize * 0.5 : rangeLow
bins = array.new_float(profileRows, 0.0)
diff = array.new_float(profileRows + 1, 0.0)
for rec in selected
first = math.max(0, math.min(profileRows - 1, int(math.floor((rec.lo - bottom) / stepSize))))
last = math.max(0, math.min(profileRows - 1, int(math.floor((rec.hi - bottom) / stepSize))))
if rec.hi <= rec.lo or first == last
array.set(bins, first, array.get(bins, first) + rec.vol)
else
density = rec.vol / (rec.hi - rec.lo)
leftVolume = math.max(0.0, bottom + (first + 1) * stepSize - rec.lo) * density
rightVolume = math.max(0.0, rec.hi - (bottom + last * stepSize)) * density
array.set(bins, first, array.get(bins, first) + leftVolume)
array.set(bins, last, array.get(bins, last) + rightVolume)
if last - first > 1
fullRow = density * stepSize
array.set(diff, first + 1, array.get(diff, first + 1) + fullRow)
array.set(diff, last, array.get(diff, last) - fullRow)
float running = 0.0
float largest = 0.0
int peak = 0
for r = 0 to profileRows - 1 by 1
running := running + array.get(diff, r)
value = math.max(0.0, array.get(bins, r) + running)
array.set(bins, r, value)
if value > largest
largest := value
peak := r
peak
if largest <= 0
status := 'Skipped: no positive volume'
status
else
result := bottom + (peak + 0.5) * stepSize
status := hasFallback ? 'Chart/mixed approximation' : 'LTF approximation'
while array.size(profileLines) >= profileKeep
line.delete(array.shift(profileLines))
label.delete(array.shift(profileTags))
oldBoxes = array.shift(profileBoxCounts)
if oldBoxes > 0
for j = 0 to oldBoxes - 1 by 1
box.delete(array.shift(profileBoxes))
int made = 0
if profileVisible
for r = 0 to profileRows - 1 by 1
weight = array.get(bins, r) / largest
rightTime = _start + int((_end - _start) * profileWidth * weight)
rowBottom = bottom + r * stepSize
shade = r == peak ? color.new(amber, 55) : color.new(textMuted, profileOpacity)
rowBox = box.new(_start, rowBottom + stepSize, rightTime, rowBottom, xloc = xloc.bar_time, border_color = color.new(amber, 100), bgcolor = shade)
array.push(profileBoxes, rowBox)
made := made + 1
made
array.push(profileBoxCounts, made)
array.push(profileLines, line.new(_start, result, _end, result, xloc = xloc.bar_time, color = amber, width = 2))
tip = 'CONFIRMED SWING POC (estimate)\n' + status + '\nConfirmation close (feed timezone): ' + str.format_time(_confirmed, 'yyyy-MM-dd HH:mm', syminfo.timezone) + '\n' + str.tostring(array.size(selected)) + ' source candles; ' + str.tostring(profileRows) + ' rows.\nFull endpoint candles included. Highest-volume row midpoint; uniform OHLC allocation.\nKnown only on reversal confirmation, not at the historical endpoint.'
array.push(profileTags, label.new(_end, result, 'POC ' + f_price(result), xloc = xloc.bar_time, style = label.style_label_left, color = color.new(amber, 100), textcolor = amber, size = size.tiny, tooltip = tip))
[result, status]
bool buy = false
bool sell = false
bool reversed = false
if ready and barstate.isconfirmed
if side == 0
if jm != jm[1]
side := jm > jm[1] ? 1 : -1
buy := side == 1
sell := side == -1
anchorPrice := close
anchorTime := time
anchorTime
else // Equal highs/lows retain their first occurrence.
if high > tradeHigh
tradeHigh := high
highTime := time
highIndex := bar_index
highIndex
if low < tradeLow
tradeLow := low
lowTime := time
lowIndex := bar_index
lowIndex
extreme := side == 1 ? tradeHigh : tradeLow
extremeTime := side == 1 ? highTime : lowTime
extremeIndex := side == 1 ? highIndex : lowIndex
trail := side == 1 ? math.max(trail, extreme - width) : math.min(trail, extreme + width)
slopeOK = not requireSlope or (side == 1 ? jm < jm[1] : jm > jm[1])
trigger = f_threshold(side, trail, extreme)
hardBreak = fastBreak and (side == 1 ? close < trigger - atr * breakExtra : close > trigger + atr * breakExtra)
crossed = side == 1 ? close < trigger : close > trigger
if crossed and (slopeOK or hardBreak)
reversed := true
grossReturn = side * (close - entryPrice) / entryPrice * 100.0
lastNet := grossReturn - roundTripCost
lastMFE := math.max(0.0, (side == 1 ? tradeHigh - entryPrice : entryPrice - tradeLow) / entryPrice * 100.0)
lastMAE := math.max(0.0, (side == 1 ? entryPrice - tradeLow : tradeHigh - entryPrice) / entryPrice * 100.0)
array.push(netResults, lastNet)
array.push(holdBars, float(bar_index - entryIndex))
array.push(holdMinutes, (time_close - entryTimeClose) / 60000.0)
array.push(favorable, lastMFE)
array.push(adverse, lastMAE)
totalCompleted := totalCompleted + 1
wins := wins + (lastNet > 0 ? 1 : 0)
winningSum := winningSum + math.max(lastNet, 0.0)
losingSum := losingSum + math.max(-lastNet, 0.0)
if array.size(netResults) > statsWindow
removed = array.shift(netResults)
wins := wins - (removed > 0 ? 1 : 0)
winningSum := math.max(0.0, winningSum - math.max(removed, 0.0))
losingSum := math.max(0.0, losingSum - math.max(-removed, 0.0))
array.shift(holdBars)
array.shift(holdMinutes)
array.shift(favorable)
array.shift(adverse)
legColor = side == 1 ? upColor : dnColor
lastDelay := bar_index - extremeIndex
if showZZ and extremeTime >= anchorTime
legStyle = anchorConfirmed ? line.style_solid : line.style_dashed
if showGlow
f_line(anchorTime, anchorPrice, extremeTime, extreme, color.new(legColor, 88), legStyle, zigWidth + 6)
f_line(anchorTime, anchorPrice, extremeTime, extreme, legColor, legStyle, zigWidth)
f_label(extremeTime, extreme, '•', label.style_none, color.new(legColor, 100), legColor, size.small, 'Swing endpoint confirmed ' + str.tostring(lastDelay) + ' bar(s) later. Signal is on the confirmation candle.')
if showExtremes
intervalTip = 'Signal trade #' + str.tostring(tradeNumber) + ' | ' + (side == 1 ? 'LONG' : 'SHORT') + '\nEntry close: ' + f_price(entryPrice) + '\nExit close: ' + f_price(close) + '\nDuration: ' + str.tostring(bar_index - entryIndex) + ' bars\nModeled net: ' + str.tostring(lastNet, '#.###') + '%\nMFE / MAE: ' + str.tostring(lastMFE, '#.###') + '% / ' + str.tostring(lastMAE, '#.###') + '%\nConfirmed on this trade\'s exit. Historical extreme, not an entry/exit fill. Entry candle pre-entry wicks excluded.'
f_extreme(highTime, tradeHigh, 'H ' + f_price(tradeHigh), label.style_label_down, dnColor, intervalTip + '\nHIGH occurred ' + str.tostring(bar_index - highIndex) + ' bar(s) before confirmation.')
f_extreme(lowTime, tradeLow, 'L ' + f_price(tradeLow), label.style_label_up, upColor, intervalTip + '\nLOW occurred ' + str.tostring(bar_index - lowIndex) + ' bar(s) before confirmation.')
if showTradePath
f_line(entryTime, entryPrice, time, close, color.new(color.silver, 45), line.style_dotted, 1)
if showPOC and anchorConfirmed and extremeTime > anchorTime
[newPOC, newStatus] = f_profile(anchorTime, extremeTime, time_close)
profileStatus := newStatus + (na(newPOC) and not na(latestPOC) ? ' | Prior valid POC retained' : '')
if not na(newPOC)
latestPOC := newPOC
latestPOCConfirmed := time_close
line.delete(extendedPOC)
extendedPOC := line.new(time_close, newPOC, time_close + 1, newPOC, xloc = xloc.bar_time, extend = extend.right, style = line.style_dotted, color = color.new(amber, 25), width = 1)
extendedPOC
anchorPrice := extreme
anchorTime := extremeTime
anchorConfirmed := true
side := -side
buy := side == 1
sell := side == -1
sell
if buy or sell
tradeNumber := tradeNumber + 1
entryPrice := close
entryTime := time
entryTimeClose := time_close
entryIndex := bar_index
tradeHigh := close
tradeLow := close
highTime := time
lowTime := time
highIndex := bar_index
lowIndex := bar_index
extreme := close
extremeTime := time
extremeIndex := bar_index
trail := side == 1 ? close - width : close + width
if showSignals
signalText = (buy ? 'BUY' : 'SELL') + (showSignalPrice ? '\n' + f_price(close) : '')
signalTip = (reversed ? 'Close opposite position, then request ' : 'Initial signal: request ') + (buy ? 'LONG' : 'SHORT') + '\nSignal #' + str.tostring(tradeNumber) + ' | Close: ' + f_price(close) + '\nCandle-close signal. This price is a reference, not a broker fill.'
signalY = buy ? low - atr * markerGap : high + atr * markerGap
f_line(time, close, time, signalY, color.new(buy ? upColor : dnColor, 70), line.style_dotted, 1)
f_label(time, signalY, signalText, buy ? label.style_label_up : label.style_label_down, buy ? upColor : dnColor, buy ? color.rgb(9, 24, 31) : color.white, size.small, signalTip)
while array.size(drawings) > history * ((showZZ ? showGlow ? 2 : 1 : 0) + (showTradePath ? 1 : 0) + (showSignals ? 1 : 0))
line.delete(array.shift(drawings))
array.shift(drawingColors)
array.shift(drawingTrades)
while array.size(markers) > history * ((showZZ ? 1 : 0) + (showSignals ? 1 : 0)) + (showSignals ? 1 : 0)
label.delete(array.shift(markers))
array.shift(markerColors)
array.shift(markerTextColors)
array.shift(markerTrades)
array.shift(markerSignals)
if array.size(drawings) > 0
for i = 0 to array.size(drawings) - 1 by 1
baseColor = array.get(drawingColors, i)
faded = array.get(drawingTrades, i) < tradeNumber - focusTrades
line.set_color(array.get(drawings, i), color.new(baseColor, faded ? math.max(color.t(baseColor), historyFade) : color.t(baseColor)))
if array.size(markers) > 0
for i = 0 to array.size(markers) - 1 by 1
baseColor = array.get(markerColors, i)
baseText = array.get(markerTextColors, i)
faded = array.get(markerTrades, i) < tradeNumber - focusTrades
hidden = array.get(markerSignals, i) and array.get(markerTrades, i) <= tradeNumber - signalHistory
label.set_color(array.get(markers, i), color.new(baseColor, hidden ? 100 : faded ? math.max(color.t(baseColor), historyFade) : color.t(baseColor)))
label.set_textcolor(array.get(markers, i), color.new(baseText, hidden ? 100 : faded ? historyFade : color.t(baseText)))
activeThreshold = side != 0 ? f_threshold(side, trail, extreme) : na
previewExtreme = side == 1 ? math.max(nz(extreme, high), high) : math.min(nz(extreme, low), low)
previewTrail = side == 1 ? math.max(nz(trail, previewExtreme - width), previewExtreme - width) : math.min(nz(trail, previewExtreme + width), previewExtreme + width)
previewThreshold = f_threshold(side, previewTrail, previewExtreme)
previewSlopeOK = not requireSlope or (side == 1 ? jm < jm[1] : jm > jm[1])
previewHardBreak = fastBreak and (side == 1 ? close < previewThreshold - atr * breakExtra : close > previewThreshold + atr * breakExtra)
previewNear = side == 1 ? close <= previewThreshold + atr * warningATR : close >= previewThreshold - atr * warningATR
warning = earlyWarning and ready and side != 0 and barstate.isrealtime and not barstate.isconfirmed and previewNear and (previewSlopeOK or previewHardBreak)
bgcolor(shadeChop and ready and isChop ? color.new(amber, 97) : na, title = 'Sideways caution')
trendColor = side == 1 ? upColor : side == -1 ? dnColor : color.gray
pJ = plot(showJurik ? jm : na, 'Jurik', color = color.new(trendColor, 10), linewidth = 2)
pC = plot(close, 'Fill reference', display = display.none)
fill(pJ, pC, color = showZone ? color.new(trendColor, 96) : na, title = 'Jurik ribbon')
pLong = plot(showTrail and side == 1 and not buy ? activeThreshold : na, 'Long confirmation threshold', color = color.new(upColor, 20), linewidth = 1,Показано первые 50% кода (символов: 86057)