Buy Point % LevelsBuy Point % Levels
Overview
Buy Point % Levels is a visual planning tool for position management. Once you've bought (or plan to buy) a stock at a given price, it draws a horizontal "Buy" line at that price plus a set of dashed stop-loss and take-profit lines, each expressed as a percentage above or below your buy point. Every line is labeled on the right with its percentage and the exact price it corresponds to, so you can see your risk/reward levels laid out on the chart at a glance.
It does not generate buy/sell signals, plot historical markers, or fire alerts — it's a reference overlay for a position you already have in mind, redrawn fresh on the most recent bar each time the chart updates.
How the buy price is determined
The script figures out your buy price in this order of priority:
1. Positions list match — if the current chart's ticker appears in the "Positions" input (see below), that price is used automatically, regardless of any other setting.
2. Manual override — if the ticker isn't in the Positions list and "Manual Override" is checked, the script uses the Buy Price input/line. The first time you use it, that line starts at the last close — drag it on the chart or type an exact value to set your real entry.
3. Default (tracking mode) — if neither of the above applies, the buy point defaults to the current/last close and moves with the price on every bar. This is the out-of-the-box behavior for any ticker you haven't entered a fixed price for — ideal for watchlist tickers you're just observing, so you can see what your levels would look like if you bought at today's price.
How to use it
Add the indicator to a chart. With no other settings changed, the buy point simply tracks the current/last close — this default behavior is what you want for a ticker you're just watching, not yet holding: as the price moves, the buy line and every level move with it, so you can see at a glance what the stop-loss and target prices would be if you bought right now.
Once you actually own a position (or have a specific entry price in mind), lock the buy point in place with either:
- Positions list — type "SYMBOL:PRICE" into the Positions field for every ticker you hold (e.g. "FLNC:19.86, TSLA:245, AAPL:227.5"), so the right fixed buy price loads automatically no matter which of those charts you open, or
- Manual Override — check Manual Override and drag the buy-price line to your entry price on a single chart.
In the Levels section, turn on the stop-loss and target percentages you want to see, and adjust each percentage to match your own risk/reward plan.
The buy line (blue) and your selected levels (red for stop, green for targets) will appear at the right edge of the chart, each labeled with its percentage and price.
Inputs
Buy Point
Positions (SYMBOL:PRICE, comma separated) — optional — A running list of ticker/price pairs, e.g. "FLNC:19.86, TSLA:245". When the chart's symbol matches one in this list (case-insensitive), that price is used as the buy point automatically — useful for keeping one master list that works across all your charts.
Manual Override (use Buy Price field / dragged line below) — When checked, and the current symbol isn't in the Positions list, the buy point comes from the Buy Price field instead of defaulting to the last close.
Buy Price (drag the line on the chart, or type here) — The manual entry price. This appears as a draggable line on the chart when the indicator is added; you can drag it into place or type a value directly in Settings. Only used when Manual Override is on and the symbol isn't matched in Positions.
Extend Lines Right (bars) — How many bars past the current price the lines and labels extend to the right. Default 10.
Levels — eight independent percentage levels, each with its own on/off checkbox and editable percentage, applied relative to the buy price: Each level draws a dashed horizontal line (red for the stop, green for targets) and a label showing its percentage and the resulting price. Any level can be renamed in effect by simply changing its percentage — the label always reflects the live value.
Notes
Lines and labels are only drawn on the most recent bar, so they always reflect your current settings rather than showing historical levels.
This is a manual planning aid, not a signal generator — it does not predict price movement, issue alerts, or represent a recommendation to buy or sell any security. Always do your own research and manage risk according to your own plan.
指标

Sattam | Harmonic LabSattam | Harmonic Lab
Sattam | Harmonic Lab is an all-in-one overlay for pattern trading: 30 harmonic and classical pattern families, ready-made entry / targets / stop for every pattern, a live panel that tracks each pattern's progress, a "possible patterns" projection for the developing leg, and higher-timeframe Supply & Demand zones. Every setting is bilingual (English | Arabic).
WHAT IT DETECTS
• Harmonic: Gartley, Butterfly, Bat, Crab, Alternate Bat, Deep Crab, Cypher, Shark, Nen Star, AB=CD, 3-Drive, 5-0, White Swan, Black Swan, Leonardo, Partizan.
• Anti patterns: Anti-Gartley, Anti-Butterfly, Anti-Bat, Anti-Crab, Anti-Shark, Anti-Cypher, Anti-Nen Star.
• Classical: Head & Shoulders, Inverse Head & Shoulders, Double Top, Double Bottom, Ascending / Descending / Symmetrical Triangle.
Patterns are built on confirmed zigzag pivots with a developing D evaluated at bar close. Drawings anchor to past pivots and a detected pattern is never redrawn. Each pattern shows its legs, shaded triangles, measurement guides with ratios, X/A/B/C/D letters, the name at D and a dotted validation zone under D. 3-Drive uses 1/2/3 boxes with extension diagonals; 5-0 uses X–B, A–C and X–D chords.
TRADE LEVELS AND LIFECYCLE
Entry, Target 1, Target 2 and Stop are computed for every pattern (defaults 10% / 40% / 94% of the pattern leg, stop at the validation edge) and drawn to the right of price until Target 1 is reached. Each pattern moves through Pending → Entered → Target 1 → Target 2, or Stopped / Invalidated / Expired. Stopped and invalidated patterns are removed at once; patterns that reached their target stay drawn for the expiry age.
ACTIVE PATTERNS PANEL
One row per active pattern: name, direction, entry, both targets, stop and age in bars, with ✓ marks as levels are reached. Optional lifecycle counters (Found / Entry / T1 / T2 / Stops / Invalid / Expired).
POSSIBLE PATTERNS
When the current leg can still complete a pattern, the projected D line, its zone and a label listing the candidate families with their D ranges (nearest first). Visual only — never part of signals or counters.
SUPPLY & DEMAND ZONES
Built on a timeframe you choose (default 4H) from a confirmed pivot followed by a displacement close beyond ATR; extended to the right and removed once a close invalidates them. Never drawn from the forming higher-timeframe bar.
ALERTS
New pattern, BUY entry, SELL entry, Target 1, Target 2, Stop, Invalidation, Expiry, New Supply Zone, New Demand Zone — plus a dynamic alert template ({ticker} {tf} {pattern} {side} {event} {entry} {t1} {t2} {sl}) for "Any alert() function call". Use "Once per bar close": all signals are computed on closed bars.
SETTINGS (groups)
01 Detection — zigzag period (8), pivot confirmation bars, nested XABCD search, candidate cap, error rate % (8), min/max pattern bars, minimum height, direction, session, max new patterns per bar, max active patterns, same-pattern blocking, expiry age, two-sided extreme bar handling.
02 Pattern families — a switch per family, Cypher minimum XC/XA, classical symmetry tolerance, H&S rules (skipped waves, pivots after the right shoulder, shoulder difference), triangle options, AB=CD time filter and tolerances.
03 Entry and targets — level basis, entry / T1 / T2 percentages, finish at T1 or T2, reward/risk targets, entry trigger (close confirmation or high/low touch).
04 Stop and validation — stop mode (zone / manual % / break-even / trailing), band padding, invalidation source, entry-side filter, validation style.
05 Appearance — draw patterns, letters, ratios, levels, validation zones, shading and transparency, palette (classic or by direction), text size, guides, line widths and styles, projection length, only active patterns, keep last pattern, maximum patterns drawn (6), completed patterns retained.
06 Projection — show nearest possible D zone, display mode, families listed, direction, colors, line width and style, prediction PRZ, Cypher forecast preference.
07 Panels — active patterns panel, lifecycle counters, size, position, alignment, colors, detection start date.
08 Alerts — event switches and the dynamic template.
09 Supply & Demand — enable, zone timeframe, pivot length, sensitivity, displacement window, width, offset, max zones per side, hide invalidated zones, colors, midline style, timeframe label.
NOTES
• Pivots need bars after them to confirm, so a pattern appears one or more bars after D completes.
• The panel and counters are not a backtest and do not represent trading performance.
• Not financial advice.
EXAMPLES
Several families on one chart:
Leonardo with a possible-patterns label:
Alternate Bat with En / T1 / T2 / SL and the panel:
Double Bottom and Symmetrical Triangle:
3-Drive and 5-0:
AB=CD completing inside a 4H demand zone:
Double Top with four possible patterns:
------------------------------------------------------------
Harmonic Lab
مؤشر متكامل لتداول الأنماط: 30 عائلة هارمونيك وكلاسيكية، مستويات دخول وأهداف ووقف جاهزة لكل نمط، لوحة حيّة تتابع تقدّم كل نمط، توقّع «الأنماط المحتملة» للموجة الجارية، ومناطق عرض وطلب من فاصل أعلى. كل الإعدادات ثنائية اللغة (English | عربي).
ما يكتشفه
• الهارمونيك: Gartley، Butterfly، Bat، Crab، Alternate Bat، Deep Crab، Cypher، Shark، Nen Star، AB=CD، 3-Drive، 5-0، White Swan، Black Swan، Leonardo، Partizan.
• الأنماط المعاكسة: Anti-Gartley، Anti-Butterfly، Anti-Bat، Anti-Crab، Anti-Shark، Anti-Cypher، Anti-Nen Star.
• الكلاسيكية: الرأس والكتفين ومعكوسه، القمة المزدوجة، القاع المزدوج، المثلث الصاعد والهابط والمتماثل.
تُبنى الأنماط على محاور زجزاج مؤكدة مع نقطة D نامية تُختبر عند إغلاق الشمعة. الرسم يُثبَّت على المحاور السابقة ولا يُعاد رسم النمط بعد اكتشافه. لكل نمط أضلاعه ومثلثاته المظلّلة وأدلة القياس بالنِّسَب وحروف X/A/B/C/D والاسم عند D ومنطقة تحقق منقّطة تحت D. 3-Drive بأرقام 1/2/3 وقطري امتداد؛ 5-0 بأوتار X–B وA–C وX–D.
المستويات ودورة الحياة
دخول وهدف أول وهدف ثانٍ ووقف تُحسب لكل نمط (افتراضيًا 10% / 40% / 94% من ضلع النمط، والوقف عند حافة منطقة التحقق) وتُرسم يمين السعر حتى بلوغ الهدف الأول. ينتقل النمط بين: قيد الانتظار ← دخل ← الهدف 1 ← الهدف 2، أو وقف / إبطال / انتهاء. الموقوف والمُبطل يُزال فورًا، والذي حقق هدفه يبقى مرسومًا حتى عمر الانتهاء.
لوحة الأنماط النشطة
صف لكل نمط نشط: الاسم، الاتجاه، الدخول، الهدفان، الوقف، وعمره بالشموع، مع ✓ عند تحقق كل مستوى. اختياريًا عدّادات دورة الحياة (Found / Entry / T1 / T2 / Stops / Invalid / Expired).
الأنماط المحتملة
حين تكون الموجة الجارية مرشحة لإكمال نمط، يُعرض خط D المتوقع ومنطقته وملصق يسرد العائلات المحتملة ونطاق D لكل منها بالأقرب أولًا. توقع بصري فقط — لا يدخل في الإشارات أو العدّادات.
مناطق العرض والطلب
تُبنى على الفاصل الذي تختاره (افتراضي 4 ساعات) من محور مؤكد يليه إغلاق بإزاحة تتجاوز ATR؛ تمتد يمينًا وتُحذف عند إبطالها بإغلاق. لا تُرسم من شمعة الفاصل الأعلى الجارية.
التنبيهات
نمط جديد، دخول شراء، دخول بيع، الهدف الأول، الهدف الثاني، الوقف، الإبطال، الانتهاء، منطقة عرض جديدة، منطقة طلب جديدة — إضافة إلى قالب تنبيه ديناميكي ({ticker} {tf} {pattern} {side} {event} {entry} {t1} {t2} {sl}) مع "Any alert() function call". اختر «Once per bar close» لأن كل الإشارات تُحتسب عند الإغلاق.
الإعدادات (المجموعات)
01 الاكتشاف — فترة الزجزاج (8)، شموع تأكيد المحور، البحث المتداخل، سقف المرشحين، نسبة الخطأ % (8)، أقل/أقصى شموع للنمط، أقل ارتفاع، الاتجاه، الجلسة، أقصى أنماط جديدة لكل شمعة، أقصى أنماط نشطة، منع تكرار النمط، عمر الانتهاء، معالجة الشمعة ثنائية الطرف.
02 عائلات الأنماط — مفتاح لكل عائلة، أدنى XC/XA لسايفر، سماحية تماثل الكلاسيكية، قواعد الرأس والكتفين (الموجات المتخطاة، المحاور بعد الكتف الأيمن، فرق الكتفين)، خيارات المثلث، فلتر زمن AB=CD وسماحياته.
03 الدخول والأهداف — أساس المستويات، نِسَب الدخول / الهدف 1 / الهدف 2، الإنهاء عند الهدف 1 أو 2، الأهداف بالعائد/المخاطرة، مُحفّز الدخول (تأكيد الإغلاق أو لمس القمة/القاع).
04 الوقف والتحقق — وضع الوقف (منطقة / يدوي % / تعادل / متحرك)، حشو النطاق، مصدر الإبطال، فلتر جهة الدخول، نمط خط التحقق.
05 المظهر — رسم الأنماط، الحروف، النِّسَب، المستويات، مناطق التحقق، التظليل وشفافيته، الألوان (كلاسيكية أو بالاتجاه)، حجم النص، الأدلة، سُمك الخطوط وأنماطها، امتداد المستويات، الأنماط النشطة فقط، إبقاء آخر نمط، أقصى أنماط مرسومة (6)، الأنماط المنتهية المُبقاة.
06 التوقع — إظهار أقرب منطقة D محتملة، وضع العرض، عدد العائلات في الملصق، الاتجاه، الألوان، عرض الخط ونمطه، منطقة PRZ، تفضيل توقع سايفر.
07 اللوحات — لوحة الأنماط النشطة، عدّادات دورة الحياة، الحجم، الموضع، المحاذاة، الألوان، تاريخ بدء الاكتشاف.
08 التنبيهات — مفاتيح الأحداث والقالب الديناميكي.
09 العرض والطلب — التفعيل، فاصل المناطق، طول المحور، الحساسية، نافذة الإزاحة، العرض، الامتداد، أقصى مناطق لكل جهة، إخفاء المُبطل، الألوان، نمط خط المنتصف، ملصق الفاصل.
ملاحظات
• المحاور تحتاج شموعًا بعدها لتتأكد، فيظهر النمط بعد اكتمال D بشمعة أو أكثر.
• اللوحة والعدّادات ليسا اختبارًا رجعيًا ولا يمثّلان أداءً تجاريًا.
• ليس توصية مالية.
指标

CryptonianEWFibLibrary "CryptonianEWFib"
Cryptonian Elliott Wave Fib /1. Stage-aware Fibonacci model, corrective projection geometry and Fresh-FVG lifecycle/confluence. Extracted from the proven 11.8c/11.8d host without methodology changes.
evaluate(goldProfile, ticker, chartTimeframeSeconds, fvgMinAtr, fvgMaxAgeBars, fibEngineOn, fvgEngineOn, fvgRequireSourceLeg, maxStoredFvgs, fvgMinRemainingPct, atrValue, mintick, currentBar, currentHigh, currentLow, currentClose, p0, p1, p2, p3, p4, pb0, pb1, pb2, pb3, primaryKey, primaryLockedCount, primaryDirection, primaryW2Depth, primaryW3Extension, primaryW4Depth, primaryW5Ratio, primaryQuality, correctionSourceKey, correctionCommittedCount, correctionOriginPrice, correctionSourceDirection, c1, cp1, c2, cp2, cb2, correctionConfirmed, correctionHasProvisional, fvgOriginalTops, fvgOriginalBottoms, fvgLiveTops, fvgLiveBottoms, fvgDirections, fvgBirthBars)
Parameters:
goldProfile (bool)
ticker (string)
chartTimeframeSeconds (int)
fvgMinAtr (float)
fvgMaxAgeBars (int)
fibEngineOn (bool)
fvgEngineOn (bool)
fvgRequireSourceLeg (bool)
maxStoredFvgs (int)
fvgMinRemainingPct (float)
atrValue (float)
mintick (float)
currentBar (int)
currentHigh (float)
currentLow (float)
currentClose (float)
p0 (float)
p1 (float)
p2 (float)
p3 (float)
p4 (float)
pb0 (int)
pb1 (int)
pb2 (int)
pb3 (int)
primaryKey (string)
primaryLockedCount (int)
primaryDirection (int)
primaryW2Depth (float)
primaryW3Extension (float)
primaryW4Depth (float)
primaryW5Ratio (float)
primaryQuality (float)
correctionSourceKey (string)
correctionCommittedCount (int)
correctionOriginPrice (float)
correctionSourceDirection (int)
c1 (float)
cp1 (bool)
c2 (float)
cp2 (bool)
cb2 (int)
correctionConfirmed (bool)
correctionHasProvisional (bool)
fvgOriginalTops (array)
fvgOriginalBottoms (array)
fvgLiveTops (array)
fvgLiveBottoms (array)
fvgDirections (array)
fvgBirthBars (array) 脚本库

CryptonianEWViewLibrary "CryptonianEWView"
Cryptonian Elliott Wave View /1. Dedicated presentation-policy layer for Minimal Trader, Balanced, Full Audit and Custom chart modes. Presentation only; no Elliott, Forecast, Trade, Runtime or Audit methodology.
resolve(mode, cleanChart, primaryDegreeLinesOn, secondaryDegreeLinesOn, subSecondaryDegreeLinesOn, alternateCountLinesOn, correctionLinesOn, showPivotSkeleton, showElliottChannels, showPrimaryCount, secondaryDegreeLabelsOn, subSecondaryDegreeLabelsOn, showAlternateCount, showCorrection, showPivotIds, showDevelopingPivot, showCorrectionLevels, showFibModel, showFreshFvg, showInvalidationLevel, showInvalidationTags, showRevisionTags, showTradeLevels, showTradeSignals, showPotentialForecast, forecastAuditOn, forecastAuditLabelsOn, contextForecastRoadmapOn, contextForecastMainLabelOn, contextForecastTargetLabelsOn, htfTradeBridgeGeometryOn, maxTradeLifecycleLabels)
Parameters:
mode (string)
cleanChart (bool)
primaryDegreeLinesOn (bool)
secondaryDegreeLinesOn (bool)
subSecondaryDegreeLinesOn (bool)
alternateCountLinesOn (bool)
correctionLinesOn (bool)
showPivotSkeleton (bool)
showElliottChannels (bool)
showPrimaryCount (bool)
secondaryDegreeLabelsOn (bool)
subSecondaryDegreeLabelsOn (bool)
showAlternateCount (bool)
showCorrection (bool)
showPivotIds (bool)
showDevelopingPivot (bool)
showCorrectionLevels (bool)
showFibModel (bool)
showFreshFvg (bool)
showInvalidationLevel (bool)
showInvalidationTags (bool)
showRevisionTags (bool)
showTradeLevels (bool)
showTradeSignals (bool)
showPotentialForecast (bool)
forecastAuditOn (bool)
forecastAuditLabelsOn (bool)
contextForecastRoadmapOn (bool)
contextForecastMainLabelOn (bool)
contextForecastTargetLabelsOn (bool)
htfTradeBridgeGeometryOn (bool)
maxTradeLifecycleLabels (int)
drawActiveZone(boxStore, labelStore, enabled, startBar, projectionBars, zoneTop, zoneBottom, zoneName, zoneColor, panelColor, labelSize)
Parameters:
boxStore (array)
labelStore (array)
enabled (bool)
startBar (int)
projectionBars (int)
zoneTop (float)
zoneBottom (float)
zoneName (string)
zoneColor (color)
panelColor (color)
labelSize (string) 脚本库

Vix Dual Adaptive (Independent) [Zofesu]CREDITS
Based on the Williams VIX Fix concept originally published on TradingView by ChrisMoody (CM_Williams_Vix_Fix, 2014, open-source). Original script:
The underlying VIX Fix formula was created by Larry Williams and is public domain.
─────────────────────────────────────
Vix Dual Adaptive (Independent) is a sentiment oscillator that runs two fully independent Williams VIX Fix engines simultaneously — one calibrated to detect capitulation, one calibrated to detect euphoria. Each engine has its own lookback window, its own percentile threshold, and its own dual-layer statistical filter.
The standard VIX Fix measures fear only: one engine, one direction, shared parameters. This implementation adds an inverse engine that mirrors the calculation to detect overextension at the top of a move, and separates the calibration of both engines so each can be tuned to the specific behavior of the asset and timeframe being traded.
─────────────────────────────────────
01 — What is Vix Dual Adaptive?
─────────────────────────────────────
The indicator plots two histograms from a common zero line — Fear above, Greed below. A histogram bar lights up only when its engine registers a statistically extreme reading. When no extreme is present, bars render in black and serve purely as visual anchors for candle alignment.
Fear Engine (Lime)
Measures how far the current low sits below the highest recent close. Large values mean price has dropped sharply from a recent peak — capitulation conditions.
Formula: (highest(close, lb) − low) / highest(close, lb) × 100
Greed Engine (Purple) — original extension
Measures how far the current high sits above the lowest recent low. Large negative values mean price has extended sharply from a recent trough — euphoric conditions.
Formula: −((high − lowest(low, lb)) / lowest(low, lb) × 100)
─────────────────────────────────────
02 — Why Two Independent Engines
─────────────────────────────────────
Market tops and bottoms do not behave symmetrically. Bottoms form through fast, violent capitulation — often a single bar of panic selling. Tops form through slow distribution — extended drift with decreasing momentum.
A single-engine VIX Fix with shared parameters cannot capture both. A lookback tuned to catch sharp capitulation will miss slow euphoric extension, and a lookback tuned for drift will smooth away panic spikes entirely.
Running two engines with independent lookback windows and independent percentile thresholds solves this. The Fear engine can be set short and sensitive; the Greed engine can be set longer and more selective — or the reverse, depending on the asset's character.
─────────────────────────────────────
03 — Dual Threshold Filtering
─────────────────────────────────────
Each engine filters its raw value through two independent statistical thresholds. A signal bar appears when either threshold is crossed.
Threshold 1 — Bollinger Band boundary
SMA of the VIX Fix value plus or minus 2 standard deviations, calculated over the engine's lookback period. This boundary adapts dynamically to current volatility — it tightens in calm markets and widens during turbulence.
Threshold 2 — Percentile rank line
The highest (or lowest) VIX Fix value recorded over twice the lookback period, multiplied by the percentile setting. At 0.99 this means only readings in the top 1% of the historical range qualify. This threshold is absolute rather than adaptive — it anchors the signal to the asset's own extreme history.
Signal logic:
Fear bar — wvf ≥ BB upper OR wvf ≥ percentile threshold
Greed bar — wvf ≤ BB lower OR wvf ≤ percentile threshold
Using OR rather than AND is intentional. Either condition alone represents a statistically meaningful extreme; requiring both would suppress the majority of valid signals.
─────────────────────────────────────
04 — Settings
─────────────────────────────────────
Fear Lookback — default 145
Bars used for the Fear engine's VIX Fix and Bollinger Band calculation. Higher = smoother, fewer signals.
Fear Percentile — default 0.99
Statistical rank required for a Fear signal. 0.99 = only the top 1% of extremes qualify. Lower values produce more signals.
Greed Lookback — default 148
Independent from the Fear lookback. Tune separately.
Greed Percentile — default 0.99
Independent from the Fear percentile. Tune separately.
Show Bollinger Bands — default off
Show Percentile Lines — default off
Both boundary lines are hidden by default. Enable them during calibration to see where the thresholds sit relative to the histogram, then hide them once the settings are finalized.
─────────────────────────────────────
05 — Calibration
─────────────────────────────────────
Each asset and timeframe requires its own settings. There is no universal configuration — the defaults are calibrated for D1 on major instruments and should be treated as a starting point.
Step 1 — Enable both boundary lines so the thresholds are visible against the histogram.
Step 2 — Set the percentile to 0.99 and adjust the lookback across a range of 50 to 500. Watch how the signal density changes.
Step 3 — Reduce the percentile gradually until the number of signals matches your trading frequency. Fewer, higher-conviction signals for swing trading; more signals for active trading.
Step 4 — Repeat independently for the second engine. The two engines do not need matching values.
Step 5 — Hide the boundary lines once calibration is complete.
Save the finished configuration as an indicator template so it can be reapplied per instrument or TimeFrame.
─────────────────────────────────────
06 — Signal Interpretation
─────────────────────────────────────
Fear bar appears — the market has reached a statistically extreme oversold condition. Potential bullish reversal zone.
Greed bar appears — the market has reached a statistically extreme overextended condition. Potential bearish reversal zone.
The entry trigger is not the appearance of the bar. It is the moment the bar disappears on a closed candle — this confirms the extreme condition has ended rather than continuing. Entry on the following candle.
A bar that stays lit across multiple candles indicates a sustained trend or ongoing accumulation, not a reversal. Waiting for the bar to close and disappear is what separates a reversal signal from a continuation warning.
If both Fear and Greed register simultaneously, the two engines are reading conflicting pressure. This typically occurs during high-volatility expansion. Check the higher timeframe and wait for support or resistance confirmation before entering.
─────────────────────────────────────
07 — How To Use
─────────────────────────────────────
Step 1 — Calibrate the indicator to your instrument and timeframe using the process in section 05.
Step 2 — Wait for a colored histogram bar. Black bars carry no signal.
Step 3 — Do not enter while the bar is lit. Wait for it to disappear on a closed candle.
Step 4 — Enter on the next candle open. Stop loss beyond the extreme of the signal range.
Step 5 — Confirm with structure. A Fear signal landing on a known support level is significantly stronger than one occurring in open space. The indicator identifies when sentiment is extreme; it does not identify where price will turn.
Works on all asset classes: Indices, Stocks, Forex, Gold, Oil, Crypto.
Best timeframes: D1, W1. 指标

CryptonianEWAuditLibrary "CryptonianEWAudit"
Cryptonian Elliott Wave Audit /1. Owns production integrity auditing, compact event-state construction, universal-event aggregation and alert deduplication for the library-first Elliott architecture. The audit rules are migrated from Elliott Wave Engine 11.8b2 without changing Elliott or trade methodology.
addUniqueLimited(values, value, maximumSize)
Adds one unique string and caps the registry size.
Parameters:
values (array)
value (string)
maximumSize (int)
eventOnce(eventRegistry, eventCondition, eventName, sourceKey, maximumSize, deduplicate)
Generic event de-duplication helper. This preserves the 11.8b2 event
key contract: eventName | sourceKey | time.
Parameters:
eventRegistry (array)
eventCondition (bool)
eventName (string)
sourceKey (string)
maximumSize (int)
deduplicate (bool)
eventState(lastEvent, currentCountKey, lastInvalidCountKey, forecastKey, tradeId, countStarted, countRevised, countInvalidated, forecastNew, forecastRevised, forecastInvalidated, tradeWaiting, tradeActivated, tradeResolved, tradeCountInvalidExit)
Creates the shared Model.EventState. The code field is a bit-mask for
future audit/UI use; the named booleans remain the authoritative contract.
Parameters:
lastEvent (string)
currentCountKey (string)
lastInvalidCountKey (string)
forecastKey (string)
tradeId (string)
countStarted (bool)
countRevised (bool)
countInvalidated (bool)
forecastNew (bool)
forecastRevised (bool)
forecastInvalidated (bool)
tradeWaiting (bool)
tradeActivated (bool)
tradeResolved (bool)
tradeCountInvalidExit (bool)
tradeLifecycleEvent(resolution)
True when Trade's per-bar resolution contains any lifecycle event.
TP1 is intentionally included even when the trade remains live because 11.8b2
treats TP1 as an alert-worthy lifecycle event.
Parameters:
resolution (TradeResolution type from AYEHAN/CryptonianEWModel/1)
productionAudit(pivotPrices, pivotBars, pivotTimes, pivotTypes, pivotIds, nestedPivotPrices, nestedPivotTimes, fvgOriginalTops, fvgOriginalBottoms, fvgLiveTops, fvgLiveBottoms, fvgDirections, fvgBirthBars, tradeActivationCount, tradeResolutionCount, tradeProfitableResolutions, tradeLosingResolutions, tradeFlatResolutions, tradeCancelled, tradeWaitingCancellationCount, tradeTp1ReachedCount, tradeTp2ReachedCount, tradeLive, tradeSetupId, tradeDirection, tradeEntry, tradeStop, tradeTp1)
Runs the original 11.8b2 production audit and owns persistent issue
history internally. Call this once per host bar.
Parameters:
pivotPrices (array)
pivotBars (array)
pivotTimes (array)
pivotTypes (array)
pivotIds (array)
nestedPivotPrices (array)
nestedPivotTimes (array)
fvgOriginalTops (array)
fvgOriginalBottoms (array)
fvgLiveTops (array)
fvgLiveBottoms (array)
fvgDirections (array)
fvgBirthBars (array)
tradeActivationCount (int)
tradeResolutionCount (int)
tradeProfitableResolutions (int)
tradeLosingResolutions (int)
tradeFlatResolutions (int)
tradeCancelled (int)
tradeWaitingCancellationCount (int)
tradeTp1ReachedCount (int)
tradeTp2ReachedCount (int)
tradeLive (bool)
tradeSetupId (string)
tradeDirection (int)
tradeEntry (float)
tradeStop (float)
tradeTp1 (float)
universalEventRaw(events, committedPivotNow, impulseCompletedNow, correctionCompletedNow, freshFvgConfluenceNow, mtfContextChangedNow, mtfPrimaryGateReadyNow, tradeLifecycleNow, forecastAuditTargetHit, primaryW5TargetHitNow, productionStructuralGate, productionTradeActivationGate, productionAuditChangedNow)
Reproduces the 11.8b2 universal-event OR tree using the compact shared
EventState plus the few event families not represented by Model /1.
Parameters:
events (EventState type from AYEHAN/CryptonianEWModel/1)
committedPivotNow (bool)
impulseCompletedNow (bool)
correctionCompletedNow (bool)
freshFvgConfluenceNow (bool)
mtfContextChangedNow (bool)
mtfPrimaryGateReadyNow (bool)
tradeLifecycleNow (bool)
forecastAuditTargetHit (bool)
primaryW5TargetHitNow (bool)
productionStructuralGate (bool)
productionTradeActivationGate (bool)
productionAuditChangedNow (bool)
universalAlert(rawEvent, maximumSize, deduplicate)
Stateful universal alert. The registry lives in Audit /1 rather than
the indicator host. This preserves 11.8b2's ANY_EW_EVENT | bar_index | time key.
Call once per host bar, then feed .fire to the single alertcondition().
Parameters:
rawEvent (bool)
maximumSize (int)
deduplicate (bool)
processUniversalAlert(events, committedPivotNow, impulseCompletedNow, correctionCompletedNow, freshFvgConfluenceNow, mtfContextChangedNow, mtfPrimaryGateReadyNow, tradeLifecycleNow, forecastAuditTargetHit, primaryW5TargetHitNow, productionStructuralGate, productionTradeActivationGate, productionAuditChangedNow, maximumSize, deduplicate)
Convenience wrapper: aggregate + deduplicate in one host call.
Parameters:
events (EventState type from AYEHAN/CryptonianEWModel/1)
committedPivotNow (bool)
impulseCompletedNow (bool)
correctionCompletedNow (bool)
freshFvgConfluenceNow (bool)
mtfContextChangedNow (bool)
mtfPrimaryGateReadyNow (bool)
tradeLifecycleNow (bool)
forecastAuditTargetHit (bool)
primaryW5TargetHitNow (bool)
productionStructuralGate (bool)
productionTradeActivationGate (bool)
productionAuditChangedNow (bool)
maximumSize (int)
deduplicate (bool)
ProductionAuditState
Complete production-integrity result. Individual checks are retained so
Fields:
pass (series bool)
status (series string)
currentIssue (series string)
signature (series string)
unresolvedActivations (series int)
issueCount (series int)
lastIssue (series string)
changedNow (series bool)
pivotArraysAligned (series bool)
nestedArraysAligned (series bool)
fvgArraysAligned (series bool)
tradeAccounting (series bool)
tradeResultAccounting (series bool)
cancellationAccounting (series bool)
liveIdentity (series bool)
liveOrdering (series bool)
tp1Accounting (series bool)
UniversalEventState
Compact result from the universal Elliott event aggregator.
Fields:
raw (series bool)
fire (series bool)
key (series string) 脚本库

CryptonianEWRuntimeLibrary "CryptonianEWRuntime"
Cryptonian Elliott Wave Runtime /1. Owns adaptive MTF profile selection, compact context/bridge request expressions, lower-timeframe confirmation processing, MTF trade gates, bottom-up bootstrap assembly, Context EW forecast assembly, HTF trade-bridge request expressions, nested-pivot request expressions, production gates and final engine-state packing. Methodology is preserved from Elliott Wave Engine 11.8b2; this library is an architecture migration, not a rules rewrite.
autoContextTimeframe(chartSeconds)
Parameters:
chartSeconds (int)
autoConfirmationTimeframe(chartSeconds)
Parameters:
chartSeconds (int)
autoBridgeTimeframe(chartSeconds)
Parameters:
chartSeconds (int)
profileState(enabled, autoProfile, manualContextTimeframe, manualExecutionTimeframe, manualConfirmationTimeframe, chartTimeframe, chartSeconds)
Builds the timeframe/profile portion of Model.MtfState.
It deliberately does not perform any data request.
Parameters:
enabled (bool)
autoProfile (bool)
manualContextTimeframe (string)
manualExecutionTimeframe (string)
manualConfirmationTimeframe (string)
chartTimeframe (string)
chartSeconds (int)
bridgeTimeframe(autoProfile, manualConfirmationTimeframe, chartSeconds)
Returns the active lower bridge timeframe used by the existing
bottom-up Elliott bootstrap. This remains separate because Model /1 MtfState
intentionally stores only Context / Execution / Confirmation.
Parameters:
autoProfile (bool)
manualConfirmationTimeframe (string)
chartSeconds (int)
bridgeTimeframeValid(bridgeTf, chartSeconds)
Parameters:
bridgeTf (string)
chartSeconds (int)
contextPack(mtfPivotStrength, atrLength, mtfMinimumSwingAtr, allowDiagonals, allowTruncation, truncationMinimumPct, contextPivotStrength, contextMinimumSwingAtr, candidateStarts, minimumNewCandidateScore, extensionThreshold, diagonalTolerance, invalidationMode)
Exact 11.8b2 higher-timeframe context packet.
mtfConfirmedSnapshot() retains the old trade-context methodology while
contextConfirmedSnapshot() retains the separate Context-EW forecast geometry.
Parameters:
mtfPivotStrength (int)
atrLength (simple int)
mtfMinimumSwingAtr (float)
allowDiagonals (bool)
allowTruncation (bool)
truncationMinimumPct (float)
contextPivotStrength (int)
contextMinimumSwingAtr (float)
candidateStarts (int)
minimumNewCandidateScore (float)
extensionThreshold (float)
diagonalTolerance (float)
invalidationMode (string)
mtfContextState(pack)
Converts ContextPack's MTF branch into the shared DegreeState contract.
Parameters:
pack (ContextPack)
contextForecastDegreeState(pack)
Converts ContextPack's full Context-EW branch into DegreeState.
Parameters:
pack (ContextPack)
bridgeDegreeState(pivotStrength, atrLength, minimumSwingAtr, candidateStarts, minimumNewScore, allowDiagonals, allowTruncation, truncationMinimumPct, extensionThreshold, diagonalTolerance, invalidationMode)
Exact lower-bridge structural expression, object form.
Parameters:
pivotStrength (int)
atrLength (simple int)
minimumSwingAtr (float)
candidateStarts (int)
minimumNewScore (float)
allowDiagonals (bool)
allowTruncation (bool)
truncationMinimumPct (float)
extensionThreshold (float)
diagonalTolerance (float)
invalidationMode (string)
ltfMomentumSignal(fastLength, slowLength)
Exact lower-timeframe momentum expression used by 11.8b2.
Parameters:
fastLength (simple int)
slowLength (simple int)
nestedPivotEvent(strength, atrLength)
Exact Part 9.2 lower-degree confirmed pivot event expression.
Parameters:
strength (int)
atrLength (simple int)
htfTradeBridgeState(enabled, degreeEngineOn, secondaryEnabled, subSecondaryEnabled, primaryPivotStrength, secondaryPivotStrength, subSecondaryPivotStrength, atrLength, primaryMinimumSwingAtr, secondaryMinimumSwingAtr, subSecondaryMinimumSwingAtr, candidateStarts, minimumNewScore, allowDiagonals, allowTruncation, truncationMinimumPct, extensionThreshold, diagonalTolerance, invalidationMode, minimumModelScore, stopBufferAtr)
Native HTF trade bridge request expression. Candidate discovery,
first-seen geometry freezing and W2/W3/W4/W5 classification remain in Trade /13.
Parameters:
enabled (bool)
degreeEngineOn (bool)
secondaryEnabled (bool)
subSecondaryEnabled (bool)
primaryPivotStrength (int)
secondaryPivotStrength (int)
subSecondaryPivotStrength (int)
atrLength (simple int)
primaryMinimumSwingAtr (float)
secondaryMinimumSwingAtr (float)
subSecondaryMinimumSwingAtr (float)
candidateStarts (int)
minimumNewScore (float)
allowDiagonals (bool)
allowTruncation (bool)
truncationMinimumPct (float)
extensionThreshold (float)
diagonalTolerance (float)
invalidationMode (string)
minimumModelScore (float)
stopBufferAtr (float)
updateMtfState(previous, enabled, autoProfile, manualContextTimeframe, manualExecutionTimeframe, manualConfirmationTimeframe, chartTimeframe, chartSeconds, gateMode, requireExecutionTimeframe, ltfConfirmationMaximumAge, realtimeBar, context, ltfSignalValues, ltfSignalTimes, primaryDirection, correctionDirection)
Updates one persistent Model.MtfState object from the current profile,
requested context packet and request.security_lower_tf() signal/time arrays.
Pass a persistent initialized object from the host, then assign the returned object
back to it on every bar. The function intentionally ignores the realtime chart
bar's final LTF intrabar, exactly as 11.8b2 did.
Parameters:
previous (MtfState type from AYEHAN/CryptonianEWModel/1)
enabled (bool)
autoProfile (bool)
manualContextTimeframe (string)
manualExecutionTimeframe (string)
manualConfirmationTimeframe (string)
chartTimeframe (string)
chartSeconds (int)
gateMode (string)
requireExecutionTimeframe (bool)
ltfConfirmationMaximumAge (int)
realtimeBar (bool)
context (ContextPack)
ltfSignalValues (array)
ltfSignalTimes (array)
primaryDirection (int)
correctionDirection (int)
runtimeEvents(current, previous, primaryDirection, correctionDirection)
Small event helper that replaces host history expressions with object
history applied correctly by the caller: pass current and previous Runtime states.
Parameters:
current (MtfState type from AYEHAN/CryptonianEWModel/1)
previous (MtfState type from AYEHAN/CryptonianEWModel/1)
primaryDirection (int)
correctionDirection (int)
bootstrapState(chartPrimaryMissing, bridge, context, chartClose, chartAtr)
Parameters:
chartPrimaryMissing (bool)
bridge (DegreeState type from AYEHAN/CryptonianEWModel/1)
context (DegreeState type from AYEHAN/CryptonianEWModel/1)
chartClose (float)
chartAtr (float)
contextForecastState(enabled, contextTimeframeValid, context, armScore)
Parameters:
enabled (bool)
contextTimeframeValid (bool)
context (ContextPack)
armScore (float)
processNested(eventTypes, eventPrices, eventTimes, eventAtrs, barTimes, pivotPrices, pivotTimes, pendingType, pendingPrice, pendingTime, pendingAtr, lastEventTime, coverageStartTime, coverageEndTime, minimumSwingAtr, enabled)
Parameters:
eventTypes (array)
eventPrices (array)
eventTimes (array)
eventAtrs (array)
barTimes (array)
pivotPrices (array)
pivotTimes (array)
pendingType (int)
pendingPrice (float)
pendingTime (int)
pendingAtr (float)
lastEventTime (int)
coverageStartTime (int)
coverageEndTime (int)
minimumSwingAtr (float)
enabled (bool)
nestedLeg(pivotPrices, pivotTimes, coverageStartTime, coverageEndTime, engineOn, timeframeValid, t0, y0, t1, y1, direction, motive, diagonal, confirmed)
Parameters:
pivotPrices (array)
pivotTimes (array)
coverageStartTime (int)
coverageEndTime (int)
engineOn (bool)
timeframeValid (bool)
t0 (int)
y0 (float)
t1 (int)
y1 (float)
direction (int)
motive (bool)
diagonal (bool)
confirmed (bool)
structuralProductionGate(productionMode, confirmOnClose, barConfirmed)
Parameters:
productionMode (bool)
confirmOnClose (bool)
barConfirmed (bool)
tradeActivationProductionGate(productionMode, confirmOnClose, barConfirmed)
Parameters:
productionMode (bool)
confirmOnClose (bool)
barConfirmed (bool)
packEngineState(primary, secondary, subSecondary, correction, bootstrap, parent, degreeResolution, forecast, contextForecast, mtf, htfTrade, events)
Parameters:
primary (DegreeState type from AYEHAN/CryptonianEWModel/1)
secondary (DegreeState type from AYEHAN/CryptonianEWModel/1)
subSecondary (DegreeState type from AYEHAN/CryptonianEWModel/1)
correction (CorrectionState type from AYEHAN/CryptonianEWModel/1)
bootstrap (BootstrapState type from AYEHAN/CryptonianEWModel/1)
parent (ParentHypothesis type from AYEHAN/CryptonianEWModel/1)
degreeResolution (DegreeResolutionState type from AYEHAN/CryptonianEWModel/1)
forecast (ForecastState type from AYEHAN/CryptonianEWModel/1)
contextForecast (ContextForecastState type from AYEHAN/CryptonianEWModel/1)
mtf (MtfState type from AYEHAN/CryptonianEWModel/1)
htfTrade (TradeBridgePack type from AYEHAN/CryptonianEWModel/1)
events (EventState type from AYEHAN/CryptonianEWModel/1)
ContextPack
One request-safe higher-timeframe packet containing both legacy MTF
Fields:
mtfDirection (series int)
mtfStage (series int)
mtfQuality (series float)
mtfInvalidation (series float)
mtfDiagonal (series bool)
forecastDirection (series int)
forecastStage (series int)
forecastScore (series float)
forecastInvalidation (series float)
forecastDiagonal (series bool)
p0 (series float)
p1 (series float)
p2 (series float)
p3 (series float)
p4 (series float)
p5 (series float)
confirmedClose (series float)
RuntimeEvents
Small host-facing diagnostic packet for runtime transitions.
Fields:
contextChanged (series bool)
motiveGateReady (series bool)
correctionGateReady (series bool) 脚本库

指标

脚本库

指标

Key Levels for FuturesWhat this does
Key Levels draws the ten reference prices that most intraday traders end up marking by hand
every morning: the previous month's high and low, the previous week's, the previous day's
regular-session high and low, the London session's, and the premarket's.
They are drawn automatically, they update themselves, and — the part that took the most work —
their tags stay on screen no matter where you scroll.
The ten levels
Tag
Level
Window
MH / ML
Previous month high and low
calendar month
WH / WL
Previous week high and low
calendar week
PDH / PDL
Previous day high and low
RTH 09:30–16:00 ET
LH / LL
London high and low
03:00–08:00 ET
PMH / PML
Premarket high and low
04:00–09:30 ET
Every window is an input, so if your definition of London or premarket differs from mine, change
it. ICT traders who want the London killzone instead of the full session can set it to
0200-0500.
Colour tells you two things at once
Most level indicators give you a pile of horizontal lines that all look alike, and you end up
squinting at the tag to work out what you are looking at. This one encodes the information in
the colour itself.
Hue tells you the timeframe. The palette runs cool to warm as the timeframe shortens:
Violet — monthly, the most structural
Blue — weekly
Cyan — previous day
Amber — London, overnight
Magenta — premarket, the most immediate
Shade tells you the side. Lighter for the high, deeper for the low.
So a deep violet line is the previous month's low and you know that at a glance, without
reading anything. Weekly and monthly levels also draw one step thicker than the intraday ones,
so the structural prices read first when the chart gets busy.
All ten colours, the line width, the tag size and the tag position are inputs. If you disagree
with the palette, it takes ten seconds to change.
Tags that do not run away
The usual approach puts level tags a fixed number of bars to the right of the last candle.
Scroll back to look at something and the tags vanish off the right edge, and you are left
guessing which line is which.
These tags anchor to chart.right_visible_bar_time, so they sit at the right edge of whatever
you are currently looking at. Scroll, zoom, jump back three weeks — the tags come with you and
stay readable. Each shows its abbreviation and, optionally, the exact price.
Weekly and monthly: settled or developing
Both default to the previous completed period — a level that is finished and will not move,
which is how PDH and PDL already behave and what most people mean when they say "last week's
high."
Flip either to Current and it tracks the developing period instead. Those draw dotted
rather than solid, so at a glance you can tell the difference between a level that is fixed and
one that can still be extended by the next candle.
On repainting
Nothing here repaints.
The previous week and month values are read with the standard offset and lookahead_on,
which returns the last completed period and nothing about the current one. The developing week
and month values are accumulated bar by bar on the chart series, so no higher-timeframe request
is involved at all. The session levels build up from the bars as they close.
A level appears when the data that defines it exists, and never changes afterwards.
Settings
Show / Hide — every pair independently. Ten levels is a lot on a quiet chart; turn off what
you are not using today.
Sessions — the London, premarket and RTH windows, plus previous-vs-current toggles for the
week and month.
Style — line width (weekly and monthly automatically draw one step heavier), how far the
tags sit in from the right edge, tag size from tiny to normal, and whether to include the price
in the tag.
Colors — all ten, individually.
Notes
Use an intraday chart. Session windows mean nothing on a daily or higher chart, and the
indicator will tell you so on screen.
On stocks, enable Extended Trading Hours or the premarket and London bars will not exist
and those levels will stay blank. Futures are fine as they are.
Session levels are calculated on the chart timeframe. On any timeframe whose bars line up
with the session boundaries — 1, 2, 3, 5, 10, 15, 30 and 60 minute all do, since the windows
start on the hour or the half hour — this is exact. On an unusual timeframe such as 7 minutes,
a level can be off by one bar's high or low.
Ten tags will overlap when levels cluster. Drop the tag size to Tiny or hide the pairs you
are not watching. 指标

Range Breakout by AVRange Compression Breakout
Volatility compression and expansion system
Range Compression Breakout automatically detects periods of low-volatility consolidation, draws and maintains the range in real time, and signals when price transitions into expansion.
How it works
Compression is measured relative to the market's own recent behavior rather than a fixed price distance. In Adaptive Percentile mode, a range qualifies when its high-low span sits among the quietest percentile of its recent history — so the same settings work across futures, FX, crypto, and equities without retuning. ATR Multiple mode is also available for a fixed volatility-based threshold.
Once a range is detected, the box is dynamic. While price stays contained, the box expands to absorb new highs and lows, capturing the full churn of the consolidation instead of resetting on every probe.
Signals
Break — price closes decisively beyond the boundary plus a buffer, with optional multi-bar confirmation and an optional volume-spike filter.
Wick Long / Wick Short — a failed probe outside the range that closes back inside on a long wick, confirmed by the following bar, indicating mean reversion toward the midline.
A cooldown period after each break prevents the box from immediately reforming on the expansion move.
Settings
Four preset profiles — Tight Ranges for low-timeframe scalping, Normal Ranges for intraday, Swing Trading for multi-day consolidations, and Options Selling for extended sideways chop — each configuring lookback, tightness, minimum bars, confirmation, and cooldown. Custom mode exposes all parameters. Box fill, borders, midline, and signal colors are fully adjustable, and each signal type toggles independently.
Alerts
Range Detected, Range Breakout, Breakout with Volume Confirmation, and Range Reversal.
Notes
Volume confirmation should be left off on spot FX and other symbols reporting tick-based volume. Diagnostic values including the range-to-ATR ratio and compression state are available in the Data Window for calibration. 指标

Multi Timeframe (i)FVG Analysis [BMT]Multi Timeframe (i)FVG Analysis
Fair value gaps and inverted fair value gaps on the chart timeframe and up to three higher timeframes, with a lifecycle per gap, relevance filters so a higher-timeframe view does not bury the chart, a directional bias that filters what you see and hear, and alerts.
WHAT IT DRAWS
A fair value gap (FVG) is a three-bar imbalance: a bullish FVG is the space between bar one's high and bar three's low when bar three's low is above bar one's high and bar two closed above it; a bearish FVG is the mirror. Each gap is a box from the bar that formed it, with an optional dotted midpoint line.
Every gap has three states, tracked separately on every enabled timeframe:
FVG : live, price has not closed through it.
iFVG (inverted) : price has closed through the far side. A bullish FVG that fails becomes a bearish iFVG and is redrawn in the iFVG color; a bearish FVG that fails becomes a bullish iFVG. The inverted level is drawn brighter than a plain FVG because it is the more actionable one.
Mitigated : price has closed back through an iFVG, and it is removed.
The mitigation test can be the close (default) or the high and low.
TIMEFRAMES
One row per timeframe: the chart timeframe plus H1, H2 and H3. Each row has its own timeframe, a Both / FVG / iFVG / Off switch, and a display filter. Off skips that timeframe entirely, including its data request. "auto" picks a higher timeframe paired to the chart timeframe (1 to 15, 5 to 60, 15 to 240, 60 to daily, and so on).
The defaults draw the chart timeframe only. Turn a higher timeframe on from its Off switch; the rows come preset to 15 minutes, 1 hour and 4 hours.
FILTERS
Three per timeframe.
All draws every live box.
N draws the newest N per side.
ATR draws only boxes within N ATRs of the current price, measured with that timeframe's own ATR(14) rather than the chart's, so "within 1 ATR" means the same thing on a 4-hour box and a 5-minute one.
The lookback is settable (300 bars by default). Boxes run a settable number of bars from where they formed, measured in chart bars by default so a higher-timeframe box does not take over a low-timeframe chart, or in the box's own timeframe if you prefer the longer projection. Extend Boxes runs every live box to the right edge, capped at a settable number of bars past the last bar.
BIAS
Neutral, Bullish or Bearish. It filters what is drawn and which alerts fire; every gap is still tracked underneath, because a gap against your bias is the one that may invert your way.
Bullish: bullish FVGs and bullish iFVGs drawn normally, bearish FVGs dimmed as inversion candidates, bearish iFVGs hidden. Alerts fire for a bullish FVG forming, a bearish FVG inverting, and price entering a bullish FVG. Bearish is the mirror. Neutral shows everything.
ALERTS
Six conditions in the alert dialog, each covering any enabled timeframe:
bullish FVG formed,
bearish FVG formed,
bullish FVG inverted,
bearish FVG inverted,
price entered a bullish FVG,
price entered a bearish FVG.
"Entered" fires the first time the chart bar trades inside a live gap.
Turn on "Send alert() messages" and choose "Any alert() function call" to get one message per event that names the symbol, the timeframe and the gap's levels. Events fire on every tracked gap whether or not the display filter is currently showing it. Without "Wait for bar close", a chart-timeframe gap is reported as soon as it appears intra-bar and can be withdrawn if the bar closes back over it.
THEME
Auto reads the chart background and picks light or dark. Light is the traditional green and red. Dark is built for a dark canvas: fills sit a little above the background so they do not fight the candles, and the two sides are matched in brightness rather than in transparency. Custom exposes the six colors, the border, and the counter-bias dim as inputs, since box colors are not on the Style tab.
STATUS TABLE
Optional, hidden by default. One row per timeframe with the filter in use and live counts of FVGs and iFVGs per side, plus the chart ATR.
NOTES
Every higher timeframe is one request.security call. A gap on a higher timeframe is detected when that timeframe's bar prints it, not on close, unless "Wait for bar close" is on.
指标

KTI-G (Known Trends Index-Gold)█ OVERVIEW
Known Trends Index - Gold (KTI-G) plots, in a separate pane, a daily integer score that sums the calendar patterns in force on each trading day of a gold chart. The thesis is that gold's seasonal tendencies are better tested by letting the chart's own history define the profile, with a hard in-sample cutoff, than by hardcoding windows taken from published sources.
█ HISTORY / BACKGROUND
The index design follows the Known Trends Index that Jay Kaeppel described for the US equity market: each known seasonal trend contributes one point while it is active, and the sum is read as a favorable, neutral, or unfavorable climate rather than as a trade signal. This script applies that summation structure to gold and changes what the components are.
The literature on gold seasonality has not aged well at the level of specific months. A 2013 academic study of London gold prices from 1980 to 2010 found September and November to be the only months with positive and statistically significant returns. A 2024 replication reported a structural break around December 2010, after which those two months turned negative and January became the significant month. Practitioner windows for gold, including Kaeppel's own trading-day-of-year windows for gold futures, describe the same broad second-half and winter tendency with dates that differ by source.
The one part of the story with a physical mechanism is demand. Indian jewelry buying peaks around Diwali and the wedding season that follows it, and Chinese buying rises in the weeks before the lunar new year. Both festivals move on the lunar calendar, so fixed calendar dates describe them poorly.
The script therefore keeps three fixed components with a stated rationale (physical demand with lunar dates, turn of month, and September as a contested pattern), keeps Kaeppel's windows only as an optional comparison overlay, and gives the largest role to an empirical profile learned from the chart with no lookahead.
█ HOW IT WORKS
All date arithmetic runs on GMT-noon timestamps built from the bar's year, month, and day, so the logic is independent of the chart's exchange timezone. A US market holiday calendar is generated for the current year plus one year on either side (New Year's Day, Martin Luther King Day from 1998, Presidents Day, Good Friday by the Gregorian Easter algorithm, Memorial Day, Juneteenth from 2022, Independence Day, Labor Day, Thanksgiving, Christmas). A trading day is a weekday not in that calendar.
Two counters are maintained per bar: the trading day of month (TDOM) and the trading day of year (TDY). TDY is computed by counting calendar trading days between consecutive bars, so it stays correct across missing bars in the chart data.
The components are computed in this order.
1. Empirical profile. Two arrays of 252 slots accumulate the sum and count of daily returns (close divided by prior close, minus one) by TDY. On each bar the component is scored first, using only what has already been accumulated, and the bar's own return is added afterward. The score compares the smoothed profile for the bar's TDY against the unconditional mean daily return: the smoothed value is the mean return over a circular window of plus or minus the smoothing half-width in TDY slots. The score is +1 when the smoothed value exceeds the unconditional mean by the threshold, -1 when it falls below the mean by the threshold, and 0 otherwise. No score is produced until the accumulated count reaches the minimum number of years multiplied by 250. Accumulation stops after the training end date when the freeze option is on; otherwise it continues as an expanding window. TDY values above 252 fold into slot 252.
2. Physical demand. Diwali is computed for the prior and current year as the new moon nearest November 1, taken as a date in India Standard Time. Chinese New Year is computed for the current and next year as the second new moon after December 21 of the preceding year, taken as a date in Beijing time. New moon instants come from the Meeus mean-phase series with the fourteen largest periodic corrections. The component is +1 from 15 calendar days before Diwali through 45 days after it, and from 30 calendar days before Chinese New Year through the day before it. Overlapping windows do not add.
3. Turn of month. +1 on the last two trading days of a month and the first trading day of the next month.
4. September. The user-set September weight on every bar in September, 0 by default.
5. Kaeppel overlay. Off by default. When on, +1 for TDY 250 through year end and TDY 1 through 38, -1 for TDY 39 through 134, +1 for TDY 135 through 188, -1 for TDY 189 through 249.
KTI-G is the sum of the five components. With default settings the possible range is -3 to +4.
On the last bar of a daily chart the script walks every calendar day from January 1 of the current year through February 28 of the next year, rebuilding TDOM and TDY along the way, evaluates the same component function for each future trading day after the current bar, and draws one box per nonzero value in the right margin. The projection uses the profile arrays as they stand on the last bar. The boxes are deleted and redrawn once per new trading day.
█ HOW TO USE
Apply the script to a daily chart of a gold futures continuous contract, a gold bullion fund, or a gold miner proxy. The code is written for daily bars because every component is defined per trading day; on any other timeframe the main plot returns na and the table shows a notice.
The column plot is the index. Teal columns are readings of 2 or higher, gray columns are 0 or 1, red columns are -1 or lower. Two dotted horizontal lines mark the boundaries at 1.5 and -0.5, and a solid line marks zero. These zone cutoffs are the author's choice and are not taken from any published source; they should be re-examined after inspecting the distribution of readings on the chosen symbol.
The semi-transparent boxes to the right of the last bar are the projected index for each future trading day through February 28 of next year, colored by the same zone rule. A small label marks the first projected day. Zero-value future days draw no box.
The table in the top right shows the current reading, the value and sign of each active component, the profile deviation from the mean in basis points per day, the TDY, whether the bar is in-sample or out-of-sample relative to the training end, the number of training days accumulated, and the computed dates of the current year's Diwali and next year's Chinese New Year.
Eight hidden series are available in the Data Window and in chart data export: each of the five components, the profile deviation in basis points, the TDY, and an in-sample flag. These exist so that the components active during any drawdown can be inspected bar by bar.
The intended use is diagnostic. With the freeze option on, every bar after the training end date is a clean out-of-sample test of whether the seasonal shape learned from the earlier period persisted on that symbol. Comparing the frozen result against the expanding-window result shows whether the shape moved.
█ SETTINGS
Show active components (on): draws the table.
Project through Feb 28 of next year (on): draws the forward projection boxes and label.
Empirical profile
• Empirical TDY profile (on): includes the empirical component in the sum.
• Training end (2010-12-31): last date whose return is accumulated into the profile when freezing is on. The default is the break date reported in the 2024 replication study.
• Freeze profile at training end (on): stops accumulation after the training end. Off gives an expanding window that keeps learning.
• Smoothing half-width (10): number of TDY slots on each side of the current slot averaged together, 0 to 40.
• Threshold vs. mean (3.0 bps/day): the profile must differ from the unconditional mean by this amount to score +1 or -1.
• Minimum years before scoring (10): the empirical component returns 0 until this many years of daily returns, at 250 per year, have been accumulated.
Fixed components
• Physical demand, lunar Diwali + CNY (on).
• Turn of month (on).
• September weight (0): -1, 0, or +1 applied on September bars.
• Kaeppel TDY windows overlay (off).
█ WHAT MAKES IT ORIGINAL
The script combines four things that are not, to the author's knowledge, found together in a published gold seasonality indicator.
First, the seasonal profile is learned from the chart with no lookahead and a user-set in-sample cutoff, so the out-of-sample record of gold seasonality on any symbol can be read directly from the plot rather than inferred from a fixed set of published dates.
Second, the demand component uses computed lunar dates for Diwali and Chinese New Year, generated in the script from a new-moon series, instead of fixed Gregorian windows that drift against the festivals by up to a month.
Third, the trading-day-of-year and trading-day-of-month counters are built from a generated holiday calendar and count calendar trading days between bars, so the index is robust to gaps in the symbol's data and can be projected forward for dates that have no bars yet.
Fourth, every component is exposed as its own series so that a reading can be decomposed on any historical bar, which is the step needed to find out which pattern was active when the index was wrong.
█ NOTES / LIMITATIONS
• The empirical component needs at least the minimum years of daily history before the training end date to score at all. A symbol whose data begins after the training end never scores that component while freezing is on; lower the minimum, move the training end, or turn freezing off. The table's training-day count shows how much history has been used.
• The main plot is na on any timeframe other than daily, and the table displays a notice.
• There is no request.security call and no lookahead. The empirical score on a bar uses only returns from earlier bars. The projection boxes and table are rebuilt on the last bar only; historical columns do not repaint.
• The forward projection is date-bounded at February 28 of the year after the chart's last bar. It rolls forward each calendar year and is not extended beyond that date.
• The projection uses the profile as it stands on the last bar. With freezing off, the projected values can change from day to day as the profile continues to learn.
• Trading-day math uses a US exchange holiday calendar. Gold futures trade on a calendar that differs by a day in some years, and special unscheduled closures are not modeled, so TDY values can be offset by one relative to a futures exchange count in those years.
• Diwali and Chinese New Year dates are computed astronomically and can differ from the observed festival by one day. Rare lunar leap-month cases for Chinese New Year are not handled.
• The zone thresholds and the demand window lengths are the author's constructions. Published seasonal patterns have shown decay after publication, and nothing in this script should be read as a forecast.
• The script uses up to 500 boxes for the projection; a projection window of roughly 300 trading days stays within that ceiling. Per-bar loops are bounded by the smoothing window (at most 81 slots) and the calendar-day gap between consecutive bars. 指标

Linear Regression Channel Visible Range Volume ProfileLR Channel VRVP — Linear Regression Channel + Visible Range Volume Profile
A multi-factor overlay that blends Linear-Regression-smoothed candles with a true Visible-Range Volume Profile, a statistical mean channel, Bollinger Band %, adaptive percentile bands, and auto-merging pivot Support/Resistance. Designed for traders who want a single clean visual that answers four questions at once: (1) Where is price relative to its statistical envelope? (2) Where has volume actually traded? (3) Where has the market accepted or rejected value? (4) Where are the extremes that are outside the standard deviation?
⚠️ Important note on the Volume Profile zone labels
The 68.2% and 95.45% Volume Profile zones are volume-coverage thresholds inspired by the 1σ/2σ probabilities of a normal distribution; they are not calculated standard deviations of the volume distribution. They are just shown as an analog representation of standard deviation.
The Volume Profile is not assumed to be normally distributed. The "±1σ" and "±2σ" labels are used as convenient shorthand because the 68.2% and 95.45% coverage percentages correspond to the familiar 1σ and 2σ bands of a Gaussian or Bell Curve. The actual values are computed by expanding outward from the POC until the specified percentage of traded volume is captured — a purely empirical calculation that makes no distributional assumption.
🔹 What's on the chart
Linear Regression Candles
The candles you see are not raw OHLC. Each of the four price points (open, high, low, close) is independently smoothed by a rolling linear regression over N bars (default 20). This removes intrabar noise while preserving the underlying trend slope, and produces candles whose shape reflects the smoothed market rather than the last tick.
Doji detection runs on the smoothed values: a candle is a doji when its body is ≤ 8% of its range and both upper and lower wicks are larger than the body. Dojis frequently appear at regression inflection points. On the chart, they are represented as yellow candles.
Static Mean Channel
A simple SMA(length) ± 2 × stdev(length) envelope (default 50). This is your statistical "normal" range. Price inside the channel = rotation. Price outside = extension. The channel fill is colored by regime (see below).
Visible-Range Volume Profile (right edge)
On every realtime tick the script rebuilds a volume profile across the currently visible bars. Each bar's volume is split into an up-volume / down-volume proxy based on whether the bar closed above or below its open, then distributed into price bins proportionally to the overlap between the bar's range and each bin. This is a proxy, not a true bid/ask tape read — it uses candle direction as a stand-in for aggressive buying vs. selling.
Three nested volume-coverage zones are drawn:
POC — Point of Control, the single bin with the highest traded volume. Solid yellow line extending left. The POC is a highest-volume price / acceptance reference, not a "fair value" in any valuation sense.
68.2% Value Area (VAH / VAL 34.1%) — dashed white lines. The volume-weighted band that captures 68.2% of traded volume around the POC. Comparable to a ±1σ analogy.
95.45% Extended Value Area (±47.7%) — solid purple lines. The band that captures 95.45% of traded volume around the POC. Comparable to a ±2σ analogy. I personally like to enter my trades at or outside of this area.
Bars outside the 95.45% zone are painted red to mark thinly traded / low-acceptance areas — price levels where the market spent little time and may be more prone to fast traversal. This is a low-acceptance highlight, not a proof of rejection.
Percentile Nearest Rank Bands
Symmetric grey dotted lines at mean ± PNR(|close − mean|, N). Unlike stdev bands, PNR uses the actual empirical distribution of price deviations, so it does not assume normality. On trending instruments this gives a much more honest "extreme" reading of price moves.
Support / Resistance (pivot-based, auto-merging)
Swing highs and lows are detected with a configurable lookback. When a new pivot lands within 0.5 × ATR of an existing level, the two are averaged into a single line instead of drawing a redundant one. Oldest levels are trimmed past the configured cap so the chart stays readable.
🔹 Candle colors — what each one means
🟢 Green (default bull) - Smoothed close > smoothed open, and LinReg close is inside the mean channel. Indicates a normal bullish bar in a neutral/slightly-bullish regime.
🔴 Red (default bear) - Smoothed close ≤ smoothed open and LinReg close is inside the mean channel. Indicates a normal bearish bar in a neutral/slightly-bearish regime.
🔵 Blue - LinReg close > upper band (bull bar) or LinReg close < lower band (bear bar). Indicates price has extended beyond the mean channel — early warning of a stretched move.
🟡 Yellow - Doji (body ≤ 8% of range with wicks on both sides) indecision. Often marks regression inflection points. Overrides all other colors.
🟦 Cyan (customizable) - Bollinger %B > 1, RSI overbought and price is outside both outer bands of the channels — or the mirror condition on the downside. These fully align three extreme conditions: oscillator stretched, price outside mean channel, price outside empirical PNR band. This is the strongest "everything is stretched" state. Dojis still override it.
Color priority (highest wins):
Doji → yellow
Extreme override enabled & condition met → cyan
LinReg close outside mean channel → blue
Otherwise → green / red
🔹 Background colors — what each one means:
🟩 Green vertical band ("Buy Zone BG") = Bollinger %B < 0 AND RSI < oversold threshold (30/40 depending on channel length). Price is trading below the lower Bollinger band and RSI confirms oversold. A classic mean-reversion / accumulation context.
🟥 Red vertical band ("Sell Zone BG") = Bollinger %B > 1 and RSI > overbought threshold (60/70 depending on channel length). Price is trading above the upper Bollinger band and RSI confirms overbought. Classic distribution / exhaustion context.
🟪 Purple vertical band ("Prime Accumulation Zone") where the BB% and RSI are both oversold threshold = Rare triple-confirmation zone: trend momentum is elevated in both directions, %B is depressed, and RSI is oversold. Marks high-conviction accumulation setups.
🟥 Dark red vertical band ("Prime Distribution Zone") = Percentile, Bollinger %B and RSI overbought threshold (Mirror of the above). High-conviction distribution / exhaustion setups.
The red and green backgrounds are frequent — they mark every overbought/oversold reading. The purple and dark-red backgrounds are rare and should be treated as elevated-conviction signals.
🔹 Channel fill color
The area between the upper and lower mean-channel bands is filled, and the fill changes color to reflect the current regime:
Channel Fill color
🟢 Green (translucent) = Price above mean and %B above its own average. Bullish regime — buyers in control.
🔴 Red (translucent) = Price below mean or %B below its own average. Bearish / neutral regime — sellers in control.
⚪ White (translucent) = Bollinger %B > 1 or %B < 0. Extreme regime — oscillator has broken out of its own band.
🔹 Volume Profile colors
Up-volume bars (inside VA) - Teal = Volume from bars closing above open — up-volume proxy
Down-volume bars (inside VA) - Orange = Volume from bars closing below open — down-volume proxy.
Bars outside 95.45% zone - Red = Thinly traded / low-acceptance area — possible rejection zone.
POC line - Yellow = Point of Control — highest-volume price / acceptance reference.
±1σ analogy (68.2% VA) - White dashed = 68.2% volume-coverage boundary.
±2σ analogy (95.45% EVA) - Purple solid = 95.45% volume-coverage boundary.
PNR bands - Grey dotted = Empirical percentile envelope around the mean.
🔹 How to read it
Start with the profile. POC = highest-volume price / acceptance reference. The 68.2% zone = normal rotation area. The 95.45% zone = the wider coverage band. Red bars = low-acceptance areas where price moved quickly and may do so again.
Check the fill. Green fill = bullish regime; red = bearish; white = stretched oscillator.
Look for candle confluence. A cyan candle appearing at or beyond the 95.45% VP boundary, near a pivot S/R level, and inside a purple background is the highest-probability reversal context this script identifies.
Use the backgrounds as context, not triggers. Green/red bands fire frequently and are noisy alone. Purple/dark-red bands are rare and pair well with a cyan candle and a structural level.
Trend direction comes from the slope of the smoothed candles and their position relative to the mean channel — not from any single bar.
🔹 Inputs reference and controls
Linear Regression Candles - LinReg period, doji sensitivity
Static Mean Channel - SMA length (also drives RSI and PNR length)
Percentile Nearest Rank - Sensitivity threshold (default 85)
Volume Profile - Rows, width, VA %, history depth, up/down colors, outside-95.45% color, label toggle, line-extension toggle.
Support & Resistance - Pivot lookback, max levels per side, ATR merge tolerance, line width, color, label toggle.
Extreme Oscillator - Candle Color, Enable toggle, custom color.
🔹 Notes & caveats
The Volume Profile reflects the currently visible chart range. Scroll or zoom and it redraws.
The profile recomputes on every realtime tick. Initial load on long-history charts may take a moment.
The 68.2% and 95.45% zones are volume-coverage thresholds, not calculated standard deviations of the volume distribution. The ±1σ / ±2σ labels are an analogy only.
Up-volume / down-volume is a candle-direction proxy, not a true bid/ask tape classification.
"Rejected" / "low-acceptance" areas are potential rejection zones, not confirmed ones — the profile shows where volume was thin, and thin areas are prone to fast traversal, not guaranteed to reverse.
Alerts are provided for the extreme-oscillator conditions (upper and lower).
This indicator is a contextual / analytical tool. It does not generate buy/sell signals.
Pair with a separate momentum oscillator pane if you want confirmation timing.
🔹 Credits
Built with Pine Script v6 using built-in ta.* functions. Logic is original. Feedback welcome. 指标

Volume & Movement# Volume & Movement
A separate TradingView Pine v6 indicator for comparing activity, sustained volume and candle behaviour. Uses the chart's own candles and feed volume.
## Install
1. Open a standard candlestick chart in TradingView.
2. Open **Pine Editor**, create a new indicator and replace its contents with `Volume_and_Movement.pine`.
3. Choose **Add to chart**. Save under **Volume & Movement** if you want to keep it in your account.
No extra data subscription, library or account connection is used by the script. The chart's own market-data availability still applies. Alerts require you to create an alert in TradingView; this script does not create alerts or orders automatically.
## Read the pane
The default bars compare each completed candle's volume with the immediately preceding candle:
| Reading | Meaning |
|---|---|
| 0.50× | Half as much volume |
| 1.00× | The same volume |
| 2.00× | Twice as much volume |
| 3.00× | Three times as much volume |
**Blue:** more than 10% above the previous candle. **Amber:** more than 10% below it. **Grey:** within that neutral zone, or no valid previous comparison. Colours describe the change in volume, not buying or selling. The neutral zone and all colours are adjustable.
The **slate line** compares the combined volume of the latest five candles with the five immediately before them. Example: the earlier group totals 500 and the latest group totals 800; the line reads 1.60×. These groups do not overlap within an individual comparison. Each new candle advances both windows one candle.
The dashed **1× line** is the equal-volume reference. The default scale is uncapped. If you set a visual cap, orange dots mark clipped readings; their exact values remain in the dashboard and Data Window.
You can change bar height to **Recent typical** or **Matching clock time**. The bar colours continue to show change against the previous candle. The group line always retains its own group-to-group comparison. These are distinct baselines, although all use a 1× reference.
## Purple markers
These are adjustable descriptive conditions, not predictions or trade recommendations:
| Marker | What happened | Default rule |
|---|---|---|
| **S — Busy / stalled** | High activity, small range and little net price progress | High volume; range at/below prior 30th percentile and ≤0.75× typical; close-to-close distance ≤0.5× typical range |
| **A — Busy / advancing** | High activity and a large candle closing near an edge | High volume; range at/above prior 80th percentile and ≥1.25× typical; body ≥60% of range; close in top/bottom 20% |
| **R — Busy / rejection** | High activity with a dominant wick and a recovered close | High volume; range ≥typical; wick ≥60% of range; close in upper 35% for a lower wick, or lower 35% for an upper wick |
| **L — Large move / light volume** | Large candle range despite unusually light activity | Low volume; range at/above prior 80th percentile and ≥1.25× typical |
High volume must exceed the prior 90th-percentile value **and** be at least 1.5× the baseline median. Low volume must be below the prior 20th-percentile value **and** at most 0.65× the median. Requiring both a percentile and a multiple avoids labelling tiny fluctuations as extremes. Equal values at a percentile boundary do not qualify as unusual volume.
Default baselines use the **previous 100 candles**, excluding the candle being assessed. Typical means the median. An optional setting uses the matching-time volume baseline once it has enough samples; otherwise the dashboard explicitly identifies the recent-history fallback. Candle-size baselines continue to use recent candles in either mode.
Classification priority is S, then R, then A, then L. A price gap between the previous close and the candle open exceeding half the typical candle range suppresses these shape labels and is identified in the dashboard. The volume readings still remain available where comparable.
## Time-of-day context
“Same clock time” compares volume with the median of prior candles opening at the same clock minute. Default: exchange timezone, previous 28 calendar days, weekdays together and Saturday/Sunday separately, at least three matching days.
For example, an exchange-time 10:00–10:15 candle is compared with previous matching 10:00–10:15 candles, rather than the quieter overnight candles. This is a custom median-based comparison; it is not an exact clone of TradingView's built-in Relative Volume at Time.
- Supported for native intraday charts from 1 minute through 4 hours. Other standard timeframes retain the previous-candle, group and recent-history readings.
- Only completed, full-duration candles enter time history. The current day never enters its own baseline. Missing sessions are skipped, not treated as zero.
- Matching uses the exact opening minute and the same full chart-candle duration. For example, a 09:30 candle is never substituted for a 09:00 candle.
- Day matching can use all days, weekday/weekend groups, or the same weekday. Same-weekday matching needs more calendar history to warm up.
- The available chart history limits the sample. “Warming” means not enough matching history or no positive median; it does not mean low volume.
- Exchange time follows the exchange's daylight-saving rules. Brisbane remains fixed. During a repeated daylight-saving clock hour, the last completed candle for that day's bucket is retained, so each day contributes at most one observation.
## Timing, gaps and data
By default, the unfinished live candle is hidden and the dashboard shows the latest closed candle. Optional live preview is faded and explicitly labelled LIVE; its volume is incomplete and is not extrapolated to a full candle. Markers and alerts always wait for a confirmed close.
By default, immediate and group comparisons do not cross intraday session gaps or unequal-duration candle boundaries. They become available again after comparable candles accumulate. You can override this in settings. An unavailable or zero denominator produces “—”, never an infinite ratio. Valid zero current volume can produce 0×.
Detailed mode adds body/wick percentages and the group's net price distance divided by all close-to-close distance travelled. 100% means each close moved in one direction; a small percentage means more back-and-forth movement. Neither this nor candle direction identifies actual buyer-initiated versus seller-initiated volume.
The volume belongs to the selected symbol and feed. It may represent units, contracts, quote currency or tick activity depending on the feed. Comparisons do not combine exchanges or reconstruct order flow. Standard time-based charts are required; synthetic chart types are rejected.
## Alerts and sensible starting settings
Start with **Previous candle**, groups of **5**, history **100**, default anomaly thresholds and closed candles. Enable detailed mode only when examining a candle. The Data Window gives exact historical values when you move the crosshair; the dashboard shows the latest eligible candle.
Alert choices: any unusual event, or S/A/R/L individually. The default alerts only when an anomaly appears or its type/direction changes. Disable that option for every qualifying closed candle. Configure notifications yourself in TradingView.
Thresholds are starting definitions to evaluate, not settings demonstrated to improve trading results. This version does not include EMA-band integration, automatic impulse/pullback segmentation, an order-flow feed, a scanner or trade execution.
## Verification
See `VERIFICATION.md` for the actual checks performed and any remaining TradingView compile/runtime limitation.
References: (www.tradingview.com), (www.tradingview.com), (www.tradingview.com).
指标

OMSF_Education_LibTo keep the codebase of the OMSF Learning Space indicator cleanly structured, easy to read, and as concise as possible, I have extracted core calculations and logic functions into this reusable library. This keeps the main script lightweight while allowing you to flexibly utilize these individual building blocks for your own custom scripts and quantitative experiments.
Extracted Functions & Modules
1. pivot_fun – Pivot Analytics & Trend State
Derivatives of the classic Pivot High/Low concept to identify key structural highs and lows using configurable confirmation lookback windows.
Provides continuously updated persistent pivot levels, running extreme levels, and a clean trend state machine (1 = Long, -1 = Short) along with standard pivot lag metrics (avg_std_delay).
2. dir_kaufman_eff_ratio – Directional Kaufman Efficiency Ratio (KER)
Computes directional trend efficiency ranging from -1.0 (strong downward efficiency) to +1.0 (strong upward efficiency), featuring built-in protection against division by zero.
3. ker_marketstructure_validation – KER Market Structure Validation
Accumulates and averages KER metrics separately for Long and Short market regimes to evaluate overall structural trend quality.
4. max_excurs_ratio – MFE / MAE Analytics
Tracks ATR-normalized Maximum Favorable Excursion (MFE) and Maximum Adverse Excursion (MAE) values for individual trend segments.
Computes running aggregate ratios and stores historical trade metrics in float arrays—ideal for statistical distribution and percentile analysis.
5. vis_mfe_mae_ratio_long & vis_mfe_mae_ratio_short – Visualization Components
Renders dynamic chart overlays featuring break-even levels, stop-loss excursion bounds, color fills, and informational labels displaying real-time or locked segment performance.
📌 Coming next:
OMSF Learning Space Update: Chapter 5 MFE/MAE. ()
Best regards, arni 脚本库

Zen ABR Scalping LadderThis indicator puts two numbers on the same scale, in points, so you can see at a glance whether a scalp-sized target is realistic on the timeframe you are looking at.
WHAT IT DRAWS
Five ABR lines. ABR is the average bar range: high minus low, averaged over the last N bars. Lookbacks are locked at 2, 4, 8, 16 and 32. Short lookbacks react fast, long ones hold the longer picture.
A scalp reference line, set at a percentage of ADR, the average daily range. Default is 10%. Set it to whatever your own scalp target is.
A translucent grey cloud filling the gap between the scalp line and the ABR lines. One fill per line. Where several lookbacks sit on the same side, the fills overlap and the grey darkens on its own, so no single lookback has to be picked as the driver.
Everything is drawn in price points, which is the whole idea. A twelve-point average bar and a ten-point target become two lines on one axis, and you can see which is on top without doing arithmetic.
HOW TO READ IT
Cloud above the scalp line: an average bar on this timeframe is bigger than your target. One bar can carry the trade.
Cloud below the scalp line: an average bar is smaller than your target. The target now needs several bars in a row. Either move up a timeframe or take fewer points.
Darker grey: more of the lookbacks agree. Lighter grey with lines split either side of the scalp line: the fast and slow readings disagree, and something has recently changed.
WHY 10% OF ADR
The default comes from my own scalp-sizing work. I plotted daily range history for several index futures markets against the scalp distance I was actually using, and the scalp sat at roughly a tenth of the daily range in each case, despite very different price levels and point scales. It is a starting point, not a law. Change the percentage to your own target and watch where the line lands.
SETTINGS WORTH KNOWING
Pane cap. On by default at 2x the scalp line. Without it, one volatility spike stretches the vertical scale and squashes the readable zone into a flat band at the bottom. With it, anything above the cap draws flat at the cap. The optional value table still shows the true uncapped number.
Middle-three mode. Drops the fastest lookback and the slowest, and fills from the average of ABR 4, 8 and 16 instead. Calmer top edge on fast markets.
Fixed levels. Three horizontal point levels, off by default, for pinning your own targets into the pane.
Value table. Off by default. Shows every live line in points and as a percentage of ADR.
Crossing markers. Off by default. Dots on the scalp line where the middle-three average crosses it.
WHAT MAKES IT DIFFERENT
Most volatility tools give you a ratio, a normalised reading, or a percentage in a corner. This one keeps everything in points and puts your own target on the same axis, so the comparison is direct rather than mental. The stacked cloud is the second part: instead of choosing one lookback and trusting it, all of them draw, and the shading does the agreeing for you.
LIMITATIONS
It has no opinion on direction. It will not tell you to buy or sell, and it does not know whether the market is trending or ranging. All it reports is how big a typical bar is right now against the size of the target you chose.
ADR is taken from the standard daily bar, which includes overnight trade. That is deliberate, so the script needs no session string, no timezone and no instrument preset and runs on any chart of any market. If you want a day-session-only ADR, the source is open and the daily request is the one line to change.
On a weekly or monthly chart the ADR calculation falls back to the chart timeframe, so the reference line becomes a percentage of the average weekly or monthly range. Intended use is intraday and daily.
Nothing repaints. The bar currently forming is excluded from every average. 指标

SHK Adaptive Candle Price Strength# SHK Adaptive Candle Price Strength (SHK ACPS)
**SHK Adaptive Candle Price Strength (SHK ACPS)** is a price-action strength indicator designed to estimate the strength of each price bar using its available price structure.
The indicator produces a simple **0–100 strength value** directly below the price, allowing traders to quickly evaluate whether the current price movement has relatively strong or weak momentum.
## How It Works
SHK ACPS analyzes the relationship between:
- Open
- High
- Low
- Close
- Candle body
- Upper wick
- Lower wick
- Recent price movement
- ATR-based volatility
The result is converted into a **0–100 strength scale**.
### Strength Scale
**0–20:** Very weak price strength
**20–40:** Weak
**40–60:** Moderate
**60–80:** Strong
**80–100:** Very strong
The number is displayed below the corresponding price area.
## Green and Red Strength
The indicator uses color instead of displaying unnecessary BUY/SELL text.
🟢 **Green** = bullish price strength
🔴 **Red** = bearish price strength
⚪ **Gray** = neutral or flat movement
The strength value and its color can therefore be read together.
For example:
**85 in green** → very strong bullish price movement
**72 in red** → strong bearish price movement
**28 in green** → weak bullish movement
**18 in red** → weak bearish movement
## Candle Structure Analysis
When meaningful OHLC structure is available, the indicator evaluates the candle body relative to the complete candle range.
A larger body relative to the total range generally indicates stronger directional participation.
The indicator also considers wick pressure.
For bullish candles:
- Larger lower wick can contribute positively.
- Larger upper wick can reduce bullish strength.
For bearish candles:
- Larger upper wick can contribute positively.
- Larger lower wick can reduce bearish strength.
This allows the strength value to consider more than simply whether the candle closed higher or lower.
## Adaptive Price-Movement Analysis
For price representations where traditional candle body/wick information is not meaningful, the indicator can use **close-to-close price movement relative to ATR**.
ATR provides a volatility reference.
A larger price movement relative to recent volatility produces a higher movement-strength reading, while a smaller movement produces a lower reading.
This makes the indicator useful across different chart representations, including:
- Candles
- Hollow Candles
- Heikin Ashi
- Line
- Step Line
## Current Candle
The strength value is designed to update with the **current developing price bar**.
This means the displayed number can change while the current candle is forming.
For example, a candle may begin with:
**35 → 48 → 67 → 82**
as price movement develops.
Therefore, the current value should be treated as a **live strength reading**, not a fixed value until the bar closes.
## ATR-Based Positioning
The strength value is positioned below the price using ATR rather than a fixed number of ticks.
This allows the distance to adapt to the instrument's volatility.
The result is more practical across instruments with different price scales.
## Optional Strength Bar
An optional strength-bar calculation is included in the script.
It can be enabled from the indicator settings if a visual strength representation is desired.
## Important Interpretation
SHK ACPS is a **strength measurement tool**, not a standalone trading system.
A high green value does not automatically mean that price must continue upward.
Likewise, a high red value does not guarantee that price will continue downward.
Strength can increase near the end of a move, during breakouts, or during volatile reversals.
For better decision-making, traders may combine the indicator with:
- Market structure
- Support and resistance
- Trend direction
- Moving averages
- Volume
- Momentum indicators
- Breakout confirmation
- Higher-timeframe analysis
## Example Usage
A trader may observe:
**Green 80–100**
This indicates strong bullish price structure or movement.
If this occurs together with a confirmed breakout and supportive market structure, it may indicate stronger bullish participation.
Similarly:
**Red 80–100**
indicates strong bearish price structure or movement.
When combined with a confirmed breakdown or bearish market structure, it may provide additional confirmation.
Lower readings can indicate that price movement is relatively weak and may warrant more caution.
## Designed for Simple Visual Reading
The main philosophy of SHK ACPS is simplicity.
Instead of filling the chart with multiple signals, arrows, or BUY/SELL labels, the indicator provides:
**One number + one color**
This allows the trader to visually judge the relative strength of the current price movement without adding excessive chart clutter.
### Quick Reference
| Color | Strength | General Interpretation |
|---|---:|---|
| 🟢 Green | 80–100 | Very strong bullish |
| 🟢 Green | 60–79 | Strong bullish |
| 🟢 Green | 40–59 | Moderate bullish |
| 🟢 Green | 0–39 | Weak bullish |
| 🔴 Red | 80–100 | Very strong bearish |
| 🔴 Red | 60–79 | Strong bearish |
| 🔴 Red | 40–59 | Moderate bearish |
| 🔴 Red | 0–39 | Weak bearish |
**SHK Adaptive Candle Price Strength (SHK ACPS)** is intended to give traders a clean, adaptive view of price strength while keeping the chart visually simple. 指标

SuperTrend Regime Confluence📊 SUPERTREND REGIME CONFLUENCE
A trend-following strategy combining a volatility-adaptive SuperTrend with a
market-regime classifier and a five-factor confluence filter.
The three components aren't stacked arbitrarily. Each one fixes a specific,
well-known weakness of the others, which is why they're combined into a single
tool rather than used separately.
🧩 WHY THESE COMPONENTS ARE COMBINED
A standard SuperTrend has two weaknesses:
- Fixed ATR multiplier: too tight in volatile markets (premature flips), too
wide in quiet trends.
- It flips on every crossover regardless of conditions, causing whipsaws in
sideways markets.
This strategy addresses both:
1️⃣ Regime detection adapts the band.
An ADX plus ATR-ratio classifier labels each bar Trending, Volatile, or Ranging.
In Volatile conditions the multiplier widens (fewer false flips during
expansion); in Ranging conditions it tightens. The band reacts to conditions
instead of using one fixed setting.
2️⃣ The regime filter removes the worst environment.
Entries during the Ranging regime (where trend-following bleeds) can be skipped
entirely.
3️⃣ The confluence score gates each flip.
Rather than trading every SuperTrend flip, each candidate entry is scored 0 to
100. Only flips clearing a minimum score are taken.
Together: the classifier makes the band adaptive, the regime filter removes the
setting where the signal fails, and the score removes the weakest signals. Each
piece compensates for a limitation of the SuperTrend it's built on.
🧮 THE CONFLUENCE SCORE (rules-based, not machine learning)
A plain weighted sum of five factors, each contributing fixed points. It is
fully deterministic and documented in the code. No model, no training, no black
box:
- Volume surge (0 to 20): entry-bar volume vs its moving average
- Displacement (0 to 25): distance price moved beyond the band, in ATR units
- Trend alignment (0 to 20): signal direction vs a longer EMA
- Regime quality (0 to 15): more points in a clean Trending regime
- Prior distance (0 to 20): how far price held from the band before the flip
The sum (capped at 100) must exceed the Min Signal Score input to trigger entry.
🛡️ RISK MANAGEMENT AND SIZING
- Risk-based sizing: each position is sized so a stop-out risks a fixed percent
of equity.
- Capped at 90% of equity: no leverage, always a margin buffer (no liquidations).
- Selectable stops (ATR, Percent, or SuperTrend flip) and take-profits
(Risk:Reward, Percent, or None).
- Optional EMA filter, volume filter, entry cooldown, and long/short toggles.
- Default risk sits within TradingView's suggested 5 to 10 percent band. Lower it
for a more conservative profile.
⚙️ DEFAULT SETTINGS (as shown)
BTCUSDT, 4H, 6% risk per trade.
ATR length 10, base multiplier 3, regime lookback 40, ADX 14, ADX threshold 20.
Trend EMA 50, min signal score 65, ATR stop 6x, risk:reward 2.5, cooldown 5 bars.
Commission 0.06%, slippage 2 ticks.
Backtest shown: Jan 2020 to Sep 2026. Return +824%, max drawdown 24.55%, profit
factor 1.80, win rate 46.4%, 168 trades.
⚠️ NOTES ON USE
This is a trend-following system, so it performs best on instruments that trend
and expand in volatility. Expect drawdowns and losing streaks during extended
sideways periods, which is inherent to the approach.
Results shown are a historical backtest on a single instrument and do not
indicate future performance. Test on your own instrument, timeframe, and cost
assumptions before use. This is not financial advice. 策略

Volatility Time WindowsVolatility Time Windows finds the hours of the day when a market statistically moves the most and draws them on your chart as zones: past occurrences, the window that is running right now, and the next one coming up.
WHAT IT DOES
Every intraday market has a rhythm. Some hours are consistently wild, others are consistently dead. This script measures that rhythm from your chart's own history instead of relying on fixed session times. It splits the day into time slots (default 60 minutes), measures how much price moves in each slot, and merges the slots that are consistently above average into "volatile windows". Those windows are then drawn as boxes around the actual high-low range of every occurrence, so you can see at a glance where the movement clusters.
HOW IT WORKS
1. For every bar, the high-low range in percent of price is measured.
2. To make different regimes comparable, each value is normalized by the average range of the previous 24 hours. A wild week in 2022 therefore counts the same as a quiet week today, only the intraday pattern matters.
3. The normalized values are aggregated per time slot across all loaded bars (minimum 20 samples per slot). The result is a ratio per slot: 1.00 = average hour, 1.50 = 50 % more movement than an average hour.
4. Consecutive slots at or above the threshold (default 1.2x average) are merged into one window. A single slot between two volatile slots joins the window if it is at least average, so a small dip does not split a session in two.
5. Windows are ranked by their average ratio and the top ones (default 2) are shown.
WHAT YOU SEE
- Blue boxes around the high-low range of every past occurrence of a window, with a label showing the time span and the average high-low range of that window in percent (e.g. 13:00-17:00 · Ø 1.35 %).
- The window that is running right now is drawn slightly stronger and its label shows when it ends.
- The next occurrence within the following 24 hours is drawn as a dashed box around the current price. Its height equals the average range of that window, so you get a feeling for the expected move, and its label counts down to the start.
- Hover a label to see the ratio of the window versus the daily average.
HOW TO USE IT
- Use an intraday chart that is not larger than the chosen time resolution (e.g. a 5m, 15m or 1h chart with 60-minute slots). More history means more reliable statistics; the script uses everything TradingView loads.
- Set the timezone to the one you think in. Slot boundaries and labels follow that timezone, so daylight saving changes are handled correctly.
- Use "Mon-Fri" for crypto if weekends dilute your profile, or "Sat-Sun" to study weekend behaviour separately.
- Lower the threshold (e.g. 1.15) for longer windows, raise it (1.3 or more) to isolate the peak hours only.
- Alerts: "Volatility window starts" fires at the start of a window. The heads-up alert warns a configurable number of minutes before the start (create the alert with "Any alert() function call").
SETTINGS
Time resolution: size of the slots the day is split into (15 / 30 / 60 / 120 min).
Timezone: timezone used for slot boundaries and labels.
Days: which weekdays enter the statistics.
Volatile if ≥ x average volatility: threshold for a slot to count as volatile.
Windows to show: how many of the top windows are drawn.
Days of history: how far back zones are drawn (0 = all loaded bars).
Show next occurrence: dashed projection of the upcoming window.
Labels, text size, zone color.
Heads-up minutes: lead time for the pre-alert.
NOTES
- The statistics are descriptive, not predictive. They show when the market has moved the most in the loaded history, which helps with timing entries, sizing stops and avoiding dead hours, but a volatile window is not a directional signal.
- TradingView limits a script to 500 boxes and labels, so the oldest zones drop off once the limit is reached.
- Works on any symbol with intraday data: crypto, forex, indices, futures, stocks. 指标

Position Size CalculatorPOSITION SIZE CALCULATOR
Calculating the exact number of shares to buy before entering a trade can be slow and distracting. This on-chart indicator does all the position sizing math for you in real time.
Simply enter your total account balance, choose your preferred allocation percentages, and the script displays an on-screen table showing the exact amount to invest and the number of whole shares to buy.
WHAT IT DOES
- Automatic Share Sizing: Calculates whole shares to buy based on your capital and allocation percentages.
- 3 Allocation Tiers: Configure 3 custom sizing options (e.g. 10%, 20%, 30%) to suit different trade setups.
- Live or Manual Price:
- By default, it takes the confirmed close price of your chosen timeframe (e.g. 5-min, Daily).
- Or toggle "Manual Entry Price" to calculate sizes for planned limit orders.
- Safe Math: Always rounds down to complete shares (math.floor) so you never exceed your intended risk.
- Clean & Flexible Display: Fully customizable table position, color themes, and an option to hide the table outside regular market hours.
HOW TO USE IT
1. Add the indicator to your chart.
2. Open Settings (the gear icon on the indicator label):
- Account: Enter your total trading capital.
- Allocation Tiers: Set your allocation percentages for Tier 1, 2, and 3.
- Price Settings: Keep automatic close price detection, or check "Use Manual Entry Price" and type your limit price.
3. Check the on-chart table:
- Find your desired tier column.
- Read the green highlighted number in the "Shares" row and place your order.
CUSTOMIZATION OPTIONS
- Show/Hide Investment Row: Display only the share count or include the cash value.
- Hide When Market Closed: Automatically hides the table when the market is inactive to keep your charts clean.
- Table Position: Move the table to any corner or side of your screen (Top-Right, Top-Left, Bottom-Right, etc.).
- Colors: Adjust background, border, text, and highlight colors to fit dark or light charts.
DISCLAIMER
This script is a position sizing calculation tool and does not provide financial advice, buy/sell signals, or trade recommendations. Always manage your risk according to your personal trading plan. 指标

ICT Daily Liquidity Sweep [PineGen AI]ICT Daily Liquidity Sweep
OVERVIEW
This strategy trades liquidity sweeps in the style of ICT (Inner Circle Trader) concepts. It marks the Asian session range each day, then looks for price to sweep above or below that range — or above/below the previous day's high/low — and reverse back inside it. A sweep followed by a close back inside the range is treated as a potential liquidity grab, and the strategy enters in the direction of the reversal.
Entries are only considered during a configurable time window (London/NY hours by default), which is when these liquidity-sweep setups are most commonly discussed in ICT-based trading approaches.
HOW IT WORKS
Asian range: the script tracks the high and low of the Asian session (00:00–08:00 UTC by default, adjustable) and locks the range once the session ends.
Sweep detection: a long setup requires price to trade below the Asian low or the previous day's low and close back above it within the trading window. A short setup is the mirror condition against the Asian high or previous day's high.
Risk and exits: stop-loss is placed beyond the sweep wick with a configurable buffer. Two take-profit levels are set at user-defined risk-reward multiples (TP1 partial close, TP2 full close). A hard time-based exit closes any open position at a configurable hour to avoid holding through low-liquidity periods.
Position sizing: quantity is calculated from account equity and a user-defined risk percentage per trade, not a fixed lot size.
SETTINGS
SL Buffer (pips) — distance beyond the sweep wick for the stop
Risk % — percentage of equity risked per trade, used to size position
TP1 / TP2 R:R — take-profit distances as a multiple of initial risk
TP1 Close % — portion of the position closed at TP1
Window Start / End (UTC) — the hours during which new entries are allowed
Labels / Session backgrounds — visual toggles only, no effect on signals
BACKTEST ASSUMPTIONS
Default backtest settings use a starting capital of 10,000, 10% of equity per trade, a 0.01% commission per side, and 2 ticks of slippage. These are configurable in the Properties tab and should be adjusted to match your actual broker/instrument costs before drawing conclusions from the results — commission and slippage assumptions materially affect strategy performance, especially on lower timeframes.
IMPORTANT NOTES
This strategy does not repaint — orders are processed on bar close and higher-timeframe data is pulled with lookahead disabled. Backtest results are hypothetical and do not account for real-world factors such as latency, partial fills, or changing market conditions, and past performance is not indicative of future results. This script is provided for educational purposes and is not financial advice. Always forward-test on a demo account before considering live use, and adjust the commission/slippage settings to reflect your actual trading costs. 策略
