FractalExpansionModel_Lib_AlignmentReason5TraceLibrary "FractalExpansionModel_Lib_AlignmentReason5Trace"
emptyProbe()
Return an empty route result when C18 never entered a route fold.
lowerProbe(dT, dTC, rOT, rCT, semantic, order, maxRecords, minimumHead, maximumHead)
Mirror C18 foldLower exactly and expose its first rejected pair or
unique selected packet. Main calls this only after the unchanged fold and only
for the first live reason-5 observation in one context epoch.
Parameters:
dT (array)
dTC (array)
rOT (array)
rCT (array)
semantic (array)
order (array)
maxRecords (int)
minimumHead (int)
maximumHead (int)
scalarProbe(cdT, cdTC, crOT, crCT, cSemantic, cOrder, pdT, pdTC, prOT, prCT, pSemantic, pOrder, minimumHead, maximumHead)
Mirror C18 foldScalar exactly, including delivered/shape/selection,
exact-repeat/conflict/strict-advance, and boundary co-release precedence.
Parameters:
cdT (int)
cdTC (int)
crOT (int)
crCT (int)
cSemantic (int)
cOrder (int)
pdT (int)
pdTC (int)
prOT (int)
prCT (int)
pSemantic (int)
pOrder (int)
minimumHead (int)
maximumHead (int)
classifyOrigin(preReason, storedReason, storedReadiness, storedDT, storedDTC, storedROT, storedRCT, storedSemantic, storedOrder, postReason, postReadiness, probe)
Classify only a proven route. A new-identity emitter is never chosen
by elimination; soft retention and unresolved paths remain explicit.
Parameters:
preReason (int)
storedReason (int)
storedReadiness (int)
storedDT (int)
storedDTC (int)
storedROT (int)
storedRCT (int)
storedSemantic (int)
storedOrder (int)
postReason (int)
postReadiness (int)
probe (ProbeResult)
eventClass(priorReason, priorReadiness, currentReason, currentReadiness)
Classify row transitions without weakening the normal resolved-row
contract. Recovery is exactly reason 0/readiness 1.
Parameters:
priorReason (int)
priorReadiness (int)
currentReason (int)
currentReadiness (int)
ProbeResult
Fields:
foldReason (series int)
origin (series int)
selected (series bool)
selectedIndex (series int)
priorDT (series int)
priorDTC (series int)
priorROT (series int)
priorRCT (series int)
priorSemantic (series int)
priorOrder (series int)
nextDT (series int)
nextDTC (series int)
nextROT (series int)
nextRCT (series int)
nextSemantic (series int)
nextOrder (series int)
selectedDT (series int)
selectedDTC (series int)
selectedROT (series int)
selectedRCT (series int)
selectedSemantic (series int)
selectedOrder (series int)
compareEligible (series bool)
exactRepeat (series bool)
boundaryCoRelease (series bool)
transitionReason (series int) 脚本库

XeL OnlineRecursionXeL OnlineRecursion is a Pine Script library for online and streaming statistical estimation on continuous numerical and financial data.
The library is designed around recursive statistical populations whose retained state is updated observation by observation. Most recursive components use constant retained memory and O(1) work per observation, making them suitable for indicators and models that require adaptive statistics without repeatedly recalculating an entire historical window.
OnlineRecursion is statistical infrastructure rather than a trading signal, strategy, or standalone indicator. It is intended to be imported and composed by other Pine scripts.
CORE DESIGN
The library separates four conceptual layers:
Streaming and population mechanics.
Generic retained statistical state.
Derived statistical interpretations.
Finance-oriented evidence and recursive weighting models.
A central design principle is that retained state represents a statistical population. Statistics that can be derived from an existing population are computed from that state rather than introducing unnecessary independent recursions.
STATISTICAL TOOLS
The library includes:
First-order recursive filtering and recursive extrema estimation.
Sample-and-hold, settlement, accumulation, and exact rolling-sum tools.
Fixed-memory P2 cumulative quantile estimation.
Adaptive quantile and expectile estimation.
Adaptive conditional tail-mean estimation.
Adaptive Huber location estimation.
Adaptive MAD and Gaussian-equivalent robust scale.
Recursive univariate moments through fourth order.
Variance, sigma, skewness, kurtosis, and effective sample size.
Recursive covariance and correlation.
Recursive linear-regression views including beta, intercept, and R-squared.
Recursive Heavy-Tail distribution estimation.
Relative-return, relative-projection, and additive-moment transforms.
Recursive decay, anchored, participation, and composite-alpha constructors.
Market-participation models.
Market-dispersion models.
POPULATION SEMANTICS
OnlineRecursion treats population geometry as part of the mathematical definition of an estimator.
Depending on the component, the represented population may be:
Cumulative.
Finite rolling.
Exponentially weighted.
Anchored.
Conditional.
Observation-clock.
Event-clock.
These population interpretations are not assumed to be interchangeable.
Initialization, missing observations, reset behavior, recursive coefficients, and population boundaries are therefore explicit estimator semantics rather than incidental implementation details.
Where defined as a recursive feedback coefficient, alpha generally follows a convention. Exact initialization behavior is defined by each estimator because creation of a new statistical population is not always equivalent to an ordinary recursive update.
FINANCE-ORIENTED EVIDENCE
The library includes reusable tools for constructing adaptive market evidence, including time-decay weighting, participation-based weighting, relative-return transformations, and recursive market-dispersion models.
Available dispersion interpretations include:
Mean displacement.
Realized movement.
Drawdown.
Upthrust.
Directional stress peaks.
Average directional stress.
Participation models allow recursive weighting to respond to different market-population relationships rather than treating every observation as equally informative.
The chart accompanying this publication demonstrates library mechanics on NQ continuous futures using hourly observations and Open Interest participation.
The upper and lower dispersion plots, recursive mean, and lower-pane statistic illustrate one possible composition of exported library functionality.
These plotted outputs are demonstrations of statistical mechanics. They are not trading signals or recommended parameter settings.
HEAVY-TAIL MODEL
The Heavy-Tail estimator combines generic recursive moment state with additional model-specific interpretations such as Student-t degrees of freedom, t-distribution scale, and absolute-innovation scale.
HeavyTail is one statistical interpretation built on the generic moment backbone. The library does not assume that this model is appropriate for every market, instrument, or application.
USAGE
Import the library from another Pine Script and use the exported state types, methods, enumerations, or functional interfaces required by the application.
Stateful interfaces provide explicit control over retained state and update timing. Functional interfaces are also provided where convenient for series-oriented use.
Some estimator compositions intentionally require caller-controlled timing.
For example, when one adaptive estimator supplies a threshold, center, or scale to another estimator, the caller may need to use the previously retained value to avoid unintended same-observation feedback.
MISSING DATA AND CALLER POLICY
Market-data-dependent functions can return na when required information is unavailable or when the requested statistical relationship is not currently defined.
Fallback behavior intentionally remains with the importing application when the library cannot define the relationship mathematically.
This prevents unavailable data from being silently converted into a different statistical assumption.
LIMITATIONS
OnlineRecursion does not provide:
Entry or exit logic.
Trading recommendations.
Profitability claims.
A guarantee that any estimator is appropriate for a particular market.
Recursive estimators depend on their coefficient policy, population definition, and initialization semantics.
A recursive population is not automatically equivalent to a finite rolling-window population merely because their outputs may appear similar.
Users should therefore select estimators and coefficient models according to their statistical meaning rather than treating all recursive parameters as interchangeable smoothing controls.
DESIGN INTENT
OnlineRecursion is intended to provide reusable statistical infrastructure from which higher-level models can be composed.
The architecture follows this separation:
Foundational state represents the retained population.
Derived statistics interpret that population.
Models add model-specific assumptions.
Applications decide how statistical evidence is used.
This separation is intended to keep generic statistical machinery independent from application-specific trading logic.
VERSION
This first TradingView library publication corresponds to XeL OnlineRecursion development release 1.0.0-rc.2 , dated 2026-09-04.
TradingView library publication revisions such as /1 are independent of the project's development release numbering. 脚本库

Pattern Atlas : Geometric [AxeAlgo]Pattern Atlas : Geometric Patterns
WHAT THIS LIBRARY IS
This is a Pine Script v6 library of 17 classical chart pattern detectors — Head and Shoulders, Double/Triple Tops and Bottoms, triangles, wedges, flags, and the rest of the standard technical-analysis catalog built from swing highs and lows rather than single-candle shape. Unlike candlestick patterns, which read one to a handful of fixed bars, chart patterns span a variable, often large number of bars, so this library carries one small piece of state — a rolling history of confirmed swing pivots — that every pattern function reads from. Beyond that, the same philosophy as Library #1 applies: no plotting, no alerts, and no inputs in this script by design, since a library's job is to hand other scripts a clean, reusable, well-documented API, not to draw on a chart itself (Pine doesn't allow a library to plot anything anyway). If you're looking for a ready-to-use indicator built on top of this library, see the companion "Pattern Atlas : Geometric Indicator " script, which imports every function here and turns it into on-chart signals, measured-move price targets, a live scanner table, and alerts.
Chart pattern analysis is one of the foundational tools of classical technical analysis, going back to Edwards and Magee's original work and refined since by researchers like Thomas Bulkowski, whose statistical studies of pattern behavior are the closest thing this field has to an industry-standard reference. The patterns in this library follow that standard catalog, so anyone who already knows what a Head and Shoulders top or an Ascending Triangle looks like will recognize exactly what each function is checking for.
WHY A LIBRARY INSTEAD OF ONE MONOLITHIC INDICATOR
Splitting detection logic out as an importable library means:
- Any Pine coder building their own strategy, indicator, or screener can pull in exactly the pattern checks they need without copy-pasting swing-pivot and trendline math into every new script.
- The detection logic is tested and maintained in one place. When a threshold gets refined, everything importing this library benefits from the update by bumping one version number.
- It keeps the math separate from presentation — how a pattern gets drawn, colored, or alerted on is a completely separate decision from whether the pattern is actually present, and different users want different presentations.
HOW TO IMPORT AND USE IT
Add this line near the top of your script (adjust the version number to whatever the current published version is):
import AxeAlgo/Pattern_Atlas_Geometric/1 as geo
Unlike Library #1, most of the functions here need a shared pivot history to work from. Call trackPivots() exactly once per bar, then pass its result into every detect*() function that needs it:
pivots = geo.trackPivots()
match = geo.detectDoubleTopBottom(pivots)
if match.found
label.new(bar_index, high, match.patternName)
Four functions — detectSpike(), detectFlag(), detectPennant(), and detectIslandReversal() — read directly off recent price action instead of the shared pivot history, so they're called without a pivots argument: geo.detectSpike().
trackPivots() takes three optional parameters: leftBars and rightBars (how many less-extreme bars must surround a candidate swing point before it confirms as a pivot — higher values mean fewer, more significant pivots, at the cost of a longer confirmation lag), and maxPivots (how much pivot history to retain). All three have sensible defaults.
Every detect*() function returns the same structure, called ChartPatternMatch, so the calling pattern is identical no matter which of the 17 you use. It has nine fields:
- found — true if the pattern matched at the evaluated bar, false otherwise.
- patternName — the specific name of what matched (e.g. "Ascending Triangle"), na when not found.
- direction — "bullish" or "bearish".
- pivotBars — bar_index of each pivot the match was built from, in chronological order.
- pivotPrices — price of each pivot, in the same order as pivotBars.
- breakoutLevel — the support, resistance, or neckline level price broke through to confirm the pattern.
- necklineSlope — slope (price per bar) of the breakout line, na when the pattern's breakout level isn't a sloped line.
- barIndex — the bar_index the pattern completes (breaks out) on.
- description — a full sentence naming the pattern and the actual measured price levels that triggered it — genuinely useful for a tooltip or an alert message, not just a repeat of the pattern name.
Two additional exported functions turn that raw match into something more actionable, and both work on any ChartPatternMatch regardless of which detect*() function produced it:
- patternStrength(match) — a 0-100 score for how decisively the confirmation close broke through breakoutLevel, relative to the pattern's own price range. A breakout that clears the level by a meaningful fraction of the pattern's own size scores higher than a one-tick poke through it.
- patternTarget(match) — a classical measured-move price target, projecting the pattern's own height from the breakout point. Returns na for patterns without a reliable height to project from (V-Top/V-Bottom Spike, Island Reversal, Bump-and-Run Reversal).
Every detect*() function also exposes its own set of tunable threshold parameters — how flat a "flat top" has to be, how much two shoulders can differ and still count as equal, and so on — all with sensible defaults so you don't have to touch them unless you want to tighten or loosen a specific pattern's sensitivity for a particular instrument or timeframe.
THE 17 PATTERNS
Reversal patterns (7) — signal a potential change in the prevailing trend:
- Head and Shoulders / Inverse Head and Shoulders — detectHeadAndShoulders(). Three swing extremes with the middle one more extreme than the two roughly-equal outer ones, confirmed when price breaks the neckline connecting the two points between them.
- Double Top / Double Bottom — detectDoubleTopBottom(). Two roughly equal peaks (or troughs) with a retracement between them, confirmed when price breaks back through that retracement level.
- Triple Top / Triple Bottom — detectTripleTopBottom(). The same idea as a Double Top/Bottom with a third roughly-equal touch, confirmed on the break of the support or resistance formed between the touches.
- Rounding Top / Rounding Bottom — detectRoundingTopBottom(). A gradual, curved advance-and-rollover (or decline-and-recovery) between two similar edge levels. Approximate: read from three swing pivots rather than fitting a true curve.
- Diamond Top / Diamond Bottom — detectDiamondTopBottom(). Swing range that widens and then narrows again, confirmed on a break of the resulting support or resistance. Rare and approximate: read from three pivot pairs rather than a clean diamond outline.
- Broadening Formation — detectBroadeningTopBottom(). Diverging highs and lows forming an increasingly volatile range, confirmed on a break of either edge. Approximate: read from two pivot pairs rather than a hand-fitted diverging channel.
- V-Top / V-Bottom (Spike) — detectSpike(). A single sharp extreme with no rounding — a large move into the pivot and an equally large move away from it, both measured against the recent average bar range, within a handful of bars. Self-contained, no pivots argument needed.
Continuation patterns (8) — typically resolve in the direction of the move that preceded them:
- Ascending Triangle — detectTriangleAscending(). Flat resistance with rising support, confirmed on a break above resistance.
- Descending Triangle — detectTriangleDescending(). Flat support with falling resistance, confirmed on a break below support.
- Symmetrical Triangle — detectTriangleSymmetrical(). Converging highs and rising lows, confirmed (bullish or bearish) whichever side the price actually breaks.
- Rising Wedge / Falling Wedge — detectWedge(). Both trendlines slope the same direction and converge; breaks the opposite way from the slope, since the shared-direction move was already losing momentum.
- Bull Flag / Bear Flag — detectFlag(). A strong directional move (the pole), followed by a tight, roughly parallel pullback, confirmed on a break back out in the pole's direction. Self-contained, no pivots argument needed.
- Bull Pennant / Bear Pennant — detectPennant(). The same pole-and-consolidation structure as a Flag, but the consolidation narrows and converges rather than staying parallel. Self-contained, no pivots argument needed.
- Rectangle — detectRectangle(). Price boxed between flat support and flat resistance, confirmed on a break of either edge.
- Cup and Handle / Inverted Cup and Handle — detectCupAndHandle(). A rounded recovery (or decline) back to its starting rim, then a shallow pullback (the handle), confirmed on a break through the rim.
Structural / gap-based patterns (2):
- Bullish / Bearish Island Reversal — detectIslandReversal(). A bar (or small cluster) isolated by a gap on both sides, then abandoned by a gap the other way — an abrupt reversal. Self-contained, pure gap logic, no pivots argument needed.
- Bump-and-Run Reversal — detectBumpAndRun(). A lead-in trendline, then a "bump" phase accelerating well beyond it, then a "run" breaking back through the lead-in line. Approximate: the lead-in line is read from just two pivots rather than a hand-drawn trendline.
WHAT THIS LIBRARY DELIBERATELY DOES NOT DO
No plotting, no drawing, no alertcondition() calls, and no inputs — Pine doesn't allow any of those inside a library in the first place, since a library can never be added to a chart on its own. If you want signals, price targets, a scanner table, or alerts, import this library into your own script (or use the companion "Pattern Atlas : Chart Pattern Scanner " indicator, which does exactly that) rather than expecting this script to render anything by itself.
This library also does not evaluate multi-timeframe data, volume, or broader market structure — it's swing-pivot and trendline geometry only, on purpose, so its behavior is easy to reason about and easy to reuse as one building block among several.
Four of the seventeen patterns are explicitly noted above as approximate: Rounding Top/Bottom, Diamond Top/Bottom, Broadening Formation, and Bump-and-Run Reversal are read from a small, fixed number of swing pivots rather than fitting a true curve or hand-drawn trendline to the data. They will not catch every textbook-perfect example of these shapes, and they may occasionally flag a looser approximation of one. Treat them as a starting point for further chart review, not a final word.
PART OF A LARGER SERIES
This is Library #2 in the AxeAlgo Pattern Atlas — a planned set of Pine libraries splitting pattern detection by the method actually used to find each kind of pattern: candlestick shape (Library #1, already published), classical chart/geometric patterns (this library), harmonic patterns (Fibonacci-ratio XABCD structures), and market-structure concepts (order blocks, liquidity, Wyckoff-style events). Each library is independent and useful on its own; together they're meant to cover technical pattern analysis without forcing unrelated detection methods into the same function.
A NOTE ON REPAINTING
trackPivots() only confirms a swing pivot once rightBars bars have passed since it happened — the same confirmation lag ta.pivothigh()/ta.pivotlow() use, just written out as plain comparisons so it works safely inside a library's exported functions. That means a pivot never moves or disappears once confirmed; it just takes rightBars bars to become known, which is a normal and unavoidable part of swing-pivot detection, not a defect in this library. On the currently-forming bar, a pattern's found status can still change tick to tick as that bar's own high, low, and close move — that's inherent to reading live price action. If you're building persisted signals, drawings, alerts, or price targets on top of these functions (rather than a live "what's happening right now" readout), gate your usage on barstate.isconfirmed so a signal only fires once the bar it describes has actually closed, exactly like the companion scanner indicator does.
DISCLAIMER
This library is a technical analysis tool for identifying classical chart pattern shapes in historical and live price data. It does not predict future price movement, and a detected pattern — including any projected price target — is a description of past price action, not a signal guaranteed to repeat. Nothing in this script constitutes financial advice. Always combine pattern recognition with your own risk management and broader analysis before making any trading decision.
脚本库

CapitalCompassCoreCapital Compass Core
Capital Compass Core is the shared Pine Script framework for the Capital Compass ecosystem. It centralizes reusable calculations, state definitions, visual standards, market-context logic, risk logic, portfolio helpers, strategy utilities, panel functions, formatting tools, and alert infrastructure used across Capital Compass scripts.
The library is designed to keep Market Navigator, Tactical Navigator, Strategy Lab, Portfolio Compass, and future Capital Compass tools operating from the same definitions instead of maintaining duplicate implementations across multiple scripts.
Purpose
Capital Compass Core is infrastructure rather than a standalone trading indicator.
The library calculates and standardizes reusable logic. Consuming indicators and strategies remain responsible for user inputs, plots, fills, chart markers, alert conditions, strategy orders, and script-specific interpretation.
Core calculates and standardizes. The consuming script orchestrates and renders.
Core systems
Reusable functionality includes:
• EMA, SMA, RMA, WMA, VWMA, HMA, DEMA, TEMA, and VWAP
• Moving-average structure, compression, expansion, zones, crosses, and standardized MA hierarchy
• 20-SMA / 21-EMA Fast Trend Zone
• Ichimoku calculations
• Bollinger Bands
• ATR, relative volume, drawdown, price-shock, and volatility calculations
• SuperTrend and multi-SuperTrend agreement
• RSI/MFI/MACD momentum components and consolidated momentum states
• Market regime, risk, opportunity, and market-permission scoring
• Tactical market phases and transition states
• Market Navigator state aggregation
• Price structure, pivots, and regular divergence
• Asset-profile presets
• Portfolio allocation and deployment calculations
• Account-context helpers
• Position sizing, ATR stops, targets, trailing logic, reward/risk, R multiples, expectancy, and strategy-quality helpers
• Confirmed higher-timeframe data helpers
• Relative-strength calculations
• Alert-event routing and transition helpers
• JSON and text formatting
• Theme-aware panels, table cells, text, borders, fills, and semantic state backgrounds
State and color standard
Capital Compass uses a consistent semantic visual language:
• Green = bullish / favorable
• Red = bearish / unfavorable
• Orange = caution / transition / sideways / neutral / mixed
• Gray = inactive / unavailable / insufficient data
• Blue = informational / fast-trend reference
• Magenta = major structural reference
Moving-average identity colors are separate from directional state colors. This allows a moving average to retain a recognizable identity while optional Trend mode communicates bullish, bearish, or transitional conditions.
The standardized moving-average hierarchy includes:
8, 13, 20, 21, 34, 50, 55, 89, 100, and 200 periods.
Primary structural references:
• 20 / 21 = fast trend
• 50 / 55 = intermediate trend / caution zone
• 200 = major long-term structural reference
Capital Compass Core also provides theme-aware helpers derived from the active TradingView chart colors so consuming scripts can remain readable across light and dark chart themes.
Capital Compass ecosystem
Market Navigator
Long-term market condition, regime, risk, opportunity, portfolio context, and review.
Tactical Navigator
Tactical trend, momentum, transition, Fast Trend Zone, volatility, and market-phase analysis.
Strategy Lab
Research, hypothesis testing, backtesting support, position sizing, risk planning, and strategy evaluation.
Portfolio Compass
Portfolio allocation, deployment, account context, and long-term capital-management support.
Shared calculations should be imported from Capital Compass Core rather than independently duplicated inside each script.
Library usage
Import the library with:
import DrGetDown/CapitalCompassCore/1 as CC
Examples of shared functionality include:
CC.ma(...)
CC.maColor(...)
CC.fastTrendZone(...)
CC.marketNavigatorState(...)
CC.tacticalPhase(...)
CC.momentumScore(...)
CC.stateColor(...)
CC.panelPos(...)
CC.strategyPlan(...)
Published library versions are intentionally explicit. Consuming scripts should migrate only after a newer Core release has been compiled, tested, and validated.
Design principles
• Maintain one definition for shared calculations and state meanings.
• Separate market-state colors from moving-average identity colors.
• Keep reusable calculations in Core whenever technically practical.
• Keep script-specific interpretation and rendering in the consuming script.
• Avoid unnecessary duplicate or correlated calculations.
• Use confirmed higher-timeframe data where explicitly specified.
• Keep risk and position-sizing mathematics separate from actual strategy order placement.
• Preserve consistent panel placement, formatting, abbreviations, state meanings, and visual behavior across the ecosystem.
• Test significant shared changes before promoting them across dependent Capital Compass scripts.
Limitations
Capital Compass Core does not predict future prices and does not guarantee profitable trades or prevent losses.
Market regimes, momentum states, tactical phases, opportunity scores, risk scores, divergences, moving-average structures, and strategy statistics are analytical classifications based on supplied market data and configured assumptions. They should not be interpreted as guarantees of future performance.
Backtest statistics describe historical results and do not guarantee similar future results.
Portfolio, allocation, deployment, and position-sizing helpers provide mathematical and analytical context only. Actual decisions remain dependent on objectives, portfolio circumstances, risk tolerance, time horizon, liquidity needs, taxes, diversification, and independent research.
Version
Internal Core version: 1.0.0
TradingView library release: /1
Capital Compass
OBSERVE • DISCERN • PREPARE • ACT WISELY
Tuned to the signal. Anchored to the mission. 脚本库

Volume Profile Library [1CG]Volume Profile Library
A high-performance fixed range volume profile engine bundled with an embedded renderer. This library handles volume accumulation, core analytics (Point of Control and Value Area), and complex visual rendering natively. It features robust box and polyline display modes, handles absolute and recurring time ranges, and accepts lower-timeframe intrabar arrays to construct highly accurate volume profiles.
Supported Configurations (As Seen in Example)
By wrapping the engine in your own script, you can expose a wide array of configurations to the user. The library natively supports processing all of the following parameters:
Time zone & Range Modes : Support for 'From Time' (single anchored profile), 'Between Times', 'Daily Anchor' (recurring at a specific time), and 'Daily Session' (recurring inside a specific session).
Profile Fidelity : Configure the number of price rows (up to 49), define the Value Area percentage, and optionally split each row into estimated buy/sell volumes based on intrabar close locations.
Visual Modes : Choose between traditional 'Boxes' (stacked volume rows), 'Polylines' (straight connective bands), and 'Curved Polylines', or disable all drawings while calculations continue.
Appearance & Gradients : Natively handles coloring for bull/bear/total volume, fading volume out outside the Value Area, rendering gradient color bands within polylines, and highlighting the Range Box and Point of Control (POC) line/label.
History Retention : Retain multiple historical recurring profiles on the chart at once without constantly recalculating them.
How to Use Correctly
To use this library effectively, the consuming indicator or strategy must handle three critical tasks:
Declare Engine State : Create a persistent state instance using `var profileState = VP.createState()`. The engine requires this state to manage arrays, recycle drawings, and persist historical sessions across bars.
Allocate Limits : Because the library manages drawing native Pine boxes, lines, and polylines, your main script must provide it with a large enough budget. You must add these limits to your `indicator()` or `strategy()` declaration (e.g., `max_boxes_count = 500`, `max_polylines_count = 100`).
Fetch Intrabar Data : Pine Script restricts `request.security_lower_tf()` inside loops and libraries. You must fetch these arrays (High, Low, Close, Volume) at the global scope of your consumer script and pass them directly into `VP.update()`.
Example Integration
import OneCleverGuy/VolumeProfileLibrary/ as VP
// 1. Declare persistent state and assemble config
var VP.ProfileState profileState = VP.createState()
var VP.ProfileConfig profileConfig = VP.ProfileConfig.new()
// 2. Fetch lower-timeframe data for volume accuracy
string ltf = timeframe.in_seconds() > 60 ? "1" : timeframe.period
= request.security_lower_tf(syminfo.tickerid, ltf, )
// 3. Update the engine on every bar
profileState := VP.update(profileState, profileConfig, true, ltfHighs, ltfLows, ltfCloses, ltfVolumes)
// 4. Retrieve statistics for your own logic
= VP.getMostRecentLevels(profileState)
Important Notes
Bars without lower-timeframe coverage will automatically fall back to the chart bar's data during accumulation.
Ensure you guard against missing volume in your main script (e.g., `if not na(volume)`), as the engine strictly requires volume data to function.
脚本库

Pattern Atlas : Candlestick [AxeAlgo]Pattern Atlas : Candlestick
WHAT THIS LIBRARY IS
This is a Pine Script v6 library of 23 candlestick pattern detectors — one exported function per pattern family, each doing pure open/high/low/close arithmetic against the current or a specified historical bar. There is no plotting, no alerts, and no inputs in this script by design: a library's job is to hand other scripts a clean, reusable, well-documented API, not to draw on a chart itself (Pine doesn't allow a library to plot anything anyway). If you're looking for a ready-to-use indicator built on top of this library, see the companion "Pattern Atlas : Candlestick Scanner " script, which imports every function here and turns it into on-chart signals, a live scanner table, and alerts.(will be published soon)
Candlestick reading is one of the oldest and most widely taught tools in technical analysis, going back to Steve Nison's work bringing Japanese candlestick charting to Western traders. The patterns in this library follow that standard catalog (cross-checked against TA-Lib's CDL* function list, the closest thing to an industry-standard reference), so anyone who already knows what a Morning Star or a Bullish Engulfing bar looks like will recognize exactly what each function is checking for.
WHY A LIBRARY INSTEAD OF ONE MONOLITHIC INDICATOR
Splitting detection logic out as an importable library means:
- Any Pine coder building their own strategy, indicator, or screener can pull in exactly the pattern checks they need without copy-pasting candlestick math into every new script.
- The detection logic is tested and maintained in one place. When a threshold gets refined, everything importing this library benefits from the update by bumping one version number.
- It keeps the math separate from presentation — how a pattern gets drawn, colored, or alerted on is a completely separate decision from whether the pattern is actually present, and different users want different presentations.
HOW TO IMPORT AND USE IT
Add this line near the top of your script (adjust the version number to whatever the current published version is):
import AxeAlgo/PatternCandlestick/1 as cdl
Then call any function directly. Every function returns the same structure, called CandleMatch, so the calling pattern is identical no matter which of the 23 you use:
match = cdl.detectDoji()
if match.found
label.new(bar_index, low, match.patternName)
CandleMatch has six fields:
- found — true if the pattern matched at the evaluated bar, false otherwise.
- patternName — the specific name of what matched (e.g. "Hanging Man"), na when not found.
- direction — "bullish", "bearish", or "neutral".
- barIndex — the bar_index the pattern completes on.
- barsUsed — how many bars the pattern spans (1, 2, 3, or 5 for the one continuation pattern that needs a 5-bar read).
- description — a full sentence naming the pattern and the actual measured values that triggered it (body size as a percent of range, wick-to-body multiples, or the specific price levels involved, depending on the pattern) — genuinely useful for a tooltip or an alert message, not just a repeat of the pattern name.
Every function also accepts an optional offset parameter (default 0, meaning the current/most recent bar) if you want to check a pattern further back in history, plus its own set of tunable threshold parameters — how strict the "small body" or "long wick" cutoffs are — all exposed with sensible defaults so you don't have to touch them unless you want to tighten or loosen a specific pattern's sensitivity for a particular instrument.
THE 23 PATTERNS
Single-bar patterns (9) — each reads one candle's own open/high/low/close shape:
- Doji — detectDoji(). Body is negligible relative to the bar's range; open and close land almost on top of each other. Neutral.
- Long-Legged Doji — detectLongLeggedDoji(). A doji with long wicks on both sides — both directions were pushed and rejected in the same bar. Neutral.
- Dragonfly Doji — detectDragonflyDoji(). A doji with a long lower wick and almost no upper wick — buyers rejected the lows. Bullish.
- Gravestone Doji — detectGravestoneDoji(). A doji with a long upper wick and almost no lower wick — sellers rejected the highs. Bearish.
- Hammer / Hanging Man — detectHammerHangingMan(). Small body, long lower wick, negligible upper wick — the same shape read two ways depending on the prior trend: a Hammer after a decline (bullish), a Hanging Man after an advance (bearish). The function infers the prior trend automatically from a lookback window, or you can supply your own trend context.
- Inverted Hammer / Shooting Star — detectInvertedHammerShootingStar(). The mirror shape (long upper wick, negligible lower wick), same trend-dependent split: Inverted Hammer after a decline (bullish), Shooting Star after an advance (bearish).
- Marubozu — detectMarubozu(). A full-bodied candle with negligible wicks on either side — one side was in complete control from open to close. Direction follows the body color.
- Spinning Top — detectSpinningTop(). Small body with real wicks on both sides, roughly balanced — pushes both up and down failed. Neutral.
- Belt Hold — detectBeltHold(). Opens at (or almost at) one extreme with almost no wick on the opening side, then closes strongly the other way — one side controlled the entire session from the opening bell.
Two-bar patterns (6) — each compares the current bar against the one before it:
- Engulfing — detectEngulfing(). The current bar's body fully covers the prior bar's opposite-colored body.
- Harami — detectHarami(). The current bar's body sits fully inside the prior bar's opposite-colored body — the inverse of Engulfing, read as the move stalling.
- Harami Cross — detectHaramiCross(). A Harami where the contained bar is also a doji — a stronger version of the stall.
- Piercing Line / Dark Cloud Cover — detectPiercingDarkCloud(). The current bar opens beyond the prior bar's extreme and closes back past its midpoint — Piercing Line is the bullish version after a decline, Dark Cloud Cover the bearish version after an advance.
- Tweezer Top / Bottom — detectTweezer(). Two consecutive bars sharing a near-identical high (Tweezer Top, bearish) or low (Tweezer Bottom, bullish) — the level held on both attempts.
- Kicker — detectKicker(). A gap between two opposite-colored bars with zero overlap between their bodies — an abrupt, no-transition reversal in sentiment.
Three-bar-and-longer patterns (8) — each reads a short sequence of bars together:
- Morning Star / Evening Star — detectStar(). A large bar, a small bar gapped away from it, then a third bar closing back past the midpoint of the first — the classic three-bar reversal, bullish (Morning) at the bottom or bearish (Evening) at the top.
- Morning Doji Star / Evening Doji Star — detectDojiStar(). The same structure as the Star pattern above, but the middle bar is specifically a doji — a stronger version of the signal.
- Three White Soldiers / Three Black Crows — detectThreeSoldiersCrows(). Three consecutive same-direction bars, each opening inside the prior body and closing beyond the prior close — steady, sustained buying or selling.
- Three Inside Up / Down — detectThreeInside(). A Harami followed by a third bar closing beyond the first bar's open, confirming the stall seen in the Harami actually turned into a reversal.
- Three Outside Up / Down — detectThreeOutside(). An Engulfing followed by a third bar extending the same move, confirming the reversal.
- Abandoned Baby — detectAbandonedBaby(). A Doji Star with a genuine price gap (not just a wick gap) on both sides of the middle bar — a rare, high-conviction reversal.
- Rising / Falling Three Methods — detectThreeMethods(). A strong trend bar, three small counter-trend bars fully contained inside its range, then a bar resuming the original direction beyond the first bar's close — the trend paused without reversing. This is the one pattern spanning 5 bars rather than 1-3.
- Stick Sandwich — detectStickSandwich(). Two bearish bars with matching closes sandwiching one bullish bar in between — sellers failed to push the close any lower on the second attempt.
WHAT THIS LIBRARY DELIBERATELY DOES NOT DO
No plotting, no drawing, no alertcondition() calls, and no inputs — Pine doesn't allow any of those inside a library in the first place, since a library can never be added to a chart on its own. If you want signals, a scanner table, or alerts, import this library into your own script (or use the companion "Pattern Atlas : Candlestick Scanner " indicator, which does exactly that) rather than expecting this script to render anything by itself.
This library also does not evaluate multi-timeframe data, volume, or broader market structure — it's candlestick shape and price-only, on purpose, so its behavior is easy to reason about and easy to reuse as one building block among several.
PART OF A LARGER SERIES
This is Library #1 in the AxeAlgo Pattern Atlas — a planned set of Pine libraries splitting pattern detection by the method actually used to find each kind of pattern: candlestick shape (this library), classical chart/geometric patterns (trendline-based structures like triangles, head and shoulders, flags), harmonic patterns (Fibonacci-ratio XABCD structures), and market-structure concepts (order blocks, liquidity, Wyckoff-style events). Each library is independent and useful on its own; together they're meant to cover technical pattern analysis without forcing unrelated detection methods into the same function.
A NOTE ON REPAINTING
Every function here evaluates whatever bar you point it at (the current bar by default, via the offset parameter) using that bar's own open/high/low/close. On the currently-forming bar, those values are still changing tick to tick — that's inherent to reading live price action, not a defect in this library. If you're building persisted signals, drawings, or alerts on top of these functions (rather than a live "what's happening right now" readout), gate your usage on barstate.isconfirmed so a signal only fires once the bar it describes has actually closed, exactly like the companion scanner indicator does.
DISCLAIMER
This library is a technical analysis tool for identifying classical candlestick shapes in historical and live price data. It does not predict future price movement, and a detected pattern is a description of past price action, not a signal guaranteed to repeat. Nothing in this script constitutes financial advice. Always combine pattern recognition with your own risk management and broader analysis before making any trading decision.
脚本库

脚本库

KC Institutional Core LibraryKC Institutional Core Library v1.0
KCInstitutionalCore is a reusable Pine Script v6 utility library created to support structured technical-analysis workflows without duplicating common helper logic across multiple indicators and strategies.
The library provides transparent and independently reusable functions for:
Score normalization and trade-quality grading
Premium, Discount and Equilibrium classification
Risk-to-reward calculation
Risk-based position-size estimation
Timeframe-aware trading-style classification
Adaptive higher-timeframe selection
Directional alignment analysis
Execution-blocker identification
The exported functions are deterministic utilities. They do not generate guaranteed trading signals, predict future price movement or execute trades.
Basic import example
import Kelly_Carter12/KCInstitutionalCore/1 as kc
string grade = kc.scoreToGrade(78)
string style = kc.tradeStyle(timeframe.in_seconds())
= kc.rangeLocation(close, ta.highest(high, 50), ta.lowest(low, 50))
The detailed function documentation below explains every exported function, parameter and return value.
Library "KCInstitutionalCore"
Reusable Pine Script v6 utilities for timeframe context, score grading, premium/discount classification, alignment, risk-to-reward and position-size calculations. Designed as a transparent helper library for indicators and strategies.
clamp(value, minimum, maximum)
Restricts a numeric value to the supplied minimum and maximum boundaries.
Parameters:
value (float) : Value to restrict.
minimum (float) : Lower boundary.
maximum (float) : Upper boundary.
Returns: The restricted value.
scoreToGrade(score)
Converts a numeric score into a concise quality grade.
Parameters:
score (float) : Score expressed on a 0–100 scale.
Returns: A grade string from AA to D.
normalizeScore(rawScore, maximumScore)
Normalizes a raw score to a 0–100 scale.
Parameters:
rawScore (float) : Current raw score.
maximumScore (float) : Maximum possible raw score.
Returns: Normalized score from 0 to 100, or na when maximumScore is not positive.
rangeLocation(price, rangeHigh, rangeLow)
Classifies the current price inside a supplied dealing range.
Parameters:
price (float) : Current or evaluated price.
rangeHigh (float) : Upper boundary of the range.
rangeLow (float) : Lower boundary of the range.
Returns: A tuple containing PREMIUM, DISCOUNT, or EQUILIBRIUM and the 0–100 range percentage.
riskReward(entry, stop, target)
Calculates reward-to-risk from entry, stop and target prices.
Parameters:
entry (float) : Entry price.
stop (float) : Stop-loss price.
target (float) : Target price.
Returns: Absolute reward-to-risk ratio, or na when the stop distance is zero.
positionSize(accountSize, riskPercent, entry, stop, pointValue)
Estimates position size from account risk and stop distance.
Parameters:
accountSize (float) : Account balance or planning capital.
riskPercent (float) : Percentage of account risked.
entry (float) : Entry price.
stop (float) : Stop-loss price.
pointValue (float) : Monetary value per price point for one unit.
Returns: Estimated units or lots according to the supplied pointValue, or na for invalid inputs.
tradeStyle(chartSeconds)
Maps chart duration in seconds to a general planning style.
Parameters:
chartSeconds (float) : Chart timeframe duration in seconds, normally supplied with timeframe.in_seconds().
Returns: SCALP, INTRADAY, SWING, or POSITION.
adaptiveTimeframes(chartSeconds)
Suggests two broader context timeframes from the chart duration.
Parameters:
chartSeconds (float) : Chart timeframe duration in seconds, normally supplied with timeframe.in_seconds().
Returns: A tuple containing primary and secondary context timeframe strings.
alignmentState(localBias, htfBias, mtfBias)
Summarizes local, higher-timeframe and multi-timeframe directional agreement.
Parameters:
localBias (int) : Local direction: 1 bullish, -1 bearish, 0 neutral.
htfBias (int) : Higher-timeframe direction: 1 bullish, -1 bearish, 0 neutral.
mtfBias (int) : Broader alignment direction: 1 bullish, -1 bearish, 0 neutral.
Returns: BULL ALIGNED, BEAR ALIGNED, PARTIAL, CONFLICT, or NEUTRAL.
executionBlocker(direction, htfBias, mtfBias, location, structureConfirmed, liquidityConfirmed, newsBlocked)
Returns the first material execution blocker in a transparent priority order.
Parameters:
direction (int) : Intended direction: 1 long, -1 short, 0 neutral.
htfBias (int) : Higher-timeframe direction: 1 bullish, -1 bearish, 0 neutral.
mtfBias (int) : Multi-timeframe direction: 1 bullish, -1 bearish, 0 neutral.
location (string) : PREMIUM, DISCOUNT, or EQUILIBRIUM.
structureConfirmed (bool) : True when the required structure event is confirmed.
liquidityConfirmed (bool) : True when the required liquidity event is confirmed.
newsBlocked (bool) : True when a manual news blackout is active.
Returns: A concise blocker description, or CLEAR when no listed blocker is active. 脚本库

FractalMemoryLib [Jayadev Rana]FractalMemoryLib packages the pattern-memory engine used by the Fractal Memory Projection indicator and the Fractal Memory Strategy so any script can import it.
WHAT IT DOES
The library finds the historical window whose movement shape most resembles the most recent bars (mean squared distance between stdev-normalized log returns), replays what followed that window as a projected close path, and sizes stops and targets adaptively by volatility regime.
EXPORTED FUNCTIONS
logRet(src) - one-bar log return of a series.
bestMatch(src, winLen, scanDepth, gapAhead) - scans up to scanDepth bars back and returns the offset of the most similar window plus a 0-100 similarity score. gapAhead reserves bars after the match for a projection.
analogPath(src, offset, fcLen, scaleF) - array of fcLen projected closes built by replaying the returns that followed the match, rescaled by scaleF (for example current ATR over ATR at the match).
adaptiveR(atrLen, rankLen, base) - volatility-adaptive unit risk: ATR times (base plus its 0-1 percentile rank), plus the rank itself. Call on every bar.
volRegime(volRank) - "Low", "Normal" or "High" label from the rank.
targets(entry, dirSign, unitR, slMult) - stop loss and TP1/TP2/TP3 at 1R, 2R and 3R.
USAGE NOTES
Call adaptiveR on every bar for ta consistency. bestMatch and analogPath are loop-heavy; for display purposes call them on the last bar only, and make sure the chart has at least scanDepth plus gapAhead bars of history. When the library itself is added to a chart it draws a small demo projection line from the best analog.
The analog projection is a statistical reference to a similar past episode, not a prediction, and not financial advice. 脚本库

PatternHelpersLibrary "PatternHelpers"
method update(atr, h, l, c, period)
Namespace types: WilderAtr
Parameters:
atr (WilderAtr)
h (float)
l (float)
c (float)
period (int)
method push(buf, o, h, l, c, t, idx, max_len)
Namespace types: CandleBuffer
Parameters:
buf (CandleBuffer)
o (float)
h (float)
l (float)
c (float)
t (int)
idx (int)
max_len (int)
method gap_candles(buf, prev_end_idx, next_start_idx)
Namespace types: CandleBuffer
Parameters:
buf (CandleBuffer)
prev_end_idx (int)
next_start_idx (int)
quantile_rail(vals, upper)
Parameters:
vals (array)
upper (bool)
has_acceptable_coverage(values, upper_bounds, lower_bounds)
Parameters:
values (array)
upper_bounds (array)
lower_bounds (array)
has_acceptable_coverage_const(values, upper, lower)
Parameters:
values (array)
upper (float)
lower (float)
has_low_directional_drift(closes, upper, lower)
Parameters:
closes (array)
upper (float)
lower (float)
has_balanced_rotation(values, shape_width)
Parameters:
values (array)
shape_width (float)
has_no_dominant_run(values, shape_width)
Parameters:
values (array)
shape_width (float)
ols_regression(y, x, origin_x)
Parameters:
y (array)
x (array)
origin_x (int)
residual_rail(highs_or_lows, indices, intercept, slope, origin_idx, upper)
Parameters:
highs_or_lows (array)
indices (array)
intercept (float)
slope (float)
origin_idx (int)
upper (bool)
WilderAtr
Fields:
prev_close (series float)
atr_val (series float)
count (series int)
CandleBuffer
Fields:
opens (array)
highs (array)
lows (array)
closes (array)
times (array)
indices (array)
start_idx (series int) 脚本库

脚本库

脚本库

脚本库

脚本库

脚本库

AssetCorrelationUtilsAssetCorrelationUtils
Auto-detection library for correlated asset pairings across futures, CFD, and crypto markets. Given any chart, returns the correct secondary and tertiary (and optionally quaternary) tickers for multi-asset divergence analysis, along with inversion flags and asset-category metadata.
Designed to eliminate the boilerplate of hardcoded ticker lists and manual "if EURUSD then GBPUSD" branching in every indicator that needs correlated data.
What it does
Consumer scripts call one function — resolveCurrentChart() — and receive a fully resolved AssetConfig object describing the current chart's correlated pair or triad. The library handles:
Symbol root extraction from full ticker IDs (with expiry suffixes, exchange prefixes, micro variants)
Asset category routing (futures / CFD / crypto branches)
Family-specific triad or dyad selection
Inversion detection (e.g. 6C inverse of USDCAD, DXY inverse of EUR/GBP)
Futures session and back-adjustment modifiers
Optional GXT mode for metals (currency-cross triads on Gold/Silver)
Optional Quad mode for metals (four-leg configurations)
Micro contracts always resolve to their higher-volume full-size correlated partners — MNQ correlates against ES/YM, not MES/MYM — matching the "trade the micros, read the majors" convention.
Supported asset classes
Futures
Indices: NQ, ES, YM, RTY + micros (MNQ, MES, MYM, M2K)
Metals: GC, SI, HG + micros (MGC, SIL, MHG)
Forex: 6E, 6B, 6A, 6N, 6C + micros (M6E, M6B, M6A, M6C)
Energy: CL, RB, HO + micros (MCL, MRB, MHO)
Treasury: ZB, ZF, ZN
Crypto: BTC, ETH + micros (MBT, MET)
CFD / Spot
Forex: EURUSD, GBPUSD, DXY, USDJPY, USDCHF, USDCAD
Metals: XAUUSD, XAGUSD, COPPER + cross-pairs (XAUEUR, XAUGBP, XAGEUR, XAGGBP)
Indices: NAS100, SP500, DJ30
EU Stocks: GER40, EU50 (dyad only)
Crypto (spot / perp)
Major: BTC, ETH, SOL, XRP
Alt: ZEC, DOGE, ADA, BNB, TAO
All routed via BINANCE perpetual (.P) pairs for consistent OHLC quality
Core functions
resolveCurrentChart(gxtMode = false, quadMode = false)
The one-liner entry point for most consumers. Wraps resolveAssets() with sensible defaults (uses syminfo.ticker, syminfo.tickerid, syminfo.type, syminfo.session, back-adjustment on).
resolveAssets(ticker, tickerId, assetType, session, useBackadjust, gxtMode, quadMode)
The full-control entry point. Same detection logic, but with explicit control over back-adjustment and session modification — useful for indicators with a strategy toggle (e.g. RTH vs ETH sessions).
Category detectors
detectIndicesFutures(ticker)
detectMetalsFutures(ticker) / detectMetalsFuturesGxt(ticker) / detectMetalsFuturesQuad(ticker)
detectForexFutures(ticker) / detectCADFutures(ticker)
detectEnergyFutures(ticker)
detectTreasuryFutures(ticker)
detectCryptoFutures(ticker)
detectForexCFD(ticker, tickerId)
detectCrypto(ticker, tickerId)
detectMetalsCFD(ticker, tickerId) / detectMetalsCFDGxt(ticker, tickerId) / detectMetalsCFDQuad(ticker, tickerId)
detectIndicesCFD(ticker, tickerId)
detectEUStocks(ticker, tickerId)
Each returns an AssetPairing — usable directly if you want to bypass the automatic category routing.
Resolution helpers
resolveTriad(chartTickerId, pairing) — returns primary + secondary + tertiary with inversion flags
resolveDyad(chartTickerId, pairing) — returns primary + secondary for two-asset configs
resolveQuad(chartTickerId, pairing) — returns four-asset config with inversion flags
Utility functions
applySessionModifierWithBackadjust(ticker, session) / applySessionModifierNoBackadjust(ticker, session) — apply ticker.modify with back-adjustment on or off
isTriadMode(pairing) — check whether a pairing has a valid tertiary
getAssetTicker(tickerId) — extract the clean ticker string from a full ticker ID
Fallback
getDefaultFallback(tickerId) — returns a pairing with the chart ticker as primary and empty secondaries. Used automatically when no category matches.
Return types
AssetConfig
detected (bool) — true if the chart asset was recognized
isTriadMode (bool) — true if 3 assets resolved, false for dyad
isQuadMode (bool) — true if 4 assets resolved
primary (string) — resolved primary ticker ID
secondary (string) — resolved secondary ticker ID
tertiary (string) — resolved tertiary ticker ID (empty for dyad)
quaternary (string) — resolved quaternary ticker ID (empty unless quad mode)
invertSecondary (bool)
invertTertiary (bool)
invertQuaternary (bool)
assetCategory (string) — category tag (e.g. "index_futures", "metal_cfd_gxt")
AssetPairing
Internal pairing structure used by detector functions. Consumers rarely construct this directly, but resolveTriad / resolveDyad / resolveQuad accept it if you're bypassing the auto-routing.
Quick start
import I_quacker_I/AssetCorrelationUtils/7 as AC
AC.AssetConfig config = AC.resolveCurrentChart()
string secondary = config.secondary
string tertiary = config.tertiary
bool inv2 = config.invertSecondary
bool inv3 = config.invertTertiary
bool detected = config.detected
For metals with currency-cross triads:
AC.AssetConfig config = AC.resolveCurrentChart(true)
// On Gold: secondary = "FOREXCOM:XAUEUR", tertiary = "FOREXCOM:XAUGBP"
// On Copper or non-metals: identical to resolveCurrentChart(false)
Full integration patterns (Off / Auto / Manual tri-state, explicit back-adjust control, and manual pairing) are documented inline in the library source.
Design notes
Robust ticker matching. All detectors use str.contains() on the root symbol, so any ticker format is recognized — bare (NQ), continuous (NQ1!), or dated with expiry (NQZ2025). Exchange prefixes are ignored during detection.
Consistent inversion semantics. DXY as the third leg of USD-base forex triads is marked inverted (rises when the pair falls). 6C as USDCAD's futures counterpart is fully inverted. Micros carry their parent's inversion flags unchanged.
Category tags. Every resolved AssetConfig carries an assetCategory string ("index_futures", "metal_cfd_gxt", "crypto", "fallback", etc.). Useful for consumer scripts that want to conditionally enable features per category (e.g. "only compute GXT confluence on metals").
Fallback safety. When no category matches, the library returns the chart ticker as primary with empty secondary / tertiary, detected = false, and assetCategory = "fallback". Consumer scripts should check detected before assuming correlated data is available.
Credits
Original library concept — @fstarcapital
Modifications and extensions — @I_quacker_I
Crypto remapped to BINANCE .P perpetuals
Micro contracts always correlate against higher-volume mini/full contracts
AUD/NZD forex futures family (6A, M6A, 6N)
GXT mode for metals (currency-cross triads)
Quad mode for four-leg metal configurations
Crypto tertiary swapped from TOTAL3 (market-cap index, no clean OHLC) to XRP (tradeable asset with proper sweep behavior)
License: Mozilla Public License 2.0 脚本库

脚本库

脚本库

lib_fvgLibrary "lib_fvg"
Fair Value Gap engine — detection, testing/inversion lifecycle, HTF nesting filters, entry-candidate selection, stop-loss derivation, and FVG drawing — extracted 1:1 from rewrite_strategy.pine.
method equals(this, other)
Namespace types: FVG
Parameters:
this (FVG)
other (FVG)
method remove(this, item)
Namespace types: array
Parameters:
this (array)
item (FVG)
method check_nested_in(this, htf_fvg, check_nested, check_untested, check_nearby, nearby_threshold, check_newer_ltf)
Namespace types: FVG
Parameters:
this (FVG)
htf_fvg (FVG)
check_nested (bool)
check_untested (bool)
check_nearby (bool)
nearby_threshold (float)
check_newer_ltf (bool)
method distance_to_price_post_inverse(this, price)
Namespace types: FVG
Parameters:
this (FVG)
price (float)
method is_higher_tf_or_closer_to_price_than(this, other)
Namespace types: FVG
Parameters:
this (FVG)
other (FVG)
method get_stop_loss(this, entry_price, session_extreme, enable_sl_at_fvg_created_swing_point, trail_session_level_tight_threshold)
Namespace types: FVG
Parameters:
this (FVG)
entry_price (float)
session_extreme (float)
enable_sl_at_fvg_created_swing_point (bool)
trail_session_level_tight_threshold (float)
method delete_bar(this)
Namespace types: Bar
Parameters:
this (Bar)
method delete_fvg(this)
Namespace types: FVG
Parameters:
this (FVG)
log_entry_rejection(enable_log, fvg, reason, smt, note)
Parameters:
enable_log (bool)
fvg (FVG)
reason (series EntryFilterReason)
smt (SMT type from Danieltrade29292/lib_smt/1)
note (string)
method invalidate_fvg(this, fvg, reason, entry_block_reason, lifecycle)
Namespace types: FVGBuffer
Parameters:
this (FVGBuffer)
fvg (FVG)
reason (series FVGFilterReason)
entry_block_reason (series EntryFilterReason)
lifecycle (series FVGLifecycle)
method add_fvg(this, fvg, enable_single_fvg_per_tf)
Namespace types: FVGBuffer
Parameters:
this (FVGBuffer)
fvg (FVG)
enable_single_fvg_per_tf (bool)
method detect_fvg(this, tf, tf_id, t2, h2, l2, h1, l1, h0, l0, min_gap_size, fvg_deprecation_period, enable_single_fvg_per_tf)
Namespace types: FVGBuffer
Parameters:
this (FVGBuffer)
tf (string)
tf_id (int)
t2 (int)
h2 (float)
l2 (float)
h1 (float)
l1 (float)
h0 (float)
l0 (float)
min_gap_size (float)
fvg_deprecation_period (int)
enable_single_fvg_per_tf (bool)
method invalidate_all_of_direction(this, fvg_is_bullish, reason)
Namespace types: FVGBuffer
Parameters:
this (FVGBuffer)
fvg_is_bullish (bool)
reason (series FVGFilterReason)
method invalidate_fvgs_inversed_pre_smt(this, smt_buffer, enable_log)
Namespace types: FVGBuffer
Parameters:
this (FVGBuffer)
smt_buffer (SMTBuffer type from Danieltrade29292/lib_smt/1)
enable_log (bool)
method try_park_in(this, htf_pool, check_nested, check_untested, check_nearby, nearby_threshold, check_newer_ltf)
Namespace types: FVG
Parameters:
this (FVG)
htf_pool (array)
check_nested (bool)
check_untested (bool)
check_nearby (bool)
nearby_threshold (float)
check_newer_ltf (bool)
method update_htf_relations(this, enable_filter_by_full_nest_in_HTF_fvg, enable_filter_by_untested, enable_filter_by_edge_nearby_HTF_fvg, nearby_HTF_threshold, enable_filter_by_newer_LTF_fvg)
Namespace types: FVGBuffer
Parameters:
this (FVGBuffer)
enable_filter_by_full_nest_in_HTF_fvg (bool)
enable_filter_by_untested (bool)
enable_filter_by_edge_nearby_HTF_fvg (bool)
nearby_HTF_threshold (float)
enable_filter_by_newer_LTF_fvg (bool)
method update_fvgs(this, tf2, tf2_updated, fvg2_o, fvg2_h, fvg2_l, fvg2_c, tf3, tf3_updated, fvg3_o, fvg3_h, fvg3_l, fvg3_c, tf4, tf4_updated, fvg4_o, fvg4_h, fvg4_l, fvg4_c, min_inversion_distance, max_inversion_distance, tested_by_mode, max_tests_before_inverse)
Namespace types: FVGBuffer
Parameters:
this (FVGBuffer)
tf2 (string)
tf2_updated (bool)
fvg2_o (float)
fvg2_h (float)
fvg2_l (float)
fvg2_c (float)
tf3 (string)
tf3_updated (bool)
fvg3_o (float)
fvg3_h (float)
fvg3_l (float)
fvg3_c (float)
tf4 (string)
tf4_updated (bool)
fvg4_o (float)
fvg4_h (float)
fvg4_l (float)
fvg4_c (float)
min_inversion_distance (float)
max_inversion_distance (float)
tested_by_mode (series FVGTestedByMode)
max_tests_before_inverse (int)
method find_next_best_waiting_fvgs(this, smt_buffer)
Namespace types: FVGBuffer
Parameters:
this (FVGBuffer)
smt_buffer (SMTBuffer type from Danieltrade29292/lib_smt/1)
method find_entry_candidate_fvg(this, smt_buffer, enable_filter_by_inversion_bar_close_in_untested_HTF_fvg, enable_log)
Namespace types: FVGBuffer
Parameters:
this (FVGBuffer)
smt_buffer (SMTBuffer type from Danieltrade29292/lib_smt/1)
enable_filter_by_inversion_bar_close_in_untested_HTF_fvg (bool)
enable_log (bool)
method draw_bar(this, is_bullish, bgcolor, border_color, labelcolor, txt, show_box)
Namespace types: Bar
Parameters:
this (Bar)
is_bullish (bool)
bgcolor (color)
border_color (color)
labelcolor (color)
txt (string)
show_box (bool)
method draw_fvg(this, color_bull, color_bear, debug)
Namespace types: FVG
Parameters:
this (FVG)
color_bull (color)
color_bear (color)
debug (bool)
method draw_fvgs(this, color_bull, color_bear, debug)
Namespace types: array
Parameters:
this (array)
color_bull (color)
color_bear (color)
debug (bool)
method draw_entry_fvg(this, color_bull, color_bear, debug)
Namespace types: FVG
Parameters:
this (FVG)
color_bull (simple color)
color_bear (simple color)
debug (bool)
method delete_fvgs(this)
Namespace types: array
Parameters:
this (array)
Bar
Fields:
o (series float)
h (series float)
l (series float)
c (series float)
top (series float)
btm (series float)
t_open (series int)
i_open (series int)
t_close (series int)
i_close (series int)
bar_box (series box)
bar_label (series label)
FVG
Fields:
is_bullish_original (series bool)
is_bullish_post_inverse (series bool)
tf (series string)
tf_id (series int)
top_left (chart.point)
bottom_right (chart.point)
hh (series float)
ll (series float)
deprecate_at (series int)
sl_level (series float)
is_active (series bool)
test_count (series int)
first_test_idx (series int)
is_inversed (series bool)
has_touched (series bool)
fvg_box (series box)
tooltip_label (series label)
hidden (series bool)
draw_signal_inversed (series bool)
draw_signal_text (series bool)
draw_signal_highlight (series bool)
draw_signal_set_candidate (series bool)
draw_signal_reset_candidate (series bool)
fill_state (series FVGFillState)
lifecycle (series FVGLifecycle)
filter_reason (series FVGFilterReason)
entry_filter_reason (series EntryFilterReason)
tf_inversion_bar (Bar)
inversion_idx (series int)
FVGBuffer
Fields:
items (array)
inversed (array)
invalidated (array) 脚本库

lib_smtLibrary "lib_smt"
SMT divergence + session detection/lifecycle, SMT buffers, premium/discount zones, and their on-chart drawing — extracted 1:1 from rewrite_strategy.pine.
method equals(this, other)
Namespace types: SMT
Parameters:
this (SMT)
other (SMT)
method delete_smt(this)
Namespace types: SMT
Parameters:
this (SMT)
method delete_smts(this)
Namespace types: array
Parameters:
this (array)
method replace(this, value)
Namespace types: array
Parameters:
this (array)
value (Session)
method replace(sess, idx, value, remove_buffer)
Namespace types: array
Parameters:
sess (array)
idx (int)
value (Session)
remove_buffer (array)
method reset(this)
Namespace types: SessionSignals
Parameters:
this (SessionSignals)
method reset(this)
Namespace types: SessionLevel
Parameters:
this (SessionLevel)
method reset(this)
Namespace types: Session
Parameters:
this (Session)
method invalidate_smt(this, smt, reason)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
smt (SMT)
reason (series SMTFilterReason)
method invalidate_session(this, sess, reason)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
sess (Session)
reason (series SMTFilterReason)
method set_intra(this, smt)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
smt (SMT)
method reset_intra(this, reason, sess, reset_bull, reset_bear)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
reason (series SMTFilterReason)
sess (Session)
reset_bull (bool)
reset_bear (bool)
method invalidate_all_daily_smts(this, reason)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
reason (series SMTFilterReason)
method invalidate_all_session_smts(this, is_bullish, reason)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
is_bullish (bool)
reason (series SMTFilterReason)
method invalidate_entry_daily_smt(this, entry_smt, reason)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
entry_smt (SMT)
reason (series SMTFilterReason)
method invalidate_by_detected_session_id(this, id, reason)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
id (int)
reason (series SMTFilterReason)
method invalidate_swept_sessions(this, session_signals, overflow_buffer)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
session_signals (SessionSignals)
overflow_buffer (array)
method add_smt(this, smt)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
smt (SMT)
method update_smt(this, other_high, other_low, smt_buffer, enable_invalidation_by_distance, invalidation_dist_chart_led, invalidation_dist_other_led)
Namespace types: SMT
Parameters:
this (SMT)
other_high (float)
other_low (float)
smt_buffer (SMTBuffer)
enable_invalidation_by_distance (bool)
invalidation_dist_chart_led (float)
invalidation_dist_other_led (float)
method update_smts(this, other_high, other_low, enable_invalidation_by_distance, invalidation_dist_chart_led, invalidation_dist_other_led)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
other_high (float)
other_low (float)
enable_invalidation_by_distance (bool)
invalidation_dist_chart_led (float)
invalidation_dist_other_led (float)
method update_session_level_sweeps(this, other_high, other_low)
Namespace types: Session
Parameters:
this (Session)
other_high (float)
other_low (float)
method detect_smt(this, smt_h1, smt_l1, smt_c1, smt_other_h1, smt_other_l1, is_smt_tf_new_bar, smt_buffer, active_session_id, smt_min_age, is_intra, is_blocked_intra_smt_bull, is_blocked_intra_smt_bear, timeout_intra, touch_tolerance, intra_min_swing_age)
─────────────────────────────────────────────────────────────────────────────
session.detect_smt — check if chart/other has swept H or L
§2.2.1 Level SMT Detection / §2.2.2 Daily SMT Detection / §2.2.3 Intra SMT Detection
is_intra=true → called on live active session (§2.2.3); uses running H/L, equal high/low counts
is_intra=false → called on archived session (§2.2.1/§2.2.2); levels are fixed at capture time
active_session_id: session currently open, stored as detected_session_id on new SMTs
so §2.3.2 London-detected invalidation can filter correctly on NY open
─────────────────────────────────────────────────────────────────────────────
Namespace types: Session
Parameters:
this (Session)
smt_h1 (float)
smt_l1 (float)
smt_c1 (float)
smt_other_h1 (float)
smt_other_l1 (float)
is_smt_tf_new_bar (bool)
smt_buffer (SMTBuffer)
active_session_id (int)
smt_min_age (int)
is_intra (bool)
is_blocked_intra_smt_bull (bool)
is_blocked_intra_smt_bear (bool)
timeout_intra (int)
touch_tolerance (float)
intra_min_swing_age (int)
method detect_smts(this, signals, smt_h1, smt_l1, smt_c1, smt_other_h1, smt_other_l1, is_smt_tf_new_bar, smt_buffer, active_session_id, smt_min_age, touch_tolerance)
Namespace types: array
Parameters:
this (array)
signals (SessionSignals)
smt_h1 (float)
smt_l1 (float)
smt_c1 (float)
smt_other_h1 (float)
smt_other_l1 (float)
is_smt_tf_new_bar (bool)
smt_buffer (SMTBuffer)
active_session_id (int)
smt_min_age (int)
touch_tolerance (float)
method has_active_daily_smt(this, seeks_bullish)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
seeks_bullish (bool)
method find_best_smt_by_prio(this, minimum_prio, seeks_bullish)
Namespace types: array
Parameters:
this (array)
minimum_prio (int)
seeks_bullish (bool)
method find_best_smt_by_direction(this, intra_smts_enabled, seeks_bullish)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
intra_smts_enabled (bool)
seeks_bullish (bool)
method update_best_smts(this, pd_zone, intra_smts_enabled, allow_bullish_intra_smt_post_cutoff_if_has_daily_smt_active, allow_bearish_intra_smt_post_cutoff_if_has_daily_smt_active)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
pd_zone (int)
intra_smts_enabled (bool)
allow_bullish_intra_smt_post_cutoff_if_has_daily_smt_active (bool)
allow_bearish_intra_smt_post_cutoff_if_has_daily_smt_active (bool)
method rotate(this, sess, max)
Namespace types: array
Parameters:
this (array)
sess (Session)
max (int)
method add_session(this, sess, overflow_buffer)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
sess (Session)
overflow_buffer (array)
method evict_consumed_days(this, overflow_buffer, max_history_days)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
overflow_buffer (array)
max_history_days (simple int)
method clear_invalidated_smts(this, keep_level, keep_intra, keep_reason)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
keep_level (bool)
keep_intra (bool)
keep_reason (bool)
method archive(this)
Namespace types: SessionLevel
Parameters:
this (SessionLevel)
method archive(this)
Namespace types: Session
Parameters:
this (Session)
method update_levels(this, is_smt_tf_new_bar, other_high, other_low, smt_t1, smt_h1, smt_l1, smt_other_h1, smt_other_l1)
Namespace types: Session
Parameters:
this (Session)
is_smt_tf_new_bar (bool)
other_high (float)
other_low (float)
smt_t1 (int)
smt_h1 (float)
smt_l1 (float)
smt_other_h1 (float)
smt_other_l1 (float)
method update_session(this, signals, smt_buffer, new_day, other_high, other_low, smt_t1, smt_h1, smt_l1, smt_c1, smt_other_h1, smt_other_l1, is_smt_tf_new_bar, smt_min_age, timeout_intra, in_any_no_intra_smt_zone, enable_block_intra_smts_pre_high_prio_sweep, previous_session, intra_min_swing_age)
Namespace types: Session
Parameters:
this (Session)
signals (SessionSignals)
smt_buffer (SMTBuffer)
new_day (bool)
other_high (float)
other_low (float)
smt_t1 (int)
smt_h1 (float)
smt_l1 (float)
smt_c1 (float)
smt_other_h1 (float)
smt_other_l1 (float)
is_smt_tf_new_bar (bool)
smt_min_age (int)
timeout_intra (int)
in_any_no_intra_smt_zone (bool)
enable_block_intra_smts_pre_high_prio_sweep (bool)
previous_session (Session)
intra_min_swing_age (int)
method draw_session(this, show_chart, show_panel)
Namespace types: Session
Parameters:
this (Session)
show_chart (bool)
show_panel (bool)
method draw_session_consumed(this)
Namespace types: Session
Parameters:
this (Session)
method delete(this)
Namespace types: Session
Parameters:
this (Session)
method delete(this)
Namespace types: array
Parameters:
this (array)
method register(this, enabled, session, _fill_color, _text, _text_color, _border_color, prio, id, is_daily, is_session, enable_intra_smts, is_no_intra_smt_zone, smt_timeout, strategy_config)
Namespace types: array
Parameters:
this (array)
enabled (bool)
session (string)
_fill_color (color)
_text (string)
_text_color (color)
_border_color (color)
prio (int)
id (int)
is_daily (bool)
is_session (bool)
enable_intra_smts (bool)
is_no_intra_smt_zone (bool)
smt_timeout (int)
strategy_config (StrategyConfig)
method short_id(this)
Namespace types: SMT
Parameters:
this (SMT)
method label_text(this, other_ticker, include_filter_reason, is_leader)
Namespace types: SMT
Parameters:
this (SMT)
other_ticker (string)
include_filter_reason (bool)
is_leader (bool)
method draw_smt(this, other_ticker, show_label_leader, show_label_follower, verbose)
Namespace types: SMT
Parameters:
this (SMT)
other_ticker (string)
show_label_leader (bool)
show_label_follower (bool)
verbose (bool)
method draw_smts(this, other_ticker, show_label_leader, show_label_follower, show_filter_reason)
Namespace types: array
Parameters:
this (array)
other_ticker (string)
show_label_leader (bool)
show_label_follower (bool)
show_filter_reason (bool)
get_pd_range(enable, bars_lookback, new_hour)
Parameters:
enable (simple bool)
bars_lookback (int)
new_hour (bool)
draw_pd(new_hour, pd_start, pd_high, pd_equilibrium, pd_low)
Parameters:
new_hour (bool)
pd_start (int)
pd_high (float)
pd_equilibrium (float)
pd_low (float)
SMT
Fields:
detected_session_id (series int)
leader (series int)
leader_level (chart.point)
sweep (chart.point)
follow_level (chart.point)
session_id (series int)
prio (series int)
is_bullish (series bool)
deprecate_at (series int)
detection_bar (series int)
detection_close (series float)
valid_from (series int)
invalidated (series bool)
filter_reason (series SMTFilterReason)
leader_line (series line)
leader_label (series label)
follow_line (series line)
follow_intermediate_line (series line)
follow_label (series label)
smt_color (series color)
draw_remove_highlight (series bool)
used_for_trade (series bool)
trade_end_time (series int)
SessionLevel
tracks session H/L
Fields:
chart (chart.point)
other (chart.point)
chart_smt_tf (chart.point)
other_smt_tf (chart.point)
is_consumed (series bool)
smt (SMT)
StrategyConfig
Fields:
big_win_threshold (series float)
cutoff_hour (series int)
cutoff_tz (series string)
cutoff_mode (series SessionCutoffMode)
max_losses (series int)
max_wins (series int)
Session
Fields:
id (series int)
prio (series int)
timeout (series int)
session (series string)
h (SessionLevel)
l (SessionLevel)
_fill_color (series color)
_text (series string)
_text_color (series color)
_border_color (series color)
is_daily (series bool)
is_session (series bool)
is_no_intra_smt_zone (series bool)
enable_intra_smts (series bool)
strategy_config (StrategyConfig)
start_time (series int)
end_time (series int)
cutoff_at (series int)
is_active (series bool)
is_consumed (series bool)
box_chart (series box)
box_other (series box)
mean_sum (series float)
mean_count (series float)
mean (series float)
is_any_low_swept (series bool)
is_any_high_swept (series bool)
draw_signal_consumed (series bool)
tooltip_chart (series label)
tooltip_other (series label)
SessionSignals
Fields:
signal_session_started (series int)
signal_session_ending (series int)
signal_session_ended (series int)
signal_no_intra_smt_zone_started (series int)
signal_no_intra_smt_zone_ending (series int)
signal_no_intra_smt_zone_ended (series int)
signal_intra_smt_h (series int)
signal_intra_smt_l (series int)
signal_session_consumed (series bool)
SMTBuffer
Fields:
session_smts (array)
daily_smts (array)
intra_smts (array)
invalidated (array)
delete_buffer (array)
monitored_sessions (array)
monitored_days (array)
consumed_days (array)
max_days (series int)
best_bull_smt (SMT)
best_bear_smt (SMT) 脚本库

MarketReactionLibrary "MarketReaction"
Modular library for sessions, Initial Balance, PSY ranges, VWAPs, alerts, and macro sentiment helpers.
getSessionConfig(source)
Returns session config by source name.
Parameters:
source (simple string) : Session source: Tokyo, New York, London, Jerusalem, EU B, US B.
Returns: SessionConfig.
sessionModule(session, timeZone, sessionText, sessionColor, sessionDuration, showVisuals, showLabels, showLines, showMiddleLine, showBg, bgTransp)
Builds session high/low/middle lines, label, background fill and VWAP.
Parameters:
session (simple string) : Session string.
timeZone (simple string) : IANA timezone.
sessionText (simple string) : Label text.
sessionColor (color) : Session color.
sessionDuration (simple int) : Approximate session duration in ms.
showVisuals (bool) : Show this session visuals.
showLabels (bool) : Show labels.
showLines (bool) : Show high/low lines.
showMiddleLine (bool) : Show middle line.
showBg (bool) : Show background fill.
bgTransp (int) : Background transparency.
Returns: SessionResult.
initialBalanceModule(session, ibSession, timeZone, sessionLabel, showDLabels, showWLabels, showMLabels, showPrevD, showPrevW, showPrevM, dColor, wColor, mColor)
Calculates Daily, Weekly, Monthly Initial Balance and W/M IB VWAPs.
Parameters:
session (simple string) : Full session string.
ibSession (simple string) : IB sub-session string.
timeZone (simple string) : IANA timezone.
sessionLabel (simple string) : Session label.
showDLabels (bool) : Show D.IB labels.
showWLabels (bool) : Show W.IB labels.
showMLabels (bool) : Show M.IB labels.
showPrevD (bool) : Calculate previous daily IB.
showPrevW (bool) : Calculate previous weekly IB.
showPrevM (bool) : Calculate previous monthly IB.
dColor (color) : Daily IB label color.
wColor (color) : Weekly IB label color.
mColor (color) : Monthly IB label color.
Returns: IBResult.
psyRangeModule(session, timeZone, showLabels, showPrev, sessionColor)
Calculates PSY high/low, previous PSY levels, labels, and VWAP.
Parameters:
session (simple string) : Session string.
timeZone (simple string) : Timezone.
showLabels (bool) : Show PSY labels.
showPrev (bool) : Show previous PSY levels.
sessionColor (color) : PSY color.
Returns: PSYResult.
rangeSignal(highLevel, lowLevel, price)
Returns enter/exit signals for a range.
Parameters:
highLevel (float) : Range high.
lowLevel (float) : Range low.
price (float) : Price source.
Returns: RangeSignal.
tablePosition(pos)
Converts table position string to Pine position.
Parameters:
pos (simple string) : Position text.
Returns: Pine table position.
SessionConfig
Session configuration.
Fields:
session (series string) : Full session time.
ib (series string) : Initial Balance sub-session time.
tz (series string) : Session timezone.
label (series string) : Session label.
col (series color) : Session color.
duration (series int) : Approximate session duration in milliseconds.
SessionResult
Session result.
Fields:
high (series float) : Session high.
low (series float) : Session low.
mid (series float) : Session middle.
vwap (series float) : Session VWAP.
inSession (series bool) : True if bar is inside session.
firstBar (series bool) : True on first session bar.
highLine (series line) : Session high line.
lowLine (series line) : Session low line.
midLine (series line) : Session middle line.
IBResult
Initial Balance result.
Fields:
dHigh (series float) : Daily IB high.
dLow (series float) : Daily IB low.
pdHigh (series float) : Previous daily IB high.
pdLow (series float) : Previous daily IB low.
wHigh (series float) : Weekly IB high.
wLow (series float) : Weekly IB low.
pwHigh (series float) : Previous weekly IB high.
pwLow (series float) : Previous weekly IB low.
mHigh (series float) : Monthly IB high.
mLow (series float) : Monthly IB low.
pmHigh (series float) : Previous monthly IB high.
pmLow (series float) : Previous monthly IB low.
wVwap (series float) : Weekly IB VWAP.
mVwap (series float) : Monthly IB VWAP.
inSession (series bool) : True if bar is inside selected full session.
inIB (series bool) : True if bar is inside selected IB session.
ibFirstBar (series bool) : True on first IB bar.
sessionFirstBar (series bool) : True on first full-session bar.
PSYResult
PSY range result.
Fields:
high (series float) : Current PSY high.
low (series float) : Current PSY low.
pHigh (series float) : Previous PSY high.
pLow (series float) : Previous PSY low.
vwap (series float) : PSY VWAP.
inSession (series bool) : True if bar is inside PSY range.
firstBar (series bool) : True on first PSY bar.
RangeSignal
Range signal result.
Fields:
enter (series bool) : True when price enters range.
exit (series bool) : True when price exits range.
topDn (series bool) : Crossunder from above high.
topUp (series bool) : Crossover above high.
botUp (series bool) : Crossover from below low.
botDn (series bool) : Crossunder below low. 脚本库

AxiomMovingAverageLibraryAxiom Moving Average Library
Overview
If your Pine script offers a moving average type selector, you have probably written the same dispatch logic more than once. An enum, a switch, and a quiet hope that the next script you copy it into stays consistent with the last one.
This library replaces that pattern. Import it, use the MaType enum for your dropdown, and call get_ma() to route the user's choice to the right computation. Eight standard moving average types — SMA, EMA, RMA, WMA, VWMA, HMA, and SWMA — all backed by Pine's built-in ta.* functions. Nothing custom under the hood.
Why it exists
This is a maintenance problem, and it compounds.
Every Axiom indicator and strategy that gives users a moving average choice needs the same underlying infrastructure: a type list, a dispatcher, and correct parameter handling for each type. When that logic lives inside every script individually, it drifts. One script picks up HMA support; another doesn't. A third gets the defaults wrong. None of this is visible until someone notices that the same configuration produces different behavior across two Axiom tools.
That kind of inconsistency doesn't announce itself — it just erodes confidence in the products over time.
This library makes the dispatch code shared. Every consuming script references the same enum, calls the same wrappers, and gets the same result for the same inputs. The repetitive parts stay consistent so you can focus on the work that's actually yours — choosing which averages to offer, deciding what lengths make sense, and building the logic around the result. The plumbing shouldn't be something you rewrite every time.
Quickstart
import AxiomCharts/AxiomMovingAverageLibrary/1 as maLib
maChoice = input.enum(maLib.MaType.EMA, title = "MA Type")
maLength = input.int(20, title = "MA Length", minval = 1)
maValue = maLib.get_ma(maChoice, close, maLength)
Import the library, give your users a dropdown, and route their selection through get_ma(). That covers the standard integration.
Recommended alias : maLib — short, and it distinguishes this from the Pro library if you end up using both.
API
The library exports three things: an enum, eight individual wrapper functions, and one dispatcher.
MaType enum
Eight values, each mapping to a standard moving average:
MaType.SMA - Simple Moving Average
MaType.EMA - Exponential Moving Average
MaType.RMA - Wilder / Relative Moving Average
MaType.WMA - Weighted Moving Average
MaType.VWMA - Volume-Weighted Moving Average
MaType.HMA - Hull Moving Average
MaType.SWMA - Symmetrically Weighted Moving Average
The enum works directly with input.enum(), so you can wire it into a settings dropdown without building your own type list.
Wrapper functions
Each type has a named function: ma_sma(src, length), ma_ema(src, length), ma_rma(src, length), ma_wma(src, length), ma_vwma(src, length), ma_hma(src, length), and ma_swma(src).
Two behaviors worth knowing before you use them:
SWMA takes no length. Pine's ta.swma applies a fixed symmetrical weighting over 4 bars. The wrapper accepts src only. If you route through get_ma with MaType.SWMA, the length argument is accepted for signature consistency but ignored. The window is always 4.
get_ma dispatcher
Accepts a MaType value and routes to the correct wrapper. If an unrecognized value reaches the switch, it falls back to SMA as a safety net.
Examples
Direct wrapper call
When you only need one moving average type and don't need a dropdown:
import AxiomCharts/AxiomMovingAverageLibrary/1 as maLib
smoothed = maLib.ma_ema(close, 20)
For a single MA type in a single script, a direct ta.ema(close, 20) is simpler and carries no dependency. The library earns its keep when you need the shared enum or when multiple scripts need to stay in sync.
User-selectable dropdown
The most common pattern — let users pick the MA type from a settings menu:
import AxiomCharts/AxiomMovingAverageLibrary/1 as maLib
maChoice = input.enum(maLib.MaType.EMA, title = "MA Type")
maLength = input.int(20, title = "MA Length", minval = 1)
maValue = maLib.get_ma(maChoice, close, maLength)
Watch for: VWMA on symbols without volume
ta.vwma requires volume data. On symbols that don't report volume — some forex feeds, certain indices — the result is na. The library does not guard against this. If your script includes VWMA as an option, handle the no-volume case in your own code.
FAQ
What's the difference between Lite and Pro?
Lite covers eight standard moving averages. Each one wraps a Pine built-in — no custom math involved. The Pro library adds thirteen additional types on top of those eight, including DEMA, TEMA, KAMA, JMA, FRAMA, T3MA, VAMA, ZLMA, ZLEMA, Laguerre, and McGinley variants. If your needs outgrow the standard eight, that's when Pro becomes relevant.
Why doesn't SWMA accept a length?
That's a Pine constraint. ta.swma applies a fixed symmetrical weighting across 4 bars. There is no length parameter to pass, so the wrapper doesn't accept one either. If you route through get_ma with MaType.SWMA, the length argument is there for API consistency but doesn't affect the output.
Can I use VWMA on any symbol?
Only on symbols that report volume data. On instruments without volume, VWMA returns na. The library won't catch that for you — if your script offers VWMA, check for volume data and handle the na case in your own code.
What Pine version do I need?
Pine v6. The library uses v6 enum syntax, so scripts on v5 or earlier cannot import it.
Limitations
Pine v6 required. Scripts on earlier versions cannot import this library.
Eight standard types only. Adaptive averages (KAMA, JMA, FRAMA), lag-compensated filters (T3MA, ZLMA, McGinley), and other specialized types are not included. The Pro library covers those.
SWMA uses a fixed 4-bar window. The length parameter passed through get_ma is ignored for SWMA.
VWMA needs volume data. On symbols without volume, it returns na. Your script should account for this.
The SMA fallback is a safety net, not a feature. If an unrecognized value reaches get_ma, it defaults to SMA. In practice, Pine's enum type system prevents this at compile time. Don't build routing logic around it.
Versioning and release notes
Pin your import to a specific version number you have actually verified in the environment where you are using the library:
import AxiomCharts/AxiomMovingAverageLibrary/
If you later need to move from Lite to Pro, expect changes: a different library title and an expanded MaType enum with additional values. It's not a drop-in swap — your code will need updating.
Support and training
Visit our website at axiomcharts.com for any documentation or questions.
Disclaimer
This library is published for educational and informational purposes. It provides standardized moving average computation utilities for Pine Script developers. It does not generate trading signals, recommend positions, or guarantee any financial outcome. All trading decisions and their consequences are yours. Use this library as one part of your own research and process. 脚本库

脚本库
