ChatgptLibraryLibrary "ChatgptLibrary"
TODO: add library description here
effective_period(high_series, low_series, volume_series, period_length, lookback_length, max_search)
Calculates adaptive effective period.
Parameters:
high_series (float) : High price series.
low_series (float) : Low price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: Adaptive effective period.
adaptive_ema(source, high_series, low_series, volume_series, period_length, lookback_length, max_search)
Adaptive EMA using effective period.
Parameters:
source (float) : Source series.
high_series (float) : High price series.
low_series (float) : Low price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: Adaptive EMA, alpha and effective period.
adaptive_channel(high_series, low_series, volume_series, period_length, lookback_length, smooth_length, max_search)
Adaptive price channel.
Parameters:
high_series (float) : High price series.
low_series (float) : Low price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
lookback_length (simple int) : EMA lookback multiplier.
smooth_length (simple int) : EMA smoothing.
max_search (int) : Maximum search distance.
Returns: Effective period, upper, lower, middle and width.
adaptive_rsi(source, high_series, low_series, volume_series, period_length, lookback_length, max_search)
Adaptive RSI.
Parameters:
source (float) : Source series.
high_series (float) : High price series.
low_series (float) : Low price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: Adaptive RSI and effective period.
adaptive_atr(high_series, low_series, close_series, volume_series, period_length, lookback_length, max_search)
Adaptive ATR.
Parameters:
high_series (float) : High price series.
low_series (float) : Low price series.
close_series (float) : Close price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: Adaptive ATR and effective period.
adaptive_macd(source, high_series, low_series, volume_series, fast_period, slow_period, signal_period, lookback_length, max_search)
Adaptive MACD.
Parameters:
source (float) : Source series.
high_series (float) : High price series.
low_series (float) : Low price series.
volume_series (float) : Volume series.
fast_period (simple int) : Fast adaptive period.
slow_period (simple int) : Slow adaptive period.
signal_period (int) : Signal EMA period.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: MACD, Signal, Histogram.
adaptive_bollinger(source, high_series, low_series, volume_series, period_length, deviation, lookback_length, max_search)
Adaptive Bollinger Bands.
Parameters:
source (float) : Source series.
high_series (float) : High price series.
low_series (float) : Low price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
deviation (float) : Standard deviation multiplier.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: Upper band, Middle band, Lower band, Band width and Effective period.
adaptive_supertrend(high_series, low_series, close_series, volume_series, period_length, multiplier, lookback_length, max_search)
Adaptive SuperTrend.
Parameters:
high_series (float) : High price series.
low_series (float) : Low price series.
close_series (float) : Close price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
multiplier (float) : ATR multiplier.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: SuperTrend, Trend Direction and Effective Period.
adaptive_donchian(high_series, low_series, volume_series, period_length, lookback_length, max_search)
Adaptive Donchian Channel.
Parameters:
high_series (float) : High price series.
low_series (float) : Low price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: Upper band, Lower band, Middle line, Width and Effective period.
adaptive_keltner(source, high_series, low_series, close_series, volume_series, period_length, multiplier, lookback_length, max_search)
Adaptive Keltner Channel.
Parameters:
source (float) : Source series.
high_series (float) : High price series.
low_series (float) : Low price series.
close_series (float) : Close price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
multiplier (float) : ATR multiplier.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: Upper band, Middle band, Lower band, Width and Effective period.
adaptive_adx(high_series, low_series, close_series, volume_series, period_length, lookback_length, max_search)
Adaptive ADX.
Parameters:
high_series (float) : High price series.
low_series (float) : Low price series.
close_series (float) : Close price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: ADX, +DI, -DI and Effective Period.
adaptive_stochastic(close_series, high_series, low_series, volume_series, period_length, smooth_k, smooth_d, lookback_length, max_search)
Adaptive Stochastic.
Parameters:
close_series (float) : Close price series.
high_series (float) : High price series.
low_series (float) : Low price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
smooth_k (int) : K smoothing.
smooth_d (int) : D smoothing.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: K, D and Effective Period.
adaptive_cci(high_series, low_series, close_series, volume_series, period_length, lookback_length, max_search)
Adaptive Commodity Channel Index.
Parameters:
high_series (float) : High price series.
low_series (float) : Low price series.
close_series (float) : Close price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: CCI and Effective Period.
adaptive_williams_r(high_series, low_series, close_series, volume_series, period_length, lookback_length, max_search)
Adaptive Williams %R.
Parameters:
high_series (float) : High price series.
low_series (float) : Low price series.
close_series (float) : Close price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: Williams %R and Effective Period.
adaptive_roc(source, high_series, low_series, volume_series, period_length, lookback_length, max_search)
Adaptive Rate of Change.
Parameters:
source (float) : Source series.
high_series (float) : High price series.
low_series (float) : Low price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: ROC and Effective Period.
adaptive_pivot(source, left_bars, right_bars)
Adaptive Pivot Detector.
Parameters:
source (float) : Source series.
left_bars (int) : Left pivot bars.
right_bars (int) : Right pivot bars.
Returns: Pivot High, Pivot Low, Pivot High Price, Pivot Low Price.
adaptive_divergence(price_source, indicator_source, pivot_length)
Adaptive Divergence Detector.
Parameters:
price_source (float) : Price series.
indicator_source (float) : Indicator series.
pivot_length (int) : Pivot length.
Returns: Bullish divergence, Bearish divergence and Divergence strength.
adaptive_pivot_divergence(price_source, signal_source, pivot_length)
Adaptive Pivot Divergence Detector.
Parameters:
price_source (float) : Price series.
signal_source (float) : Indicator series.
pivot_length (int) : Pivot length.
Returns: Bullish divergence, Bearish divergence and Divergence strength.
adaptive_flat_channel(upper_channel, lower_channel, flat_length, tolerance)
Adaptive Flat Channel Detector.
Parameters:
upper_channel (float) : Upper channel.
lower_channel (float) : Lower channel.
flat_length (int) : Number of bars to evaluate.
tolerance (float) : Maximum allowed movement.
Returns: Flat upper, Flat lower and Flat channel.
adaptive_breakout_strength(close_series, upper_channel, lower_channel, channel_width, volume_series, volume_length)
Adaptive Breakout Strength.
Parameters:
close_series (float) : Close price.
upper_channel (float) : Upper channel.
lower_channel (float) : Lower channel.
channel_width (float) : Channel width.
volume_series (float) : Volume.
volume_length (simple int) : Volume EMA length.
Returns: Breakout direction and Breakout strength.
adaptive_channel_rejection(open_series, high_series, low_series, close_series, upper_channel, lower_channel)
Adaptive Channel Rejection.
Parameters:
open_series (float) : Open price.
high_series (float) : High price.
low_series (float) : Low price.
close_series (float) : Close price.
upper_channel (float) : Upper channel.
lower_channel (float) : Lower channel.
Returns: Rejection direction and Rejection strength.
adaptive_channel_compression(channel_width, compression_length)
Adaptive Channel Compression.
Parameters:
channel_width (float) : Width of the channel.
compression_length (simple int) : Number of bars.
Returns: Compression ratio, Is compressing, Is expanding.
adaptive_market_energy(channel_width, volume_series, volume_length)
Adaptive Market Energy.
Parameters:
channel_width (float) : Width of channel.
volume_series (float) : Volume series.
volume_length (simple int) : Volume EMA length.
Returns: Energy score.
adaptive_market_phase(adx, rsi, compression_ratio, breakout_strength)
Adaptive Market Phase.
Parameters:
adx (float) : Adaptive ADX.
rsi (float) : Adaptive RSI.
compression_ratio (float) : Channel compression ratio.
breakout_strength (float) : Breakout strength.
Returns: Market phase.
adaptive_rsi_zigzag(rsi_series, center_level, lookback_length)
Adaptive RSI Zigzag Detector.
Parameters:
rsi_series (float) : RSI series.
center_level (float) : Center level.
lookback_length (int) : Number of bars.
Returns: Zigzag count and Zigzag detected.
adaptive_flat_level(level_series, flat_length, tolerance)
Adaptive Flat Level Detector.
Parameters:
level_series (float) : Channel upper or lower series.
flat_length (int) : Number of bars.
tolerance (float) : Maximum allowed movement.
Returns: Flat state and Flat strength.
adaptive_level_strength(level_series, high_series, low_series, tolerance, lookback_length)
Adaptive Level Strength.
Parameters:
level_series (float) : Support or resistance level.
high_series (float) : High price series.
low_series (float) : Low price series.
tolerance (float) : Touch tolerance.
lookback_length (int) : Number of bars.
Returns: Touch count and Level strength.
adaptive_breakout_probability(breakout_strength, level_strength, compression_ratio, volume_ratio)
Adaptive Breakout Probability.
Parameters:
breakout_strength (float) : Breakout strength.
level_strength (float) : Level strength.
compression_ratio (float) : Channel compression ratio.
volume_ratio (float) : Volume ratio.
Returns: Breakout probability.
adaptive_reversal_probability(rsi, divergence_strength, rejection_strength, flat_strength, channel_width_percent)
Adaptive Reversal Probability.
Parameters:
rsi (float) : Relative Strength Index.
divergence_strength (float) : Divergence strength.
rejection_strength (float) : Rejection strength.
flat_strength (float) : Flat level strength.
channel_width_percent (float) : Channel width percentage.
Returns: Reversal probability.
adaptive_trend_exhaustion(rsi, adx, momentum, roc)
Adaptive Trend Exhaustion.
Parameters:
rsi (float) : Relative Strength Index.
adx (float) : Average Directional Index.
momentum (float) : Momentum.
roc (float) : Rate of Change.
Returns: Trend exhaustion score.
adaptive_channel_memory(upper_channel, lower_channel, tolerance, lookback_length)
Adaptive Channel Memory.
Parameters:
upper_channel (float) : Upper channel.
lower_channel (float) : Lower channel.
tolerance (float) : Maximum channel difference.
lookback_length (int) : Number of bars.
Returns: Memory score.
adaptive_false_breakout(breakout_strength, rejection_strength, volume_ratio)
Adaptive False Breakout Detector.
Parameters:
breakout_strength (float) : Breakout strength.
rejection_strength (float) : Rejection strength.
volume_ratio (float) : Current volume divided by average volume.
Returns: False breakout probability.
adaptive_trap_detector(breakout_direction, breakout_strength, rejection_strength, rsi)
Adaptive Trap Detector.
Parameters:
breakout_direction (int) : Breakout direction.
breakout_strength (float) : Breakout strength.
rejection_strength (float) : Rejection strength.
rsi (float) : Relative Strength Index.
Returns: Trap direction and Trap probability.
adaptive_rsi_behavior(rsi, zigzag_count, divergence_strength, rejection_strength)
Adaptive RSI Behavior.
Parameters:
rsi (float) : Relative Strength Index.
zigzag_count (int) : RSI zigzag count.
divergence_strength (float) : Divergence strength.
rejection_strength (float) : Rejection strength.
Returns: RSI behavior score.
adaptive_market_behavior(trend_strength, reversal_probability, breakout_probability, exhaustion, energy, rsi_behavior)
Adaptive Market Behavior.
Parameters:
trend_strength (float) : Trend strength.
reversal_probability (float) : Reversal probability.
breakout_probability (float) : Breakout probability.
exhaustion (float) : Trend exhaustion.
energy (float) : Market energy.
rsi_behavior (float) : RSI behavior.
Returns: Market behavior score. Library

EWCoreLibEWCoreLib — Elliott Wave Pattern Evaluation Library
Overview
EWCoreLib is a Pine Script v6 library of exported functions that validate and score Elliott Wave price patterns. It has no chart output of its own and is not meant to be added to a chart; a calling script supplies the pivot data and decides what to do with the results.
It is one of three scripts published together: the EWCore indicator, this library, and EWCore Docs, an on-chart reference panel for EWCore.
If you are using EWCore, there is nothing to do here. EWCore pulls in this library itself, as part of its own code — you add EWCore to your chart and the library comes with it. This page exists for Pine programmers who want to call these functions from a script of their own, and as the open source behind EWCore's evaluation stage. The dependency runs one way only: EWCore needs this library, the library needs nothing from EWCore, and any script that can produce its own pivot series can use it.
Relation to the earlier publication
An earlier version of this library was published under the name EWCoreEvaluators. This publication continues the same codebase under a new name; it is not a variant or a competing implementation. The name changed because the earlier title stays bound to the earlier publication and cannot be reused. Any script that imports the old path should be pointed at Wick-Sniper/EWCoreLib, which is the one that receives further work.
Concepts
Pivots in, verdicts out. Every evaluator takes a pivot series — prices and bar positions in two parallel arrays — plus a starting index, and asks one question about the window beginning there: does this stretch of price form the pattern I check for? The answer comes back as a filled WaveCount object carrying the wave points, the hard-rule verdict, the component scores and an invalidation level, or as an empty one if the window does not qualify.
Configuration travels as an object, not as a parameter list. An exported function cannot read the global variables of the script importing it, and these evaluators need a great many settings — tolerances, score weights, Fibonacci levels, feature toggles. Passing them individually would mean unwieldy signatures that break on every added option. Instead the calling script builds one EngineConfig object per bar and hands it to whichever functions it calls.
Every exported function is pure. Parameters in, values out, no hidden state. That is what makes it safe to call the same evaluator from several contexts in one bar — a forward search, a historical chain walk, a sub-wave decomposition — without behaviour drifting between them.
Marginal violations are penalised, not rejected. A candidate that misses a rule by a hair is scored down rather than discarded, so a near-miss reading stays visible and comparable instead of vanishing silently.
Exported types
WaveCount — one complete candidate scenario: pattern type, direction, degree label, wave points and their bars, hard-rule and overlap flags, component scores, confidence tier, invalidation level, extension info.
EngineConfig — the settings bundle described above.
Exported functions, by purpose
Pattern evaluation — one per pattern in the canon this project supports: evaluateImpulseWindow, evaluateDiagonalWindow, evaluateZigzagFlatWindow, evaluateTriangleWindow, evaluateComboWXYWindow, evaluateComboWXYXZWindow, evaluateImpulseRecoveredWindow (rebuilds an impulse whose fourth wave the coarse pivot pass swallowed), evaluateLegWhole (judges a whole leg as a single structure rather than a chain of fragments).
Type arbitration — f_discriminateWindow, f_evalWindowTrio: when impulse, diagonal and triangle all pass on the same window, these decide which type the window really is, so the least strict pattern cannot win by default.
Re-checking and scoring — revalidateCandidate, f_comboBonus, f_dpEdgeModifier, f_legDominance, f_legWholeDominance, f_evalCandDegStep, f_evalFloorLeg, f_candDegPasses, f_floorLegPasses.
Chain and gap handling — f_realGapFill (dynamic-programming best-path search for a continuous chain of valid patterns across a pivot series), f_gapNoiseMetrics, f_depth2InnerLegs.
Degree handling — getDegreeLabel, shiftDegreeUp, shiftDegreeDown, f_degreeNameFor, f_notatedLabelTextArray: translate between Elliott degrees and the notation that belongs to each.
Explanatory text — f_patternExplanation, f_extGlyph, f_extTooltip, f_atomicDiagText, f_gapBridgeText, f_rankStage, f_rankWhy, impulseFunnelText, comboFunnelText: turn a verdict into readable reasoning for labels and tooltips.
Drawing helpers — drawImpulseFunnel, drawComboFunnel, f_drawWholeLegFallback, f_drawWholeLegFallbackFromPivots, f_drawWholeLegFallbackFromArrays, f_drawExplanationLabel, f_drawDateMarker, f_drawRoutedLeg.
Utilities — subLowerBound, f_barValToTime (resolves a stored bar value to a timestamp; historical drawings need xloc.bar_time), getLabelSize, f_lineStyle, f_frameCount.
Calling it from your own script
This section is for Pine programmers writing their own script. EWCore users can skip it — EWCore handles the import itself.
import Wick-Sniper/EWCoreLib/1 as ewcore
Type the alias by hand. The "copy to clipboard" button on the library page appends the library name a second time and produces an import line that does not resolve.
From there, build an EngineConfig once per bar, then call the evaluator for the pattern and window you are testing and read the returned WaveCount.
Notes
This library validates structure; it does not detect pivots. The quality of everything it returns depends on the pivot series you feed it — a threshold that admits noise produces confident verdicts about noise. In this project's own testing, wave counting becomes reliable at 15-minute charts and above.
A passing verdict means a reading exists that satisfies the rules checked, not that it is the correct count. Elliott Wave analysis admits more than one valid interpretation of the same chart, and these functions score candidates rather than settle them.
This library is a technical analysis building block. It is not financial advice and generates no trading signals. Library

Public_Library_ChessTalkThis is where the Chess script keeps its trash talk. The library stores every line the computer can say, and decides when it speaks and which line it picks. It imports nothing, knows nothing about chess, and never calls `math.random()`.
There are eight kinds of occasion: the computer won material, it lost material, it promoted, it's still in its opening book, the game just started, it wins, it loses, or the game ends in a draw. Each occasion fires at its own rate, so the computer needles you now and then rather than commenting on every move. Every decision comes from arithmetic on a seed boiled down from the moves played so far, which means the same game always says the same lines, however many times you reload, and a chosen line can't flicker between ticks.
We pass the {piece} token in so that a line can name its victim ("Mmm... free {piece}." becomes "Mmm... free knight."), and per-line filters keep the puns honest - the "good knight" gag only fires when a knight actually dies. A no-repeat rule stops a category saying the same line twice in a row. The banks run to 97 lines of misquoted pop culture.
The `buildTalkState()` function packs the banks, the rates, the no-repeat memory and the wounded detection into one object, so the consumer holds one variable instead of fifteen. The consumer spots the occasion while it replays the game, asks this library for a line, and stores what it gets. The live bar only reads.
See the Chess script for the backchat in action:
Library

Public_Library_ChessBookThis library holds the opening book for the Chess script. It lives apart from the brain (ChessAI) so the openings can grow without republishing the logic. It imports nothing and contains no logic of its own beyond building the map.
Each entry pairs the moves played so far (both sides' moves, lowercase, one space between) with our reply, written the same way - so the key "e2e4 e7e5" answers with "g1f3". Some entries offer several replies separated by "|", and the consumer picks between them with its game seed, so back-to-back games can open differently. The empty-string key holds White's very first move.
We use a map because the book question is exactly a lookup: given the moves played so far, what do we reply? Simply query the canonical move string as the map key and if we get a reply that's our move in response.
Pine maps can't hold arrays as values, which is why several replies pack into one "|"-separated string. Of course we could define a UDT that contains an array, but it's overhead. The trade-off of keying by move sequence rather than by position is that an unusual move order into a known position misses the book - the cost is an early exit to the ladder, never a wrong move, and in exchange every entry in the source reads as a real game you can play through.
The book holds enough entries for every common defence and sideline on both sides, deeper main lines, and wider choices in some of them.
This split of data from calculation is worth using for non-chess scripts: when a big lookup table and the logic that reads it live in separate libraries, the table can grow on its own release schedule.
See the Chess script to play the book in a real game: Library

Public_Library_ChessAIThis library is the brain of the Chess script: a small chess opponent built on the ChessCore rules engine.
It is not a search engine. It is a ladder of ten rules that looks at one position, tries the rules in order, and plays the first that fires:
1. Mate in one
2. Opening book
3. Avoid checkmate
4. Defence
5. Win material
6. Safe check
7. Exchange when ahead
8. Endgame
9. Develop
10. Any other safe move
🟩 THE FORESEE
Before the ladder runs, a foresee stage takes every legal move and adds to its object its most likely material outcome. This score comes from the opponent's best replies to our move, and a few captures after that. We look at the opponent's best captures, his checks, his most menacing quiet threats, and what happens if we don't take. We also look briefly whether two checks in a row force mate. Deep thinking follows more replies and reads six half-moves.
The score works mostly as a veto. From the list of possible moves for a ladder stage, we reject the ones that end in us being checkmated. When every legal move walks into one, we toss a coin to decide between playing the least-bad move and resigning.
🟩 KEEPING A WON GAME WON
If we are winning we want to win, not draw. While ahead on material, the quiet rules refuse any move that recreates a position the game has already seen, so it can't shuffle a rook between two good squares forever. And the foresee prices a stalemate at minus the lead it would throw away, so the winning side sidesteps the trap while the losing side, correctly, steers toward it. The endgame rule gives the ladder actual technique (push passers, rook to the seventh, king up to escort) to try to win.
🟩 DETERMINISM
No `math.random()` call decides anything on its own. The first five rules always give the same answer for a position. The last five pick from their pools with a seed the consumer supplies, derived from the game record. Variety between games comes from the consumer script mixing a clock reading into the seed, not from the library.
🟩 PROCESS FLOW
The exported functions are called in a certian order for each position:
ChessCore generates the legal moves.
`annotateMoves()` counts the attackers and defenders on every move's landing square, and notes the cheapest attacker. Every safety test the rules make reads these three numbers.
`filterPromotions()` and `classifyMoves()` trim pointless pawn promotions and flag moves that make the king's cover worse or that just undo the previous move.
The foresee adds a score to each candidate move: `foreseePrepare()` starts the story, `foreseeFinishCaptures()` follows the capture lines, and `foreseeFinishRest()` follows the checks and quiet threats. The consuming script spreads these calls across chart bars so no single bar works too hard.
The ladder rules run in order, `ruleMateInOne()` down to `ruleFallback()`, and the first one that returns a move wins.
See the Chess script to play against this AI: Library

Public_Library_ChessCoreThe rules of chess as a reusable Pine engine. It doesn't display anything or think of any moves. It just defines what is legal. This is the foundation library of the Chess script, and it's built so that any Pine project needing real chess - a different engine, a puzzle board, a game replayer - can build on it without rewriting the rules.
🟩 WHAT IT DOES
Keeps the whole position in one object: the board, whose turn it is, castling rights, the en-passant target, the move clocks, and a cached king square for each side.
Generates every fully legal move for the side to move, including castling, en passant, and promotions. It checks first based on how the pieces can move, and then creates a copy board to test which moves keeps the king out of check - so pins, discovered checks and the en-passant edge cases all just work.
Applies a move to a position and does all the admin.
Detects checkmate, stalemate, and the automatic draws. For threefold repetition it provides position keys and a counting helper. The consumer keeps the key history, because that's the one draw that needs to remember earlier positions, and these functions deliberately hold no history of their own.
Parses a typed move record like "e2e4 e7e5" - junk-tolerant and case-insensitive, so "e2-e4, E7e5" parses the same - and rebuilds it as one tidy canonical string. The Chess consumer uses that canonical record as its opening-book key and its random seed.
🟩 DESIGN NOTES
The big thing here is the scan that answers "who attacks this square?", with variants that count the attackers and price the cheapest one.
Another important part is the test of whether a move is legal on a COPY board. One definition of "attacked" is shared by the move generator, the game-status detection and castling's transit-square tests, so they can never disagree about what check means.
Each generated move is an object whose scoring fields are declared here but filled in from outside - `foreseeScore` for an AI's look-ahead, plus two endgame scores. ChessCore itself never touches them. This declare-then-fill pattern is how a foundational library can carry data that a higher library computes, without circular imports and without parallel arrays.
Internally everything thinks in (row, column), where row 0 is rank 8 (Black's back rank) and column 0 is file "a". Square names like "e4" appear only at the edges.
🟩 WHAT TRUSTS WHAT
The exports look independent, but they lean on each other in ways worth knowing before you build on them:
`applyMove()` trusts its move and changes the position in place. It doesn't re-check legality, so feed it moves from `generateLegalMoves()` - or from `matchLegalMove()`, which picks the move matching typed coordinates out of that list and brings the filled-in castling and en-passant details with it. A move object you build by hand would miss those.
To ask "what if?" without committing, `copyPosition()` first and apply the move to the copy. The generator's own self-check filter runs on such scratch boards, and so does the whole ChessAI look-ahead.
`gameStatusOf()` spots mate, stalemate and the automatic draws, but not threefold repetition, which needs history this library deliberately doesn't keep. Push each new `positionKey()` onto your own array, then ask `isThreefoldRepetition()`. Push first, then ask.
The position caches each king's square so check tests don't scan the board, and `applyMove()` maintains that cache. If you build a custom position by writing to the board matrix yourself, set the king fields to match, or every check test will look at the wrong square.
See the Chess script for the whole thing playing human vs computer: Library

SNIFOFF_51_Lang3Library "SNIFOFF_51_Lang3"
Multilingual translation layer (Group 3) for Smart Trader, SNIF-OFF 5.1, Trade Finder.
Provides 9 exported functions covering the Trade Finder and Signal Health dashboard rows,
the S17/S18/S19 volume scenarios, the PROVISIONAL badge, the Native footprint texts,
12 tooltips, and 4 helper affixes.
All 7 languages live in this single library; SNIFOFF_51_Lang and SNIFOFF_51_Lang2 stay frozen.
f_trVol3(en, lang)
Translates the S17/S18/S19 volume scenario labels.
Parameters:
en (string) : The English scenario label from f_volScenarioMsg (S17/S18/S19 keys only).
lang (string) : The dashboard language selected by the user.
Returns: The translated scenario label. Unmapped inputs return unchanged.
f_volNarr3(sid, deltaDir, liveAlert, lang)
Builds the S17/S18/S19 volume narrative with optional live-spike overlay.
Parameters:
sid (string) : Scenario ID: "S17", "S18", or "S19". Any other ID returns "".
deltaDir (int) : Anchored delta direction (+1 buyers, -1 sellers, 0 balanced) — S17 wording.
liveAlert (bool) : Explosive bar volume spike flag (Live Exception protocol).
lang (string) : The dashboard language selected by the user.
Returns: The multi-line narrative string, or "" for unknown scenario IDs.
f_trBadge3(en, lang)
Translates the Signal Health PROVISIONAL badge.
Parameters:
en (string) : The English badge label ("◌ PROVISIONAL").
lang (string) : The dashboard language selected by the user.
Returns: The translated badge label. Unmapped inputs return unchanged.
f_trTitle3(en, lang)
Translates the Trade Finder and Signal Health section titles.
Parameters:
en (string) : The English section title.
lang (string) : The dashboard language selected by the user.
Returns: The translated section title. Unmapped inputs return unchanged.
f_trTf(en, lang)
Translates Trade Finder and Signal Health state and watch labels.
Parameters:
en (string) : The English state or watch label.
lang (string) : The dashboard language selected by the user.
Returns: The translated label. Unmapped inputs return unchanged.
f_tfNarrative(state, dir, consensus, lang)
Builds the Trade Finder narrative row text.
Parameters:
state (int) : State code 1..10 (see section header for the mapping).
dir (int) : Composite pressure direction (+1 bullish, -1 bearish, 0 flat).
consensus (int) : Number of dimensions agreeing with the composite direction (0-5).
lang (string) : The dashboard language selected by the user.
Returns: The narrative string for the Trade Finder dashboard row.
f_trTipTf(key, lang)
Returns translated tooltip text for Trade Finder and Signal Health cells.
Parameters:
key (string) : Tooltip key identifier (see section header for valid keys).
lang (string) : The dashboard language selected by the user.
Returns: The translated tooltip string. Empty string for unknown keys.
f_trInline3(key, lang)
Returns translated helper affixes used inside composed dashboard strings.
Parameters:
key (string) : Affix key identifier: agree_sfx, live_sfx, bull_pfx, bear_pfx.
lang (string) : The dashboard language selected by the user.
Returns: The translated affix string. Empty string for unknown keys.
f_trTipFp3(key, lang)
Returns Native-footprint display texts for the dashboard.
Parameters:
key (string) : Text key: fp_title_nat, fp_lock_nat, fp_lock_tip_nat, fp_badge_nat.
lang (string) : The dashboard language selected by the user.
Returns: The translated text. Empty string for unknown keys. Library

Isotropic Coordinate System (ICS)Library "ICS"
Isotropic Coordinate System (ICS): a dimensionless price-time space
for scale-invariant chart geometry.
Vertical axis: y = ln(price) / sigma, where sigma is the Yang-Zhang (2000)
minimum-variance, drift-independent, gap-consistent OHLC volatility estimator.
Horizontal axis: two scalings via the XScale enum.
legacy : x = bars / lookback. Linear window fraction. Backward compatible.
isotropic : x = sqrt(bars / lookback), with y additionally divided by
sqrt(lookback). Diffusion-consistent (sqrt-time scaling), so that
tan(theta) equals the z-score of the move and 45 degrees
corresponds to a move of exactly one standard deviation
of the n-bar log-return distribution. Assumes approximately
iid returns within the sigma window (the standard assumption
behind sqrt-time scaling; see Danielsson & Zigrand, 2006, for
its known limits under vol clustering and jumps).
Every output (angle, length, area, centroid) is a pure dimensionless number,
comparable across symbols, currencies, and timeframes.
Reference: Yang, D. & Zhang, Q. (2000), "Drift-Independent Volatility
Estimation Based on High, Low, Open, and Close Prices",
The Journal of Business, 73(3), 477-492.
yangZhangSigma(length)
Yang-Zhang volatility estimator. Minimum-variance, unbiased,
drift-independent, and consistent with opening gaps
(Yang & Zhang, 2000). Uses the unbiased sample variance
(biased = false) for both the overnight and open-to-close
components, matching the estimator's unbiasedness claim.
Parameters:
length (simple int) : (simple int) Rolling window length. Must be >= 2.
Returns: (series float) Per-bar sigma, floored at 1e-10.
toX(bars, lookback, mode)
Dimensionless horizontal coordinate.
Parameters:
bars (int) : (series int) Signed bar distance from the anchor.
lookback (int) : (series int) Window length acting as the horizontal unit.
mode (series XScale) : (series XScale) Scaling mode.
Returns: (series float) Signed dimensionless x.
toY(price, sigma, lookback, mode)
Dimensionless vertical coordinate.
Parameters:
price (float) : (series float) Price. Must be > 0.
sigma (float) : (series float) Yang-Zhang sigma. Must be > 1e-10.
lookback (int) : (series int) Window length (used by isotropic mode only).
mode (series XScale) : (series XScale) Scaling mode.
Returns: (series float) Dimensionless y, or na when inputs are invalid.
moveZScore(dLogPrice, sigma, bars)
Z-score of a log-price move over n bars: dLog / (sigma * sqrt(n)).
In isotropic mode this equals tan(theta) of the same move.
Parameters:
dLogPrice (float) : (series float) ln(target) - ln(anchor).
sigma (float) : (series float) Per-bar Yang-Zhang sigma. Must be > 1e-10.
bars (int) : (series int) Number of bars in the move. Must be > 0.
Returns: (series float) The z-score, or na when inputs are invalid.
triangle(td, anchorPrice, anchorBar, targetPrice, targetBar, sig, lookback, mode)
Right triangle between an anchor and a target, computed entirely
in ICS space. Writes results in place into `td` and returns it.
On invalid inputs every field is set to na, so world X never
receives contaminated numbers.
Parameters:
td (TriangleData) : (TriangleData) Output object, updated in place.
anchorPrice (float) : (series float) Anchor price (world A). Must be > 0.
anchorBar (int) : (series int) Anchor bar_index.
targetPrice (float) : (series float) Target price (world A). Must be > 0.
targetBar (int) : (series int) Target bar_index. Must differ from anchorBar.
sig (float) : (series float) Yang-Zhang sigma. Must be > 1e-10.
lookback (int) : (series int) Horizontal unit window.
mode (series XScale) : (series XScale) Scaling mode.
Returns: (TriangleData) The same `td`, for chaining.
pinTriangle(td, anchorPrice, anchorBar, extremePrice, bodyPrice, curBar, sig, lookback, mode)
Pin (wick) triangle with three vertices in ICS space:
A = anchor, B = candle extreme, C = candle body edge.
Side BC is the wick. theta = signed angle at A between AB and AC.
Since xB = xC, the shoelace area reduces exactly to
0.5 * |yB - yC| * |dx|.
Parameters:
td (TriangleData) : (TriangleData) Output object, updated in place.
anchorPrice (float) : (series float) Anchor price (hh or ll). Must be > 0.
anchorBar (int) : (series int) Anchor bar_index.
extremePrice (float) : (series float) Candle extreme (high or low). Must be > 0.
bodyPrice (float) : (series float) Candle body edge. Must be > 0.
curBar (int) : (series int) Current bar_index. Must differ from anchorBar.
sig (float) : (series float) Yang-Zhang sigma. Must be > 1e-10.
lookback (int) : (series int) Horizontal unit window.
mode (series XScale) : (series XScale) Scaling mode.
Returns: (TriangleData) The same `td`, for chaining.
zeroTri(td)
Resets a TriangleData to na. Use when the structure is inactive,
so inactive periods never enter moving averages or normalization
as fake zero values.
Parameters:
td (TriangleData) : (TriangleData) Object to reset, updated in place.
Returns: (TriangleData) The same `td`, for chaining.
TriangleData
One triangle's measurements in ICS space. All fields dimensionless.
Fields:
theta (series float) : Signed hypotenuse angle in degrees; in isotropic mode tan(theta) is the z-score of the move.
dy (series float) : Signed Euclidean magnitude of the hypotenuse.
area (series float) : Triangle area (>= 0).
centroidY (series float) : Vertical centroid of the triangle.
FrozenAnchors
Anchors frozen at a reference bar, plus activity state.
Fields:
hh (series float) : Highest high at the freeze bar (world-A price units).
ll (series float) : Lowest low at the freeze bar (world-A price units).
mid (series float) : Geometric mean sqrt(hh * ll) at the freeze bar.
bar_x (series int) : bar_index of the freeze bar.
time_x (series int) : time of the freeze bar.
is_active (series bool) : Whether the frozen structure is currently active. Library

SNIFOFF_51_Lang2Library "SNIFOFF_51_Lang2"
Multilingual translation layer (Group 2) for Smart Trader, SNIF-OFF 5.1, Trade Finder.
Provides 21 exported functions with identical signatures to SNIFOFF_51_Lang.
Covers: 10 label functions, 3 narrative engines, 6 tooltip functions,
1 trend description, and 1 inline label function.
f_trSig(en, lang)
Translates trend engine signal labels.
Parameters:
en (string) : The English signal label.
lang (string) : The dashboard language selected by the user.
Returns: The translated signal label string.
f_trConv(en, lang)
Translates conviction level labels.
Parameters:
en (string) : The English conviction label (HIGH, MODERATE, LOW).
lang (string) : The dashboard language.
Returns: The translated conviction label.
f_trCoup(en, lang)
Translates efficiency coupling labels.
Parameters:
en (string) : The English coupling label.
lang (string) : The dashboard language.
Returns: The translated coupling label.
f_trMom(en, lang)
Translates efficiency momentum labels.
Parameters:
en (string) : The English momentum label.
lang (string) : The dashboard language.
Returns: The translated momentum label.
f_trVol(en, lang)
Translates volume scenario display labels.
Parameters:
en (string) : The English scenario label.
lang (string) : The dashboard language.
Returns: The translated scenario label.
f_trVolZone(zone, delta, lang)
Builds the directional arrow + intensity label for the volume zone cell.
Parameters:
zone (string) : The volume zone classification.
delta (int) : The delta direction integer.
lang (string) : The dashboard language.
Returns: The composed volume zone display string.
f_trPocCons(count, lang)
Builds the volume center agreement label.
Parameters:
count (int) : The number of agreeing scales (1-6).
lang (string) : The dashboard language.
Returns: The composed POC consensus display string.
f_trTitle(en, lang)
Translates dashboard module header titles.
Parameters:
en (string) : The English section title.
lang (string) : The dashboard language.
Returns: The translated section title.
f_trBadge(en, lang)
Translates status badge labels.
Parameters:
en (string) : The English badge label.
lang (string) : The dashboard language.
Returns: The translated badge label.
f_trVolLabel(en, lang)
Translates volume data row cell labels.
Parameters:
en (string) : The English label.
lang (string) : The dashboard language.
Returns: The translated data row label.
f_trendNarrative(cas, casDir, div, smD, algn, mBias, mBiasDir, conv, lang)
Builds a human-readable trend situation summary.
Parameters:
cas (bool) : Cascade active flag.
casDir (int) : Cascade direction.
div (bool) : Divergence active flag.
smD (int) : Micro direction.
algn (int) : Alignment score (-6 to +6).
mBias (bool) : Macro bias active flag.
mBiasDir (int) : Macro bias direction.
conv (string) : Conviction label string.
lang (string) : The dashboard language.
Returns: A 3-line narrative string.
f_effNarrative(rz, al, op, td, mom, lang)
Builds a human-readable efficiency situation summary.
Parameters:
rz (string) : Rank zone string.
al (bool) : Aligned flag.
op (bool) : Opposed flag.
td (int) : Trend direction.
mom (string) : Momentum label string.
lang (string) : The dashboard language.
Returns: A 2-line narrative string.
f_volNarrative(sid, td, pocCon, pocMidPrice, conv, mom, liveAlert, lang)
Builds a human-readable 3-line volume situation summary.
Parameters:
sid (string) : Scenario ID (S1–S16).
td (int) : Trend direction.
pocCon (int) : Volume center consensus count.
pocMidPrice (float) : Consensus center price.
conv (string) : Conviction label.
mom (string) : Efficiency momentum label.
liveAlert (bool) : Explosive bar volume spike flag.
lang (string) : The dashboard language.
Returns: A multi-line narrative string.
f_trTipDash(key, lang)
Returns translated tooltip text for dashboard-level cells.
Parameters:
key (string) : Tooltip key identifier.
lang (string) : The dashboard language.
Returns: The translated tooltip string.
f_trTipTrend(key, lang)
Returns translated tooltip text for Trend Engine cells.
Parameters:
key (string) : Tooltip key identifier.
lang (string) : The dashboard language.
Returns: The translated tooltip string.
f_trTipEff(key, lang)
Returns translated tooltip text for Efficiency module cells.
Parameters:
key (string) : Tooltip key identifier.
lang (string) : The dashboard language.
Returns: The translated tooltip string.
f_trTipVol(key, lang)
Returns translated tooltip text for Volume decomposition cells.
Parameters:
key (string) : Tooltip key identifier.
lang (string) : The dashboard language.
Returns: The translated tooltip string.
f_trTipFp(key, gs, lang)
Returns translated tooltip text for Volume Footprint cells.
Parameters:
key (string) : Tooltip key identifier.
gs (string) : Group size string. Pass "" for static keys.
lang (string) : The dashboard language.
Returns: The translated tooltip string.
f_trTipVi(key, lang)
Returns translated tooltip text for Volume Insight cells.
Parameters:
key (string) : Tooltip key identifier.
lang (string) : The dashboard language.
Returns: The translated tooltip string.
f_trTrendDesc(cas, casDir, div, smD, algn, mBias, mBiasDir, lang)
Builds the trend state description with conviction suffix for the tooltip.
Parameters:
cas (bool) : Cascade active flag.
casDir (int) : Cascade direction.
div (bool) : Divergence active flag.
smD (int) : Micro direction.
algn (int) : Alignment score (-6 to +6).
mBias (bool) : Macro bias active flag.
mBiasDir (int) : Macro bias direction.
lang (string) : The dashboard language.
Returns: Complete tooltip string.
f_trInlineLabel(key, lang)
Returns translated inline labels for dashboard cell content.
Parameters:
key (string) : Label key identifier.
lang (string) : The dashboard language.
Returns: The translated label string. Library

DeeptestLibrary "Deeptest"
Comprehensive quantitative backtesting library with 50+ metrics:
Sharpe/Sortino ratios, R-Expectancy, SQN, drawdown analysis, Monte Carlo
simulation, Walk-Forward Analysis, VaR/CVaR, benchmark comparison, and
interactive table rendering for PulseWire strategies.
@version 15 (20.06.2026)
@license MIT — opensource.org
IMPORTS:
fikira/Text/1 as FN — Font styling for table cells (Sans Bold / Sans-Serif Bold)
PUBLIC API:
runDeeptest(...) — Complete backtest analysis orchestrator (only export)
type Stats — 50+ metric container returned by runDeeptest
type ThresholdConfig — Metric threshold + color configuration
type RollingStats — Rolling window analysis results
══════════════════════════════════════════════════════════════════════════════════════
runDeeptest(tableBg, headerBg, borderColor, bullColor, bearColor, textSize, showComplementaryRow, showStressTestTable, showDrawdownRecoveryCards, showTradeCards, showRExpectancy, enableLogging)
runDeeptest — Complete backtest analysis orchestrator (PUBLIC API)
Calls calculateFromStrategy() for 50+ metrics, then renders:
├ Main backtest table (23 columns × 3 rows + complementary row + footer)
├ Stress test matrix (IS | Monte Carlo | OOS — if showStressTestTable)
├ Drawdown/recovery cards (if showDrawdownRecoveryCards)
└ Top/worst trade cards (if showTradeCards)
Execution model: heavy computation runs once on last confirmed bar, table
rendering on last bar. Benchmark returns accumulate per-bar from SPY daily.
Parameters:
tableBg (color) : Table background color
headerBg (color) : Header background color
borderColor (color) : Border color
bullColor (color) : Color for positive metric values
bearColor (color) : Color for negative metric values
textSize (string) : Cell font size
showComplementaryRow (bool) : Toggle 2nd data row
showStressTestTable (bool) : Toggle MC/WFA stress test table
showDrawdownRecoveryCards (bool) : Toggle drawdown/recovery card tables
showTradeCards (bool) : Toggle top/worst trade card tables
showRExpectancy (bool) : R-multiple display mode for expectancy
enableLogging (bool) : Output all metrics to Data Window via log.info()
Returns: Stats object with all computed metrics
═══════════════════════════════════════════════════════════════════════════
Stats
Stats — Comprehensive backtest statistics container (50+ fields)
Fields:
totalTrades (series int)
winTrades (series int)
lossTrades (series int)
evenTrades (series int)
winRate (series float)
lossRate (series float)
avgWinPct (series float)
avgLossPct (series float)
avgTradePct (series float)
profitFactor (series float)
payoffRatio (series float)
expectancy (series float)
rExpectancy (series float)
grossProfit (series float)
grossLoss (series float)
netProfit (series float)
netProfitPct (series float)
compEffect (series float)
sharpe (series float)
sortino (series float)
calmar (series float)
martin (series float)
maxDrawdownPct (series float)
currentDrawdownPct (series float)
maxEquity (series float)
minEquity (series float)
cagr (series float)
monthlyReturn (series float)
maxConsecWins (series int)
maxConsecLosses (series int)
avgTradeDuration (series float)
avgWinDuration (series float)
avgLossDuration (series float)
timeInMarketPct (series float)
tradesPerMonth (series float)
tradesPerYear (series float)
skewness (series float)
kurtosis (series float)
var95 (series float)
cvar95 (series float)
ulcerIndex (series float)
riskOfRuin (series float)
pValue (series float)
alpha (series float)
beta (series float)
buyHoldReturn (series float)
equityRSquared (series float)
firstTradeTime (series int)
lastTradeTime (series int)
tradingPeriodDays (series float)
sqn (series float) Library

SNIFOFF_51_LangLibrary "SNIFOFF_51_Lang"
Multilingual translation layer for Smart Trader, SNIF-OFF 5.1, Trade Finder.
Provides 13 exported functions covering all dashboard labels, status badges,
and 3 narrative engines (trend, efficiency, volume) in 4 languages.
Consumed by the main indicator via import and i18n.f_*() calls.
f_trSig(en, lang)
Translates trend engine signal labels from English to the selected language.
Parameters:
en (string) : The English signal label from the _sigTxt priority chain.
lang (string) : The dashboard language selected by the user.
Returns: The translated signal label string.
f_trConv(en, lang)
Translates conviction level labels.
Parameters:
en (string) : The English conviction label (HIGH, MODERATE, LOW).
lang (string) : The dashboard language.
Returns: The translated conviction label.
f_trCoup(en, lang)
Translates efficiency coupling labels.
Parameters:
en (string) : The English coupling label from the _effCoupledMsg matrix.
lang (string) : The dashboard language.
Returns: The translated coupling label.
f_trMom(en, lang)
Translates efficiency momentum labels.
Parameters:
en (string) : The English momentum label (Accelerating, Sharpening, Steady, Fading).
lang (string) : The dashboard language.
Returns: The translated momentum label.
f_trVol(en, lang)
Translates volume scenario display labels.
Parameters:
en (string) : The English scenario label from f_volScenarioMsg output.
lang (string) : The dashboard language.
Returns: The translated scenario label.
f_trVolZone(zone, delta, lang)
Builds the directional arrow + intensity label for the volume zone cell.
Parameters:
zone (string) : The volume zone classification (extreme/strong/normal/weak).
delta (int) : The delta direction integer (+1 buyers, -1 sellers, 0 balanced).
lang (string) : The dashboard language.
Returns: The composed volume zone display string.
f_trPocCons(count, lang)
Builds the volume center agreement label.
Parameters:
count (int) : The number of agreeing scales (1-6).
lang (string) : The dashboard language.
Returns: The composed POC consensus display string.
f_trTitle(en, lang)
Translates dashboard module header titles.
Parameters:
en (string) : The English section title.
lang (string) : The dashboard language.
Returns: The translated section title.
f_trBadge(en, lang)
Translates status badge labels (ACTIVE, LOCKED, LIVE, HIST).
Parameters:
en (string) : The English badge label.
lang (string) : The dashboard language.
Returns: The translated badge label.
f_trVolLabel(en, lang)
Translates volume data row cell labels.
Parameters:
en (string) : The English label (Total, Buy, Sell, Group, Maximum, Minimum, Control).
lang (string) : The dashboard language.
Returns: The translated data row label.
f_trendNarrative(cas, casDir, div, smD, algn, mBias, mBiasDir, conv, lang)
Builds a human-readable trend situation summary for the dashboard narrative row.
Parameters:
cas (bool) : Cascade active flag.
casDir (int) : Cascade direction (+1 bullish, -1 bearish).
div (bool) : Divergence active flag.
smD (int) : Micro direction from slope engine.
algn (int) : Alignment score (-6 to +6).
mBias (bool) : Macro bias active flag.
mBiasDir (int) : Macro bias direction.
conv (string) : Conviction label string (HIGH, MODERATE, LOW).
lang (string) : The dashboard language.
Returns: A 3-line narrative string (state + structure + conviction).
f_effNarrative(rz, al, op, td, mom, lang)
Builds a human-readable efficiency situation summary.
Parameters:
rz (string) : Rank zone string (extreme/strong/normal/weak).
al (bool) : Aligned flag (bar direction matches trend).
op (bool) : Opposed flag (bar direction opposes trend).
td (int) : Trend direction (+1, -1, 0).
mom (string) : Momentum label string (Accelerating, Sharpening, Steady, Fading).
lang (string) : The dashboard language.
Returns: A 2-line narrative string (situation + trajectory).
f_volNarrative(sid, td, pocCon, pocMidPrice, conv, mom, liveAlert, lang)
Builds a human-readable 3-line volume situation summary.
Parameters:
sid (string) : Scenario ID (S1–S16).
td (int) : Trend direction (+1, -1, 0).
pocCon (int) : Volume center consensus count (0-6).
pocMidPrice (float) : Consensus center price (weighted average of cluster).
conv (string) : Conviction label (HIGH, MODERATE, LOW).
mom (string) : Efficiency momentum label.
liveAlert (bool) : Explosive bar volume spike flag.
lang (string) : The dashboard language.
Returns: A multi-line narrative string (live alert prefix + what + why + outlook). Library

Library

AIUnifiedCoreLibrary "AIUnifiedCore"
Core signal engine for the AI Learning Trader Bot unified system.
This library contains reusable logic only. Inputs, plots, labels, strategy orders,
and alerts belong in the wrapper scripts that import this library.
clampFloat(value, minValue, maxValue)
Clamps a number between a minimum and maximum.
Parameters:
value (float) : Number to clamp.
minValue (float) : Minimum allowed value.
maxValue (float) : Maximum allowed value.
Returns: Clamped value.
trendEngine(source, fastLen, midLen, slowLen)
Calculates the EMA/VWAP trend engine.
Parameters:
source (float) : Source price.
fastLen (simple int) : Fast EMA length.
midLen (simple int) : Middle EMA length.
slowLen (simple int) : Slow EMA length.
Returns: Fast EMA, middle EMA, slow EMA, VWAP, bullish trend, bearish trend.
momentumEngine(source, rsiLen)
Calculates RSI/MACD momentum engine.
Parameters:
source (float) : Source price.
rsiLen (simple int) : RSI length.
Returns: RSI, MACD line, MACD signal, MACD histogram, bullish momentum, bearish momentum.
volumeEngine(volumeLen)
Calculates volume confirmation.
Parameters:
volumeLen (simple int) : Volume average length.
Returns: Volume average, high volume, bullish volume, bearish volume.
priceActionEngine(swingLen)
Calculates price action breakout and candle direction.
Parameters:
swingLen (simple int) : Swing lookback length.
Returns: Swing high, swing low, bullish break, bearish break, bullish candle, bearish candle.
chopEngine(diLen, adxSmooth, minAdx, atrLen, minAtrPercent, minEmaSpreadPercent, votesNeeded, emaFast, emaSlow)
Calculates the chop/no-trade filter.
Parameters:
diLen (simple int) : DMI DI length.
adxSmooth (simple int) : ADX smoothing.
minAdx (float) : Minimum ADX trend strength.
atrLen (simple int) : ATR length.
minAtrPercent (float) : Minimum ATR percent.
minEmaSpreadPercent (float) : Minimum EMA spread percent.
votesNeeded (simple int) : Number of chop votes needed.
emaFast (float) : Fast EMA.
emaSlow (float) : Slow EMA.
Returns: DI+, DI-, ADX, ATR, ATR percent, EMA spread percent, chop votes, chop market.
probabilityEngine(bullTrend, bearTrend, bullMomentum, bearMomentum, bullVolume, bearVolume, bullBreak, bearBreak, bullCandle, bearCandle, mtfLongOk, mtfShortOk)
Calculates long/short probability scores.
Parameters:
bullTrend (bool) : Bullish trend.
bearTrend (bool) : Bearish trend.
bullMomentum (bool) : Bullish momentum.
bearMomentum (bool) : Bearish momentum.
bullVolume (bool) : Bullish volume.
bearVolume (bool) : Bearish volume.
bullBreak (bool) : Bullish breakout.
bearBreak (bool) : Bearish breakout.
bullCandle (bool) : Bullish candle.
bearCandle (bool) : Bearish candle.
mtfLongOk (bool) : Higher-timeframe long confirmation.
mtfShortOk (bool) : Higher-timeframe short confirmation.
Returns: Long probability and short probability.
superEngine(emaFast, emaMid, rsiValue, macdHist)
Calculates premium super-aggressive pressure scores.
Parameters:
emaFast (float) : Fast EMA.
emaMid (float) : Middle EMA.
rsiValue (float) : RSI value.
macdHist (float) : MACD histogram.
Returns: Super long probability, super short probability.
likelyRevEngine(showSignals, aggression, minVotes, realtimeOnly, chopOk, cooldownUpOk, cooldownDownOk, longProbability, shortProbability, superLongProbability, superShortProbability, bullTrend, bearTrend, emaFast, rsiValue, macdHist, superSensitivity, minEntryProbability)
Calculates early likely reversal votes/signals.
Parameters:
showSignals (bool) : Master toggle.
aggression (simple string) : Aggression text: Balanced, Aggressive, or Hyper.
minVotes (simple int) : Minimum votes.
realtimeOnly (bool) : Only allow before candle closes.
chopOk (bool) : Whether chop filter allows signal.
cooldownUpOk (bool)
cooldownDownOk (bool)
longProbability (float) : Long probability.
shortProbability (float) : Short probability.
superLongProbability (float) : Super long probability.
superShortProbability (float) : Super short probability.
bullTrend (bool) : Bull trend.
bearTrend (bool) : Bear trend.
emaFast (float) : Fast EMA.
rsiValue (float) : RSI value.
macdHist (float) : MACD histogram.
superSensitivity (simple int) : Super aggressive threshold.
minEntryProbability (simple int) : Minimum entry probability.
Returns: Up votes, down votes, votes needed, likely rev up, likely rev down.
easyQuality(trendOk, momentumOk, mtfOk, volumeOk, breakOk, chopMarket, oppositeLikelyRev, probability)
Calculates Easy Mode trade quality score.
Parameters:
trendOk (bool) : Trend agreement.
momentumOk (bool) : Momentum agreement.
mtfOk (bool) : Higher-timeframe agreement.
volumeOk (bool) : Volume agreement.
breakOk (bool) : Breakout agreement.
chopMarket (bool) : No-trade/chop state.
oppositeLikelyRev (bool) : Opposite likely reversal warning.
probability (float) : Direction probability.
Returns: Easy Mode quality score.
actionCode(chopMarket, masterLong, masterShort, exitLong, exitShort, flipLong, flipShort, likelyRevUp, likelyRevDown)
Final unified action code.
Parameters:
chopMarket (bool) : No-trade market.
masterLong (bool) : Master long.
masterShort (bool) : Master short.
exitLong (bool) : Exit long.
exitShort (bool) : Exit short.
flipLong (bool) : Flip to long.
flipShort (bool) : Flip to short.
likelyRevUp (bool) : Likely reversal up.
likelyRevDown (bool) : Likely reversal down.
Returns: Integer action code.
actionText(action)
Converts an action code into text.
Parameters:
action (int) : Action code.
Returns: Action text.
trendText(bullTrend, bearTrend)
Converts trend states into text.
Parameters:
bullTrend (bool) : Bull trend.
bearTrend (bool) : Bear trend.
Returns: Trend text.
topStackPrice(highValue, atrValue, gapAtr, slot)
Returns stacked label price above the candle.
Parameters:
highValue (float) : Candle high.
atrValue (float) : ATR.
gapAtr (float) : Gap in ATR multiples.
slot (int) : Stack slot, starting at 1.
Returns: Label price.
bottomStackPrice(lowValue, atrValue, gapAtr, slot)
Returns stacked label price below the candle.
Parameters:
lowValue (float) : Candle low.
atrValue (float) : ATR.
gapAtr (float) : Gap in ATR multiples.
slot (int) : Stack slot, starting at 1.
Returns: Label price. Library

ICE_CRT_AuditLibrary "ICE_CRT_Audit"
renderRRAudit(t, tradeEntries, tradeStops, tradeRisks, tradeTp1s, tradeTp1Need, tradeTp1Delta, tradeRRs, tradeDistEs, tradeDistEt1, tradeMissRew, tradeDirs, tradeReasons, minRR, failTotal, avgRR, avgNeedReward, avgMissingRew, avgEntry, avgStop, avgRisk, avgTp1, avgDistStop, avgDistTp1)
Parameters:
t (table)
tradeEntries (array)
tradeStops (array)
tradeRisks (array)
tradeTp1s (array)
tradeTp1Need (array)
tradeTp1Delta (array)
tradeRRs (array)
tradeDistEs (array)
tradeDistEt1 (array)
tradeMissRew (array)
tradeDirs (array)
tradeReasons (array)
minRR (float)
failTotal (int)
avgRR (float)
avgNeedReward (float)
avgMissingRew (float)
avgEntry (float)
avgStop (float)
avgRisk (float)
avgTp1 (float)
avgDistStop (float)
avgDistTp1 (float)
renderTp1FormulaAudit(t, tradeDirs, tradeCrtRanges, tradeRatios, tradeDistEt1, tradeDistEs, tradeRRs, tradeNeedRatios, tradeGapRatios, tradeFixAt1, tradeTp1AtRR, minRR, curTp1CrtRatio, auditFixAt1, auditTotal, fixAt1Pct, auditUnfixable, needRatioMax, avgNeedRatio, avgGapRatio)
Parameters:
t (table)
tradeDirs (array)
tradeCrtRanges (array)
tradeRatios (array)
tradeDistEt1 (array)
tradeDistEs (array)
tradeRRs (array)
tradeNeedRatios (array)
tradeGapRatios (array)
tradeFixAt1 (array)
tradeTp1AtRR (array)
minRR (float)
curTp1CrtRatio (float)
auditFixAt1 (int)
auditTotal (int)
fixAt1Pct (float)
auditUnfixable (int)
needRatioMax (float)
avgNeedRatio (float)
avgGapRatio (float) Library

ICE_CRT_CoreLibrary "ICE_CRT_Core"
calcBodySize(o, c)
Parameters:
o (float)
c (float)
calcRangeSize(h, l)
Parameters:
h (float)
l (float)
calcUpperWick(h, o, c)
Parameters:
h (float)
o (float)
c (float)
calcLowerWick(l, o, c)
Parameters:
l (float)
o (float)
c (float)
calcBodyRatio(bodySize, rangeSize)
Parameters:
bodySize (float)
rangeSize (float)
validateCRT(o, h, l, c, bodyRatioMinIn, atrValIn, atrMultIn)
Parameters:
o (float)
h (float)
l (float)
c (float)
bodyRatioMinIn (float)
atrValIn (float)
atrMultIn (float)
crtLabelText(isBullish, isBearish)
Parameters:
isBullish (bool)
isBearish (bool)
crtLabelStyle(isBullish, isBearish)
Parameters:
isBullish (bool)
isBearish (bool)
crtLabelColor(isBullish, isBearish, bullishColor, bearishColor, validColor)
Parameters:
isBullish (bool)
isBearish (bool)
bullishColor (color)
bearishColor (color)
validColor (color)
crtLabelPrice(isBullish, isBearish, crtHighIn, crtLowIn, crtMidIn)
Parameters:
isBullish (bool)
isBearish (bool)
crtHighIn (float)
crtLowIn (float)
crtMidIn (float)
isGrabHigh(level, minGrab, h)
Parameters:
level (float)
minGrab (float)
h (float)
isGrabLow(level, minGrab, l)
Parameters:
level (float)
minGrab (float)
l (float)
isAcceptanceHigh(level, buffer, c)
Parameters:
level (float)
buffer (float)
c (float)
isAcceptanceLow(level, buffer, c)
Parameters:
level (float)
buffer (float)
c (float)
isWickRejectionHigh(level, wickMin, o, h, l, c)
Parameters:
level (float)
wickMin (float)
o (float)
h (float)
l (float)
c (float)
isWickRejectionLow(level, wickMin, o, h, l, c)
Parameters:
level (float)
wickMin (float)
o (float)
h (float)
l (float)
c (float)
isNoAcceptanceHigh(level, h, c)
Parameters:
level (float)
h (float)
c (float)
isNoAcceptanceLow(level, l, c)
Parameters:
level (float)
l (float)
c (float)
isFollowThroughRejectionHigh(level, grabBarIn, c, barIdx)
Parameters:
level (float)
grabBarIn (int)
c (float)
barIdx (int)
isFollowThroughRejectionLow(level, grabBarIn, c, barIdx)
Parameters:
level (float)
grabBarIn (int)
c (float)
barIdx (int)
isRejectedHigh(level, grabBarIn, wickMin, acceptBuf, o, h, l, c, barIdx)
Parameters:
level (float)
grabBarIn (int)
wickMin (float)
acceptBuf (float)
o (float)
h (float)
l (float)
c (float)
barIdx (int)
isRejectedLow(level, grabBarIn, wickMin, acceptBuf, o, h, l, c, barIdx)
Parameters:
level (float)
grabBarIn (int)
wickMin (float)
acceptBuf (float)
o (float)
h (float)
l (float)
c (float)
barIdx (int)
eventStateName(state)
Parameters:
state (int)
processHighLevel(level, trackedLevel, eventState, grabBar, grabLevel, minGrab, rejWindow, wickMin, acceptBuf, o, h, l, c, barIdx)
Parameters:
level (float)
trackedLevel (float)
eventState (int)
grabBar (int)
grabLevel (float)
minGrab (float)
rejWindow (int)
wickMin (float)
acceptBuf (float)
o (float)
h (float)
l (float)
c (float)
barIdx (int)
processLowLevel(level, trackedLevel, eventState, grabBar, grabLevel, minGrab, rejWindow, wickMin, acceptBuf, o, h, l, c, barIdx)
Parameters:
level (float)
trackedLevel (float)
eventState (int)
grabBar (int)
grabLevel (float)
minGrab (float)
rejWindow (int)
wickMin (float)
acceptBuf (float)
o (float)
h (float)
l (float)
c (float)
barIdx (int)
returnStateName(state)
Parameters:
state (int)
isInsideCrtRange(crtHighIn, crtLowIn, buffer, c)
Parameters:
crtHighIn (float)
crtLowIn (float)
buffer (float)
c (float)
processReturnLevel(level, trackedLevel, rejectPulseIn, returnStateIn, rejectBarIn, returnBarIn, crtHighIn, crtLowIn, crtReadyIn, retWindowIn, crtBufIn, c, barIdx)
Parameters:
level (float)
trackedLevel (float)
rejectPulseIn (bool)
returnStateIn (int)
rejectBarIn (int)
returnBarIn (int)
crtHighIn (float)
crtLowIn (float)
crtReadyIn (bool)
retWindowIn (int)
crtBufIn (float)
c (float)
barIdx (int)
isLegitGrabOpen(stateBefore, levelChanged)
Parameters:
stateBefore (int)
levelChanged (bool)
isLegitReturnFromReject(rejectPulse, returnStateBefore, rejectBarBefore)
Parameters:
rejectPulse (bool)
returnStateBefore (int)
rejectBarBefore (int)
amdInsideCrtCloseAt(barsBack, crtHighIn, crtLowIn, buffer, cSeries)
Parameters:
barsBack (int)
crtHighIn (float)
crtLowIn (float)
buffer (float)
cSeries (float)
amdCountPreGrabInsideCrt(grabOffsetIn, lookbackIn, crtHighIn, crtLowIn, buffer, cSeries)
Parameters:
grabOffsetIn (int)
lookbackIn (int)
crtHighIn (float)
crtLowIn (float)
buffer (float)
cSeries (float)
amdCountInsideCrtBetweenGrabSweep(grabOffsetIn, crtHighIn, crtLowIn, buffer, cSeries)
Parameters:
grabOffsetIn (int)
crtHighIn (float)
crtLowIn (float)
buffer (float)
cSeries (float)
entryConfirmCandleLong(sweptLevelIn, c, o, insideCrtIn)
Parameters:
sweptLevelIn (float)
c (float)
o (float)
insideCrtIn (bool)
entryConfirmCandleShort(sweptLevelIn, c, o, insideCrtIn)
Parameters:
sweptLevelIn (float)
c (float)
o (float)
insideCrtIn (bool)
tradeStateName(stateIn)
Parameters:
stateIn (int)
tradeStructStopLongPure(entryIn, bufIn, sweepLow, grabLow, tsLow, barLow)
Parameters:
entryIn (float)
bufIn (float)
sweepLow (float)
grabLow (float)
tsLow (float)
barLow (float)
tradeStructStopShortPure(entryIn, bufIn, sweepHigh, grabHigh, tsHigh, barHigh)
Parameters:
entryIn (float)
bufIn (float)
sweepHigh (float)
grabHigh (float)
tsHigh (float)
barHigh (float)
tradeStructTp1Long(entryIn, crtHighIn, crtLowIn, ratioIn)
Parameters:
entryIn (float)
crtHighIn (float)
crtLowIn (float)
ratioIn (float)
tradeStructTp1Short(entryIn, crtHighIn, crtLowIn, ratioIn)
Parameters:
entryIn (float)
crtHighIn (float)
crtLowIn (float)
ratioIn (float)
tradeStructTp2Long(crtHighIn)
Parameters:
crtHighIn (float)
tradeStructTp2Short(crtLowIn)
Parameters:
crtLowIn (float)
tradeStructTp3Long(entryIn, crtHighIn, pdhIn, pwhIn)
Parameters:
entryIn (float)
crtHighIn (float)
pdhIn (float)
pwhIn (float)
tradeStructTp3Short(entryIn, crtLowIn, pdlIn, pwlIn)
Parameters:
entryIn (float)
crtLowIn (float)
pdlIn (float)
pwlIn (float)
tradeCalcRRatio(entryIn, stopIn, targetIn)
Parameters:
entryIn (float)
stopIn (float)
targetIn (float)
tradeValidateLong(entryIn, stopIn, tp1In, tp2In, tp3In, minRRIn)
Parameters:
entryIn (float)
stopIn (float)
tp1In (float)
tp2In (float)
tp3In (float)
minRRIn (float)
tradeValidateShort(entryIn, stopIn, tp1In, tp2In, tp3In, minRRIn)
Parameters:
entryIn (float)
stopIn (float)
tp1In (float)
tp2In (float)
tp3In (float)
minRRIn (float)
tradeAuditInvalidReason(isLongIn, entryIn, stopIn, tp1In, tp2In, tp3In, minRRIn)
Parameters:
isLongIn (bool)
entryIn (float)
stopIn (float)
tp1In (float)
tp2In (float)
tp3In (float)
minRRIn (float)
tradeAuditOrderLongOk(entryIn, tp1In, tp2In, tp3In)
Parameters:
entryIn (float)
tp1In (float)
tp2In (float)
tp3In (float)
tradeAuditOrderShortOk(entryIn, tp1In, tp2In, tp3In)
Parameters:
entryIn (float)
tp1In (float)
tp2In (float)
tp3In (float)
tradeSimTp2OptA(isLongIn, tp1In, crtHighIn, crtLowIn, betaIn)
Parameters:
isLongIn (bool)
tp1In (float)
crtHighIn (float)
crtLowIn (float)
betaIn (float)
tradeSimTp2OptB(isLongIn, entryIn, stopIn, r2In)
Parameters:
isLongIn (bool)
entryIn (float)
stopIn (float)
r2In (float)
tradeSimTp2OptC(isLongIn, tp1In, tp3In, gammaIn)
Parameters:
isLongIn (bool)
tp1In (float)
tp3In (float)
gammaIn (float)
tradeSimFailsTp2(isLongIn, tp1In, tp2In, tp3In)
Parameters:
isLongIn (bool)
tp1In (float)
tp2In (float)
tp3In (float)
tradeSimFailsRR(entryIn, stopIn, tp1In, minRRIn)
Parameters:
entryIn (float)
stopIn (float)
tp1In (float)
minRRIn (float)
tradeAuditRRReason(entryIn, stopIn, tp1In, minRRIn)
Parameters:
entryIn (float)
stopIn (float)
tp1In (float)
minRRIn (float)
tradeAuditRequiredReward(riskIn, minRRIn)
Parameters:
riskIn (float)
minRRIn (float)
tradeAuditMissingReward(riskIn, actualRewardIn, minRRIn)
Parameters:
riskIn (float)
actualRewardIn (float)
minRRIn (float)
tradeAuditTp1ForMinRR(isLongIn, entryIn, stopIn, minRRIn)
Parameters:
isLongIn (bool)
entryIn (float)
stopIn (float)
minRRIn (float)
tradeAuditTp1Delta(tp1ActualIn, tp1NeedIn)
Parameters:
tp1ActualIn (float)
tp1NeedIn (float)
tradeAuditTp1NeedCrtRatio(riskIn, crtRangeIn, minRRIn)
Parameters:
riskIn (float)
crtRangeIn (float)
minRRIn (float)
tradeAuditTp1ActualCrtRatio(distEt1In, crtRangeIn)
Parameters:
distEt1In (float)
crtRangeIn (float) Library

chartpatternsLibrary "chartpatterns"
Library having complete chart pattern implementation
method draw(this)
draws pattern on the chart
Namespace types: Pattern
Parameters:
this (Pattern) : Pattern object that needs to be drawn
Returns: Current Pattern object
method draw(this)
draws pattern on the chart
Namespace types: FNPPattern
Parameters:
this (FNPPattern) : FNPPattern object that needs to be drawn
Returns: Current FNPPattern object
method erase(this)
erase the given pattern on the chart
Namespace types: Pattern
Parameters:
this (Pattern) : Pattern object that needs to be erased
Returns: Current Pattern object
method erase(this)
erase the given pattern on the chart
Namespace types: FNPPattern
Parameters:
this (FNPPattern) : Pattern object that needs to be erased
Returns: Current Pattern object
method createFNP(p, base)
creates FNP Pattern from base Pattern
Namespace types: Pattern
Parameters:
p (Pattern) : Pattern object from which the FNP Pattern needs to be created
base (chart.point) : base point of the flag or pennant
Returns: Current Pattern object
method push(this, p, maxItems)
push Pattern object to the array by keeping maxItems limit
Namespace types: array
Parameters:
this (array) : array of Pattern objects
p (Pattern) : Pattern object to be added to array
@oaram maxItems Max number of items the array can hold
maxItems (int)
Returns: Current Pattern array
method push(this, p, maxItems)
push FNPPattern object to the array by keeping maxItems limit
Namespace types: array
Parameters:
this (array) : array of FNPPattern objects
p (FNPPattern) : FNPPattern object to be added to array
@oaram maxItems Max number of items the array can hold
maxItems (int)
Returns: Current FNPPattern array
method findPattern(this, properties, dProperties, patterns, ohlcArray, maxLivePatterns, draw)
Find patterns based on the currect zigzag object and store them in the patterns array
Namespace types: zg.Zigzag
Parameters:
this (Zigzag type from Trendoscope/ZigzagLite/3) : Zigzag object containing pivots
properties (ScanProperties) : ScanProperties object
@oaram dProperties DrawingProperties object
dProperties (DrawingProperties)
patterns (array) : Array of Pattern objects
ohlcArray (array type from Trendoscope/ohlc/3)
maxLivePatterns (int) : max number of patterns to be retained in the patterns array
draw (bool) : pattern is drawn on the chart automatically if set to true
Returns: Current Pattern object
method findPatternPlain(this, properties, dProperties, patterns, ohlcArray)
Find patterns based on the currect zigzag object but will not store them in the pattern array.
Namespace types: zg.Zigzag
Parameters:
this (Zigzag type from Trendoscope/ZigzagLite/3) : Zigzag object containing pivots
properties (ScanProperties) : ScanProperties object
@oaram dProperties DrawingProperties object
dProperties (DrawingProperties)
patterns (array) : Array of Pattern objects
ohlcArray (array type from Trendoscope/ohlc/3)
Returns: Flag indicating if the pattern is valid, Current Pattern object
method findFNP(this, currentPattern, sProperties)
Find flag and pennant patterns based on the current zigzag object and returns the pattern object along with flag
Namespace types: zg.Zigzag
Parameters:
this (Zigzag type from Trendoscope/ZigzagLite/3) : Zigzag object containing pivots
currentPattern (Pattern) : Pattern object to be used as base
sProperties (ScanProperties) : ScanProperties object
Returns: Flag indicating if the fng pattern is valid, new FNPPattern object
ScanProperties
Object containing properties for pattern scanning
Fields:
offset (series int) : Zigzag pivot offset. Set it to 1 for non repainting scan.
numberOfPivots (series int) : Number of pivots to be used in pattern search. Can be either 5 or 6
errorRatio (series float) : Error Threshold to be considered for comparing the slope of lines
flatRatio (series float) : Retracement ratio threshold used to determine if the lines are flat
flagRatio (series float) : max ratio threshold for flag and pennnant
checkBarRatio (series bool) : Also check bar ratio are within the limits while scanning the patterns
barRatioLimit (series float) : Bar ratio limit used for checking the bars. Used only when checkBarRatio is set to true
avoidOverlap (series bool) : avoid overlapping patterns.
repaint (series bool) : allow repainting pattern if the new coordinates are more appropriate
allowedPatterns (array) : array of bool encoding the allowed pattern types.
allowedLastPivotDirections (array) : array of int representing allowed last pivot direction for each pattern types
themeColors (array) : color array of themes to be used.
DrawingProperties
Object containing properties for pattern drawing
Fields:
patternLineWidth (series int) : Line width of the pattern trend lines
showZigzag (series bool) : show zigzag associated with pattern
zigzagLineWidth (series int) : line width of the zigzag lines. Used only when showZigzag is set to true
zigzagLineColor (series color) : color of the zigzag lines. Used only when showZigzag is set to true
showPatternLabel (series bool) : display pattern label containing the name
patternLabelSize (series string) : size of the pattern label. Used only when showPatternLabel is set to true
showPivotLabels (series bool) : Display pivot labels of the patterns marking 1-6
pivotLabelSize (series string) : size of the pivot label. Used only when showPivotLabels is set to true
pivotLabelColor (series color) : color of the pivot label outline. chart.bg_color or chart.fg_color are the appropriate values.
deleteOnPop (series bool) : delete the pattern when popping out from the array of Patterns.
Pattern
Object containing Individual Pattern data
Fields:
pivots (array type from Trendoscope/ZigzagLite/3) : array of Zigzag Pivot points
trendLine1 (Line type from Trendoscope/LineWrapper/2) : First trend line joining pivots 1, 3, 5
trendLine2 (Line type from Trendoscope/LineWrapper/2) : Second trend line joining pivots 2, 4 (, 6)
properties (DrawingProperties) : DrawingProperties Object carrying common properties
patternColor (series color) : Individual pattern color. Lines and labels will be using this color.
ratioDiff (series float) : Difference between trendLine1 and trendLine2 ratios
zigzagLine (series polyline) : Internal zigzag line drawing Object
pivotLabels (array) : array containning Pivot labels
patternLabel (series label) : pattern label Object
patternType (series int) : integer representing the pattern type
patternName (series string) : Type of pattern in string
FNPPattern
Object containing Individual Pattern data
Fields:
pivots (array type from Trendoscope/ZigzagLite/3) : array of Zigzag Pivot points
trendLine1 (Line type from Trendoscope/LineWrapper/2) : First trend line joining pivots 1, 3, 5
trendLine2 (Line type from Trendoscope/LineWrapper/2) : Second trend line joining pivots 2, 4 (, 6)
baseLine (Line type from Trendoscope/LineWrapper/2) : Base line of the flag or pennant
properties (DrawingProperties) : DrawingProperties Object carrying common properties
patternColor (series color) : Individual pattern color. Lines and labels will be using this color.
ratioDiff (series float) : Difference between trendLine1 and trendLine2 ratios
zigzagLine (series polyline) : Internal zigzag line drawing Object
pivotLabels (array) : array containning Pivot labels
patternLabel (series label) : pattern label Object
patternType (series int) : integer representing the pattern type
patternName (series string) : Type of pattern in string Library

DivergenceLineLabelOutput_UtilitiesDivergenceLineLabelOutput_Utilities is a shared Pine v6 output library for scripts that already have their own oscillator, pivot, structure, or divergence logic but want a reusable divergence-rendering layer.
It centralizes the parts of the workflow that tend to get rewritten across oscillator scripts:
• HH / LH / HL / LL / EQ structure resolution
• regular / hidden divergence state checks
• same-structure context state checks
• divergence and context color routing
• standardized divergence/context label text
• price-pane and oscillator-pane line helpers
• price-pane and oscillator-pane label helpers
• confirmed-object slot visibility helpers
• live-preview line and label helpers
• native-pane and price-pane pivot context box helpers
On the example chart, the confirmed divergence lines, live preview lines, divergence labels, context labels, and pivot context boxes are all materially driven by this library.
This library is intentionally focused on output and object management. It does not calculate RSI, MACD, VFI, volume flow, pressure, or any other oscillator. It does not confirm pivots or decide which pivots are valid. Calling scripts remain responsible for their own oscillator engine, pivot engine, comparison logic, colors, visibility modes, and signal interpretation.
How to use
Import the library near the top of your script in global scope, alongside any other imports, before you start calling its helpers.
Typical placement:
//@version=6
indicator(...) or strategy(...)
import MYNAMEISBRANDON/DivergenceLineOutput_Utilities/1 as DivUtils
Replace /1 with the latest published version if a newer version is available.
This library expects the calling script to already know the price pivot, oscillator pivot, prior pivot reference, structure state, and output settings it wants to use. The library then handles the reusable line, label, live-preview, slot-budget, and box output layer.
➖Structure + Divergence State Helpers➖
These helpers convert pivot comparisons into structure tags and divergence/context states.
divStructure(curr, prev, isHigh)
Resolves HH, LH, HL, LL, or EQ from a current pivot and previous pivot.
Parameters:
curr (float): Current pivot value
prev (float): Previous pivot value
isHigh (bool): True for high-side comparison, false for low-side comparison
Returns:
Structure string
divState(priceStruct, oscStruct)
Resolves regular and hidden divergence states from price and oscillator structure tags.
Returns:
regularBear, regularBull, hiddenBear, hiddenBull, anyDivergence
divContextState(priceStruct, oscStruct)
Resolves same-structure context states from price and oscillator structure tags.
Returns:
highContinuation, highFade, lowContinuation, lowLift, anyContext
divColor(priceStruct, oscStruct, regularBearColor, regularBullColor, hiddenBearColor, hiddenBullColor, highContinuationColor, lowContinuationColor, highFadeColor, lowLiftColor, fallbackColor)
Routes a divergence or context pair to the matching caller-supplied color.
Returns:
Resolved color
➖Style + Label Helpers➖
These helpers keep divergence output styling consistent across scripts.
divLineStyle(styleIn)
Converts user-facing line-style text into Pine line-style enums.
Parameters:
styleIn (simple string): Solid, Dashed, or Dotted
Returns:
Pine line style
divLabelSize(sizeIn)
Converts user-facing label-size text into Pine label-size enums.
Parameters:
sizeIn (simple string): Tiny, Small, Normal, Large, or Huge
Returns:
Pine label size
divContrastText(bg)
Chooses black or white text based on background brightness.
Parameters:
bg (color): Background color
Returns:
Readable contrast text color
divLabelText(divType, divSide, priceStruct, oscStruct, formatMode)
Builds standardized divergence label text.
Parameters:
divType (simple string): Usually Reg or Hid
divSide (simple string): Usually Bull or Bear
priceStruct (string): Price structure tag
oscStruct (string): Oscillator structure tag
formatMode (simple string): Full, No Prefix, or Type Only
Returns:
Formatted label text
➖Confirmed Line Helpers➖
These helpers create and manage confirmed divergence or context lines.
clearLines(lines, colors)
Deletes all lines in an array and clears the matching color array.
pushOscLine(lines, colors, show, active, x1, y1, x2, y2, lineColor, lineTransp, lineWidth, lineStyle, maxLines)
Pushes a confirmed oscillator-pane line into line/color arrays.
pushPriceLine(lines, colors, show, active, x1, y1, x2, y2, lineColor, lineTransp, lineWidth, lineStyle, maxLines)
Pushes a confirmed price-pane line into line/color arrays using force_overlay=true.
Note:
Price helpers draw on the main chart from overlay=false oscillator scripts. Oscillator helpers draw in the script’s native pane.
➖Confirmed Label Helpers➖
These helpers create and manage confirmed divergence or context labels.
clearLabels(labels, colors)
Deletes all labels in an array and clears the matching color array.
pushOscLabel(labels, colors, show, active, xIndex, y, labelText, styleText, lineColor, labelTextOnly, labelBgTransp, labelSize, maxLabels)
Pushes a confirmed oscillator-pane label into label/color arrays.
pushPriceLabel(labels, colors, show, active, xTime, labelText, ylocText, styleText, lineColor, labelTextOnly, labelBgTransp, labelSize, maxLabels)
Pushes a confirmed price-pane label into label/color arrays using force_overlay=true.
Note:
For price-pane labels, xTime uses bar time and ylocText controls whether the label appears above or below the price bar.
➖Confirmed Slot Visibility Helpers➖
These helpers allow scripts to keep confirmed lines and labels stored while only showing the most recent visible slots.
applyLineSlots(lines, colors, visibleSlots)
Applies a visible slot budget to confirmed line arrays without deleting older objects.
applyLabelSlots(labels, colors, visibleSlots, labelTextOnly, labelBgTransp)
Applies a visible slot budget to confirmed label arrays without deleting older objects.
Example:
• Max Regular Lines = 1
- Live regular active = live regular only
- No live regular = latest confirmed regular only
• Max Regular Lines = 2
- Live regular active = live regular + latest confirmed regular
- No live regular = latest two confirmed regular lines
➖Live Preview Line Helpers➖
These helpers create, update, or delete live divergence preview lines.
syncLiveOscLine(ln, show, x1, y1, x2, y2, lineColor, lineWidth, lineStyle)
Creates, updates, or deletes a live oscillator-pane line.
syncLivePriceLine(ln, show, x1, y1, x2, y2, lineColor, lineWidth, lineStyle)
Creates, updates, or deletes a live price-pane line using force_overlay=true.
➖Live Preview Label Helpers➖
These helpers create, update, or delete live divergence preview labels.
syncLiveOscLabel(lbl, show, xIndex, y, labelText, styleText, lineColor, labelTextOnly, labelBgTransp, labelSize)
Creates, updates, or deletes a live oscillator-pane label.
syncLivePriceLabel(lbl, show, xTime, labelText, ylocText, styleText, lineColor, labelTextOnly, labelBgTransp, labelSize)
Creates, updates, or deletes a live price-pane label using force_overlay=true.
➖Pivot Context Box Helpers➖
These helpers provide lightweight box utilities for scripts that want to frame confirmed pivot zones.
divPivotBoxBounds(pivotValue, innerPct)
Resolves a thin box around a pivot value using an inner percentage.
Returns:
top, bottom, ok
syncNativeBox(bx, show, left, right, top, bottom, fillColor, borderColor, borderStyle, borderWidth)
Creates, updates, or deletes a native-pane pivot context box.
syncPriceBox(bx, show, left, right, top, bottom, fillColor, borderColor, borderStyle, borderWidth)
Creates, updates, or deletes a price-pane pivot context box using force_overlay=true.
➖Divergence Model➖
Regular Bearish Divergence:
Price makes HH while oscillator makes LH.
Regular Bullish Divergence:
Price makes LL while oscillator makes HL.
Hidden Bearish Divergence:
Price makes LH while oscillator makes HH.
Hidden Bullish Divergence:
Price makes HL while oscillator makes LL.
➖Structure Context Model➖
High-side continuation:
Price makes HH while oscillator also makes HH.
High-side fading:
Price makes LH while oscillator also makes LH.
Low-side continuation:
Price makes LL while oscillator also makes LL.
Low-side lifting:
Price makes HL while oscillator also makes HL.
Structure context is not divergence. It shows same-structure agreement between price and oscillator.
➖Important Notes➖
This library is an output utility layer only.
It does not:
• calculate an oscillator
• confirm pivots
• choose pivot anchors
• decide whether a divergence is valid
• decide trade direction
• decide final signal logic
Calling scripts remain responsible for:
• oscillator calculation
• pivot confirmation
• price/oscillator comparison logic
• visibility settings
• color choices
• max-line and max-label budgets
• final visual interpretation
For overlay=false oscillator scripts, Price + Oscillator / Price Only / Oscillator Only / Hide output modes work well.
For overlay=true price-pane scripts, Price Only / Hide output modes usually make the most sense. Library

Obj_XABCD_HarmonicLibrary "Obj_XABCD_Harmonic"
Harmonic XABCD Pattern object and associated methods. Easily validate, draw, and get information about harmonic patterns. See example code at the end of the script for details.
init_params(pct_error, pct_asym, types, w_e, w_p, w_d)
Create a harmonic parameters object (used by xabcd_harmonic object for pattern validation and scoring).
Parameters:
pct_error (float) : Allowed % error of leg retracement ratio versus the defined harmonic ratio
pct_asym (float) : Allowed leg length/period asymmetry % (a leg is considered invalid if it is this % longer or shorter than the average length of the other legs)
types (array) : Array of pattern types to validate (1=Gartley, 2=Bat, 3=Butterfly, 4=Crab, 5=Shark, 6=Cypher, 7=Alt-Bat, 8=Deep Butterfly, 9=Deep Crab)
w_e (float) : Weight of ratio % error (used in score calculation, dft = 1)
w_p (float) : Weight of PRZ confluence (used in score calculation, dft = 1)
w_d (float) : Weight of Point D / PRZ confluence (used in score calculation, dft = 1)
Returns: harmonic_params object instance. It is recommended to store and reuse this object for multiple xabcd_harmonic objects rather than creating new params objects unnecessarily.
method erase_pattern(p)
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic)
init(x, a, b, c, d, params, tp, p)
Initialize an xabcd_harmonic object instance from a given set of points
If the pattern is valid, an xabcd_harmonic object instance is returned. If you want to specify your
own validation and scoring parameters, you can do so by passing a harmonic_params object (params).
Or, if you prefer to do your own validation, you can explicitly pass the harmonic pattern type (tp)
and validation will be skipped. You can also pass in an existing xabcd_harmonic instance if you wish
to re-initialize it (e.g. for re-validation and/or re-scoring).
Parameters:
x (point type from reees/Pattern/1) : Point X
a (point type from reees/Pattern/1) : Point A
b (point type from reees/Pattern/1) : Point B
c (point type from reees/Pattern/1) : Point C
d (point type from reees/Pattern/1) : Point D
params (harmonic_params) : harmonic_params used to validate and score the pattern. Validation will be skipped if a type (tp) is explicitly passed in.
tp (int) : Pattern type
p (xabcd_harmonic) : xabcd_harmonic object instance to initialize (optional, for re-validation/re-scoring)
Returns: xabcd_harmonic object instance if a valid harmonic, else na
init(xX, xY, aX, aY, bX, bY, cX, cY, dX, dY, params, tp, p)
Initialize an xabcd_harmonic object instance from a given set of x and y coordinate values.
If the pattern is valid, an xabcd_harmonic object instance is returned. If you want to specify your
own validation and scoring parameters, you can do so by passing a harmonic_params object (params).
Or, if you prefer to do your own validation, you can explicitly pass the harmonic pattern type (tp)
and validation will be skipped. You can also pass in an existing xabcd_harmonic instance if you wish
to re-initialize it (e.g. for re-validation and/or re-scoring).
Parameters:
xX (int) : Point X bar index (required)
xY (float) : Point X price/level (required)
aX (int) : Point A bar index (required)
aY (float) : Point A price/level (required)
bX (int) : Point B bar index (required)
bY (float) : Point B price/level (required)
cX (int) : Point C bar index (required)
cY (float) : Point C price/level (required)
dX (int) : Point D bar index
dY (float) : Point D price/level
params (harmonic_params) : harmonic_params used to validate and score the pattern. Validation will be skipped if a type (tp) is explicitly passed in.
tp (int) : Pattern type
p (xabcd_harmonic) : xabcd_harmonic object instance to initialize (optional, for re-validation/re-scoring)
Returns: xabcd_harmonic object instance if a valid harmonic, else na
init(pattern, params, tp, p)
Initialize an xabcd_harmonic object instance from a given pattern
If the pattern is valid, an xabcd_harmonic object instance is returned. If you want to specify your
own validation and scoring parameters, you can do so by passing a harmonic_params object (params).
Or, if you prefer to do your own validation, you can explicitly pass the harmonic pattern type (tp)
and validation will be skipped. You can also pass in an existing xabcd_harmonic instance if you wish
to re-initialize it (e.g. for re-validation and/or re-scoring).
Parameters:
pattern (pattern type from reees/Pattern/1) : Pattern
params (harmonic_params) : harmonic_params used to validate and score the pattern. Validation will be skipped if a type (tp) is explicitly passed in.
tp (int) : Pattern type
p (xabcd_harmonic) : xabcd_harmonic object instance to initialize (optional, for re-validation/re-scoring)
Returns: xabcd_harmonic object instance if a valid harmonic, else na
method get_name(p)
Get the pattern name
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
Returns: Pattern name (string)
method get_symbol(p)
Get the pattern symbol from a pattern instance
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
Returns: Pattern symbol string
get_symbol(tp)
Get the pattern symbol for a given pattern type integer.
Static overload — does not require a pattern instance.
Parameters:
tp (int) : Pattern type (1=Gartley, 2=Bat, 3=Butterfly, 4=Crab, 5=Shark,
6=Cypher, 7=Alt-Bat, 8=Deep Butterfly, 9=Deep Crab)
Returns: Pattern symbol string
method get_pid(p)
Get the Pattern ID. Patterns of the same type with the same coordinates will have the same Pattern ID.
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
Returns: Pattern ID (string)
method prz_range(p)
Returns cached PRZ upper and lower bounds.
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
Returns:
method incomplete_pid(p)
Returns the pattern ID as if point D were unconfirmed (na).
Used to match incomplete patterns against their completed counterparts
during deduplication. Ensures pid format is consistent with the
library's internal pid generation.
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
Returns: Pattern ID string with D forced to na
method set_target(p, target, target_lvl, calc_target)
Set value for a target. Use the calc_target parameter to automatically calculate the target for a specific harmonic ratio.
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
target (int) : Target (1 or 2)
target_lvl (float) : Target price/level (required if calc_target is not specified)
calc_target (string) : Target to auto calculate (required if target is not specified)
Options:
Returns: Target price/level (float)
method draw_pattern(p, clr)
Draw the pattern
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
clr (color)
Returns: Pattern lines
method erase_label(p)
Erase the pattern label
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
Returns: p
method draw_prz_levels(p, clr, extendBars)
Draw PRZ target levels as horizontal dashed lines for incomplete patterns.
Shows where point D needs to land without implying a specific price path.
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
clr (color) : Line color
extendBars (int) : Number of bars to extend the lines to the right (default 50)
Returns: — the two PRZ level lines
method draw_label(p, clr, txt_clr, txt, tooltip)
Draw the pattern label. Default text is the pattern name.
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
clr (color) : Label color
txt_clr (color) : Text color
txt (string) : Label text
tooltip (string) : Tooltip text
Returns: Label
method is_complete(p)
Returns true if the pattern has a confirmed point D.
A pattern is complete when D exists AND is not an unconfirmed pivot.
Use this instead of checking na(p.d.x) directly — invalid_d being
false is a required condition that bare na checks miss.
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
Returns: bool
method age_pct(p, tLimitMult)
Returns how far through the pattern's time limit it is, as a 0.0–1.0 float.
0.0 = just confirmed, 1.0 = time limit reached.
Returns na if pattern has no confirmed D point.
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
tLimitMult (float) : Pattern time limit multiplier (same value used in main script)
Returns: float 0.0–1.0
harmonic_params
Validation and scoring parameters for a Harmonic Pattern object (xabcd_harmonic)
Fields:
pct_error (series float) : Allowed % error of leg retracement ratio versus the defined harmonic ratio
pct_asym (series float)
types (array)
w_e (series float)
w_p (series float)
w_d (series float)
xabcd_harmonic
Harmonic Pattern object
Fields:
bull (series bool) : Bullish pattern flag
tp (series int)
x (point type from reees/Pattern/1)
a (point type from reees/Pattern/1)
b (point type from reees/Pattern/1)
c (point type from reees/Pattern/1)
d (point type from reees/Pattern/1)
r_xb (series float)
re_xb (series float)
r_ac (series float)
re_ac (series float)
r_bd (series float)
re_bd (series float)
r_xd (series float)
re_xd (series float)
score (series float)
score_eAvg (series float)
score_prz (series float)
score_eD (series float)
prz_bN (series float)
prz_bF (series float)
prz_xN (series float)
prz_xF (series float)
przUpper (series float)
przLower (series float)
t1Hit (series bool) : Target 1 flag
t1 (series float)
t2Hit (series bool)
t2 (series float)
sHit (series bool) : Stop flag
stop (series float) : Stop level
entry (series float) : Entry level
eHit (series bool)
e (point type from reees/Pattern/1)
invalid_d (series bool)
pLines (array)
pLabel (series label)
cdLine (series line)
pid (series string)
params (harmonic_params) Library

Library

CyberVisLib# CyberVisLib v5
CyberVisLib provides rendering and visualization utilities for multi-oscillator indicators: color blending, sub-pane management, diagnostic tables, and tooltip formatting. Pure visualization layer—no market logic.
## What it does
Delivers four capabilities: color utilities (RGB blending, diverging/sequential gradients, confidence-to-transparency), sub-pane management (vertical space allocation for multiple oscillators), diagnostic tables (key-value pairs, dynamic coloring), and tooltip formatting. Stack RSI, MACD, Stochastic in non-overlapping vertical bands.
Outputs color values, MiniSubPane structs (band coordinates), table objects, formatted strings. All stateless, rendering-focused.
## How it works
Color blending: `RGB_out = (1-t)×RGB_a + t×RGB_b`. Diverging gradients split at zero (negative→red-yellow, positive→yellow-green). Transparency: `90 - 60×confidence`.
Sub-pane management:
1. Register oscillators (MiniOscMeta)
2. Finalize layout (STACK_TOP/BOTTOM/EQUAL_SPLIT policies)
3. Map values: `pane.band_y(unit_val)` converts to vertical coordinate
Diagnostic tables: key-value pairs, multi-column grids, conditional formatting.
## Why this is original
Only PulseWire library with complete rendering toolkit. Existing libraries mix rendering with market logic.
Unique features:
- Sub-pane vertical allocation (automatic band calculation)
- Lightweight UDT variants (co-import with OscLib)
- Diverging gradients with zero-centering
- Confidence-to-transparency mapping
- Regime color enum (consistent color mapping)
Separation of concerns: VisLib (rendering), NumLib (math), SignalLib (signals).
## How to use it
```pine
//@version=6
indicator("CyberVisLib Demo", overlay=false)
import cybermediaboy/CyberVisLib/5 as VL
// Diverging gradient
rsi = ta.rsi(close, 14)
z_rsi = (rsi - 50.0) / 25.0
color rsi_color = VL.f_diverging_rgyg(z_rsi)
plot(rsi, "RSI", color=rsi_color)
// Sub-pane management
var spm = VL.f_subpane_manager_new(VL.SubPanePolicy.EQUAL_SPLIT, 5.0)
if barstate.isfirst
spm.register(VL.f_meta_unipolar0100("rsi", "RSI", color.blue))
spm.register(VL.f_meta_bipolar("macd", "MACD", color.orange))
spm.finalize()
var pane_rsi = array.get(spm.panes, 0)
rsi_y = pane_rsi.band_y(pane_rsi.meta.to_unit(rsi))
plot(rsi_y, "RSI Pane", color.blue)
// Confidence transparency
conf = math.abs(rsi - 50.0) / 50.0
bgcolor(color.new(color.green, VL.f_transp(conf)))
```
## Key functions
- `f_blend()` - RGB color blending
- `f_diverging_rgyg()` - Diverging gradient (zero-centered)
- `f_transp()` - Confidence-to-transparency mapping
- `f_subpane_manager_new()` - Sub-pane allocation
- `f_regime_color()` - Regime color enum
- `f_kv_tooltip()` - Tooltip formatting
## Limitations
- Sub-pane allocation static after finalize
- RGB-only blending (no HSL/HSV)
- No automatic label/line cleanup
- Tables require manual cell updates
- Assumes `overlay=false` (separate pane indicators only)
Library

Library

Library

K21CommonLibrary "K21Common"
minDollarMove()
Calculates the minimum dollar move per tick for the current symbol
Returns: (float) Dollar value per tick movement
@description Uses syminfo.pointvalue (contract value per point) and syminfo.minmove
(minimum tick movement) to calculate the dollar value of a single tick.
This works across all futures contracts without manual configuration.
replaceTradeTemplateTags(template, entry_num, description, entry_price, stop_price, tp_price, contracts, risk_dollars, reward_dollars, rr_ratio, max_risk)
Replaces trade related template tags with actual values
Parameters:
template (string) : (string) Template string with tags
entry_num (int) : (int) Entry number (1-5)
description (string) : (string) Entry description
entry_price (float) : (float) Entry price
stop_price (float) : (float) Stop price
tp_price (float) : (float) TP price
contracts (int) : (int) Number of contracts
risk_dollars (float) : (float) Risk in dollars
reward_dollars (float) : (float) Reward in dollars
rr_ratio (float) : (float) Risk:Reward ratio
max_risk (float) : (float) Maximum allowed risk
Returns: (string) Processed template string
isLightColor(clr)
Checks if a color is light based on luminance calculation
Parameters:
clr (color) : (color) The color to check
Returns: (bool) True if the color is light
isDarkColor(clr)
Checks if a color is dark based on luminance calculation
Parameters:
clr (color) : (color) The color to check
Returns: (bool) True if the color is dark
isLightScheme()
Checks if the current chart color scheme is light
Returns: (bool) True if the chart uses a light color scheme
isDarkScheme()
Checks if the current chart color scheme is dark
Returns: (bool) True if the chart uses a dark color scheme
getBarIndexFromTime(target_time)
Finds the bar_index for a given timestamp by searching historical bars
Parameters:
target_time (int) : (int) The timestamp to find
Returns: (int) The bar_index where time matches or is closest to target_time Library
