مكتبة

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. مكتبة

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. مكتبة

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). مكتبة

ImportantLevelsLinesLabels_UtilitiesLevelsLinesLabels_Utilities is a shared Pine v6 utility library for scripts that already resolve their own level values, source candles, session logic, and visibility conditions, but want a reusable level-output layer.
It centralizes the pieces that tend to get rewritten across level-based scripts:
• line-style and label-size resolvers
• EM-space right-label padding
• compact price / $ difference / % difference formatting
• standardized right-side level label text
• above/below-current-price color routing
• bar-time horizontal level line management
• transparent right-side text label management
• synchronized line / label slot-array helpers
• float / int / line / label array pruning helpers
• newest-first history lookup helpers
• Active Period / Source Window / Source Candle start-time routing
• newest-first rolling highest / lowest helpers
• newest-first rolling highest / lowest helpers with matching source time
The example chart demonstrates how a calling script can use the library to render live close-style levels, previous-day high/low levels, rolling completed-window high/low levels, right-side label stacks, source-aware line starts, and reusable object slots.
This library is intentionally focused on output, formatting, object lifecycle, and history-array utilities.
It does not:
• request higher-timeframe data
• decide regular-session versus extended-session sources
• detect sessions, opens, closes, highs, lows, or pivots
• calculate candle levels, VWAPs, pivots, trendlines, or envelopes
• decide which levels should be shown
• own script inputs, tooltips, colors, or final visibility logic
• provide trading signals or directional recommendations
Calling scripts remain responsible for:
• the level engine
• the source engine
• session logic
• request.security() calls
• user inputs and tooltips
• final show/hide conditions
• color choices
• interpretation
How to use
Import the library near the top of your script in global scope, before calling its helpers.
Typical placement:
//@version=6
indicator(...)
import MYNAMEISBRANDON/LevelsLinesLabels_Utilities/1 as LVL
Replace /1 with the latest published version if a newer version is available.
This library expects the calling script to already know the level value, source time, window time, active period start, display state, colors, and label text it wants to use. The library then handles the reusable formatting, line, label, object-slot, pruning, lookup, and rolling-window utility layer.
➖Style Helpers➖
These helpers convert simple user-facing strings into Pine style enums and route colors based on whether price is above or below a level.
levelLineStyle(styleIn)
Converts user-facing line-style text into a Pine line-style enum.
Parameters:
styleIn (simple string): Solid, Dashed, or Dotted
Returns:
Pine line style
levelLabelSize(sizeIn)
Converts user-facing label-size text into a Pine label-size enum.
Parameters:
sizeIn (simple string): Tiny, Small, Normal, Large, or Huge
Returns:
Pine label size
levelColor(level, currentPrice, aboveColor, belowColor)
Routes a level to the above-color or below-color based on the current/reference price.
Parameters:
level (float): Level price
currentPrice (float): Current/reference price
aboveColor (color): Color used when currentPrice is greater than or equal to level
belowColor (color): Color used when currentPrice is below level
Returns:
Resolved color
➖Text Formatting Helpers➖
These helpers keep level labels compact and readable across high-priced stocks, low-priced stocks, crypto pairs, futures-style symbols, and other price scales.
levelSpacer(pad)
Builds EM-space padding for right-side text labels.
levelTrimTrailingZeros(txt)
Removes unnecessary trailing zeros and trailing decimal points.
levelStripLeadingZero(txt)
Removes leading decimal zeroes such as 0.42 → .42 and -0.42 → -.42.
levelSigFig(value, figs)
Rounds a number to a requested number of significant figures.
levelNumberText(value, pattern)
Formats a number with a Pine pattern and then trims unnecessary zeros.
levelPriceText(value, sigFigs)
Formats a level price using significant figures and compact decimal trimming.
levelAbsMoneyText(absValue)
Formats an absolute money value rounded to two decimals.
levelAbsPctText(absValue)
Formats an absolute percent value rounded to two decimals.
levelMoneyChangeText(currentPrice, level)
Formats current price minus level as a signed $ difference.
levelPctChangeText(currentPrice, level)
Formats current price minus level as a signed % difference.
➖Level Label Text Helpers➖
levelLabelText(tag, level, currentPrice, pad, showPrice, showMoneyDiff, showPctDiff, sigFigs)
Builds a standardized right-side level label block.
The label model is:
• optional price row
• optional $ difference row
• optional % difference row
• required level tag row supplied by the calling script
Example output:
741.82
-$22.16
-2.90%
D Hi
EM-space padding is applied to every row. This lets scripts visually stagger labels to the right while keeping the actual label pinned to the current bar_index.
➖Object Sync Helpers➖
These helpers create an object when enabled, update it in place while enabled, and delete it when the caller’s condition turns false.
syncTextLabel(lbl, show, y, txt, txtColor, sizeIn)
Creates, updates, or deletes a transparent right-side text label at the current bar_index.
syncBarTimeLevelLine(ln, show, t1, t2, y, lineColor, lineWidth, styleIn)
Creates, updates, or deletes a horizontal bar-time level line using xloc.bar_time.
This is useful for level scripts that want line starts based on a real timestamp instead of deep bar-index offsets.
➖Slot Array Helpers➖
These helpers let scripts store many repeated level lines and labels in fixed array slots instead of declaring one separate variable per object.
syncLineSlot(lines, slot, show, t1, t2, y, lineColor, lineWidth, styleIn)
Creates, updates, or deletes a bar-time level line stored in a fixed array slot.
syncLabelSlot(labels, slot, show, y, txt, txtColor, sizeIn)
Creates, updates, or deletes a transparent right-side text label stored in a fixed array slot.
Typical use:
const int SLOT_HI = 0
const int SLOT_LO = 1
const int SLOT_CL = 2
var array rowLines = array.new_line(3, na)
var array rowLabels = array.new_label(3, na)
LVL.syncLineSlot(rowLines, SLOT_HI, showHi, hiStartTime, time, hiLevel, hiColor, 2, "Dotted")
LVL.syncLabelSlot(rowLabels, SLOT_HI, showHiLabel, hiLevel, hiText, hiColor, "Normal")
This is especially useful for scripts with repeated rows such as:
• Previous Day High / Low / Close
• Weekly High / Low / Close
• Monthly High / Low / Close
• VWAP bands
• ATR levels
• rolling window levels
• trendline or envelope companion levels
➖History Array Helpers➖
These helpers support scripts that store completed records in arrays, especially newest-first arrays populated with array.unshift().
pruneFloat(arr, maxKeep)
Prunes a float array by popping old records from the end.
pruneInt(arr, maxKeep)
Prunes an int array by popping old records from the end.
pruneLineObjects(arr, maxKeep)
Prunes a line array and deletes removed line objects.
pruneLabelObjects(arr, maxKeep)
Prunes a label array and deletes removed label objects.
pruneHiLoHistory(highs, lows, highTimes, lowTimes, windowTimes, maxKeep)
Prunes synchronized high / low / high-time / low-time / window-time arrays.
pruneHlcHistory(highs, lows, closes, highTimes, lowTimes, closeTimes, windowTimes, maxKeep)
Prunes synchronized high / low / close / source-time / window-time arrays.
histFloat(arr, idx)
Returns a float history value at an array index, or na if unavailable.
histInt(arr, idx)
Returns an int history value at an array index, or na if unavailable.
requestOrManual(requestValue, manualValue)
Returns a requested value when available, otherwise the manual value.
manualOrRequest(manualValue, requestValue)
Returns a manual value when available, otherwise the requested value.
manualSourceTime(manualValue, times, idx)
Returns a matching manual source time only when the matching manual value exists.
➖Source Start-Time Helpers➖
These helpers route line-start timestamps using a common level-script model.
sourceLineStartTime(mode, sourceTime, activeTime)
Resolves Active Period versus Source Candle / Source Close Candle starts.
windowSourceLineStartTime(mode, windowTime, sourceTime, activeTime)
Resolves Active Period, Source Window, Source Candle, or Source Close Candle starts.
Start-time model:
Active Period:
Uses the active period start supplied by the calling script.
Source Window:
Uses the completed source window start supplied by the calling script.
Source Candle / Source Close Candle:
Uses the exact source candle time supplied by the calling script when available. If the exact source candle time is not available, it falls back to Source Window when available, then Active Period.
This keeps the library generic while allowing calling scripts to decide what a “source candle” means in their own context.
➖Newest-First Rolling Extreme Helpers➖
These helpers are built for arrays where index 0 is the most recent completed record.
Newest-first history model:
• index 0 = most recent completed record
• index 1 = one completed record back
• index 2 = two completed records back
• index 3 = three completed records back
• index 4 = four completed records back
A 5-record rolling high scans indexes 0 through 4 when available.
highestNewestFirst(values, lookback)
Returns the highest value and matching array index from a newest-first array window.
lowestNewestFirst(values, lookback)
Returns the lowest value and matching array index from a newest-first array window.
highestNewestFirstWithTime(values, times, lookback)
Returns the highest value, matching array index, and matching source time from synchronized newest-first arrays.
lowestNewestFirstWithTime(values, times, lookback)
Returns the lowest value, matching array index, and matching source time from synchronized newest-first arrays.
Important note:
The returned index is an array index, not a bar offset. If the calling script stores synchronized time arrays, the “with time” helpers can also return the matching source timestamp.
Example:
// Newest-first arrays populated with array.unshift().
= LVL.highestNewestFirstWithTime(
dailyHighHistory,
dailyHighTimeHistory,
5)
= LVL.lowestNewestFirstWithTime(
dailyLowHistory,
dailyLowTimeHistory,
5)
➖Recommended Usage➖
This library works best when the calling script follows this workflow:
1. Resolve the level value in the script.
2. Resolve the source candle time or source window time in the script.
3. Resolve the final visibility condition in the script.
4. Use this library to format the label, route color, choose start time, and manage the line/label object.
This keeps source logic and interpretation script-level while making the reusable output layer cleaner and easier to maintain.
➖Important Notes➖
This library is a utility layer only.
It does not:
• request data
• detect sessions
• choose RTH or EXT behavior
• calculate previous-day levels
• calculate VWAP
• calculate pivots
• calculate trendlines
• decide trade direction
• generate signals
Calling scripts remain responsible for their own engine logic and interpretation.
The included demo script is meant to show how the library can be used to manage live levels, previous-day levels, rolling completed-record levels, label padding, object slots, and start-time routing.
مكتبة

MarketPokerEnginev2
MarketPokerEnginev2
: Advanced Hand Evaluation Library
Overview
MarketPokerEngine is an institutional-grade, highly optimized library designed to evaluate poker hand combinatorics within Pine Script v6. It is specifically engineered to offload heavy logical processing and Abstract Syntax Tree (AST) node consumption from your main indicator script, ensuring rapid execution speeds even during live tick, multi-state simulations.
Core Architecture
The engine operates on a strict 5-card subset evaluation model. By feeding it exact 5-element arrays, the library mathematically guarantees zero false-positive evaluations (such as cross-suit straight flushes) without requiring excessive loop iterations.
Key Features & Functions
evaluate_hand(int ranks, int suits): The primary evaluation engine. It takes two 5-element arrays (ranks and suits) and returns a comprehensive tuple of 10 boolean/integer flags representing every possible hand hierarchy (from Royal Flush down to High Card), including Joker counts.
get_card_vertical(int r, int s): A streamlined string formatting utility. It converts raw integer IDs into clean, vertical Unicode representations (e.g., "♠️ A") optimized for box.new() or label.new() UI rendering.
Implementation Note
This library assumes 0 is reserved for Jokers, 1-13 for standard ranks (A-K), and 1-4 for standard suits. It is highly recommended to pair this library with a master script that generates combinatoric 5-card subsets (e.g., 21 combinations for a 7-card Texas Hold'em board) to determine the absolute best hand score.
日本語公開文
MarketPokerEngine: 高度なポーカー役判定コアライブラリ
概要
MarketPokerEngine は、Pine Script v6においてポーカーの役(組み合わせ)評価を処理するための、高度に最適化された専用ライブラリです。メインのインジケータースクリプトから複雑な論理演算を切り離し、抽象構文木(AST)ノードの枯渇を回避することで、ライブティック更新時や多状態シミュレーションにおいても極めて軽量な実行速度を担保します。
コア・アーキテクチャ
本エンジンは、厳密な「5要素部分集合(Subset)」の評価モデルを採用しています。7枚などの複合状態から5要素の配列を抽出して本ライブラリに渡すことで、「スートが異なるストレートフラッシュ」などの誤判定を数学的かつ構造的に排除し、無駄な計算ループを必要としない洗練された判定を実現しています。
主要機能
evaluate_hand(int ranks, int suits): 判定エンジンの心臓部です。ランク(数字)とスート(マーク)の5要素配列を受け取り、ロイヤルフラッシュからワンペアまでの全役のフラグ、およびジョーカーの枚数を含む10要素のタプル(戻り値のまとまり)を高速で返します。
get_card_vertical(int r, int s): UI描画のための文字列フォーマット機能です。内部の整数IDを、box.new() や label.new() での表示に最適化されたクリーンな縦型のUnicodeテキスト(例: "♠️ A")に即座に変換します。
実装上の注意事項
本ライブラリは、整数 0 をジョーカー、1-13 をランク(A-K)、1-4 をスートとして処理します。テキサスホールデムのような7枚のカードを扱うシステムに組み込む場合は、メインスクリプト側で7枚から5枚を選ぶ全21通りの組み合わせループを構築し、本ライブラリの評価を通過させることで、最もスコアの高い役を正確に抽出することが推奨されます。
مكتبة

مكتبة

مكتبة

مكتبة

مكتبة

ExprLibExprLib is a library for parsing and evaluating string expressions. It allows scripts to expose configurable logic by letting users define custom conditions and calculations based on available data.
█ KEY FEATURES
• Rich expression support:
• Built-in constants (e.g., `10`, `2.5`, `5e-2`, `true`, `false`, `na`)
• Custom constants
• Variables
• Arithmetic operators: `+`, `-`, `*`, `/`, `%`
• Comparison operators: `>`, `<`, `>=`, `<=`, `==`, `!=`
• Logical operators: `AND`, `OR`, `NOT` (with aliases)
• Ternary operator: `condition ? if_true : if_false`
• Parentheses: `(`, `)`
• Built-in functions: `na()`, `nz()`, `max()`, `pow()`, `sqrt()`, `random()`, and more!
• Graceful error handling during parsing and evaluation
• Optimized for evaluation performance (RPN-based approach)
█ NOTE
Since the library description cannot be changed or removed after publication, some information here may be outdated. However, you can always get the latest version of the documentation at the bottom of the source code.
█ QUICK START
An example of an indicator that colors areas on a chart where the expression evaluates to `true`:
//@version=6
indicator("Quick Start", overlay = true)
import A1trdX/ExprLib/1 as ExprLib
// ---------------
// INPUTS
// ---------------
// Let the user customize the expression
inputExpressionStr = input.text_area("trend_up AND (rsi < 50 OR close < open)", "Expression")
// -------------------
// CALCULATION
// -------------------
// Prepare some data to use in the expression.
rsi = ta.rsi(close, 14)
ema = ta.ema(close, 200)
isTrendUp = close > ema
isTrendDown = close < ema
// Step 0: Prepare the parser and evaluator.
var parser = ExprLib.createExpressionParser()
var evaluator = ExprLib.createExpressionEvaluator()
// Step 1: Parse the expression string.
var expression = parser.parse(inputExpressionStr)
// Step 2 (Recommended): Verify whether the expression was parsed without errors.
if not parser.isParsed
// You can define your own logic to handle errors
runtime.error("Failed to parse expression: " + parser.error.message)
// Step 3: Assign values to variables. Both numbers and booleans are supported.
expression.setVariable("open", open)
expression.setVariable("close", close)
expression.setVariable("rsi", rsi)
expression.setVariable("trend_up", isTrendUp)
expression.setVariable("trend_down", isTrendDown)
// Step 4: Evaluate the expression.
bool result = evaluator.evaluateToBool(expression)
// Step 4 (Alternative): If you expect a numeric result, use `evaluate()` instead.
// float result = evaluator.evaluate(expression)
// Step 5 (Recommended): Verify whether the expression was evaluated without errors.
if not evaluator.isEvaluated
// You can define your own logic to handle errors
runtime.error("Failed to evaluate expression: " + evaluator.error.message)
// ----------------
// GRAPHICS
// ----------------
// Highlight bars where the expression returns `true`
bgcolor(result ? color.new(color.green, 90) : na)
█ EXPRESSION SYNTAX REFERENCE
❱❱ Components
An expression can include:
• Constants
• Variables
• Operators
• Functions
• Parentheses
• Spaces, tabs, or newlines
❱❱ Data Types
Constants and variables can have the following data types:
• Numeric (`int`, `float`)
• Boolean (`bool`)
• Undefined (`na`)
❱❱ Identifiers
Identifiers are names used to refer to named constants, variables, and functions.
Identifier naming rules:
• Must start with a letter (`a-z`, `A-Z`) or underscore (`_`).
• May contain letters (`a-z`, `A-Z`), digits (`0-9`), and underscores (`_`).
Identifiers cannot contain spaces or other characters.
Identifiers are case-sensitive.
❱❱ Constants
Numeric Constants
Examples:
+-----------+--------------+
| Constant | Plain Value |
+-----------+--------------+
| 12 | 12.00 |
| 0.05 | 0.05 |
| .05 | 0.05 |
| 5e-2 | 0.05 |
| 5E-2 | 0.05 |
| 1.2e4 | 12000.00 |
+-----------+--------------+
Named Constants
Available built-in named constants:
+----------+-------------------------------------+-------------------------+
| Name | Description | Pine Script Equivalent |
+----------+-------------------------------------+-------------------------+
| `true` | Boolean TRUE | `true` |
| `false` | Boolean FALSE | `false` |
| `na` | Undefined value | `na` |
| `pi` | Pi (~3.14159) | `math.pi` |
| `e` | Euler's number (~2.71828) | `math.e` |
| `phi` | Golden ratio (~1.61803) | `math.phi` |
| `rphi` | Golden ratio conjugate (~0.61803) | `math.rphi` |
+----------+-------------------------------------+-------------------------+
It is possible to add custom constants.
❱❱ Variables
It is possible to add variables, just like custom constants, except that variable values can be changed before each evaluation.
❱❱ Operators
The following operators are supported:
+--------------+-------------+-------------------------+-------------+------------------+-------------+
| Type | Operator | Name | Aliases | Example #1 | Example #2 |
+--------------+-------------+-------------------------+-------------+------------------+-------------+
| Arithmetic | `+` | Add | | `a + b` | |
| Arithmetic | `-` | Subtract | | `a - b` | |
| Arithmetic | `*` | Multiply | | `a * b` | |
| Arithmetic | `/` | Divide | | `a / b` | |
| Arithmetic | `%` | Modulo | | `a % b` | |
| Comparison | `>` | Greater than | | `a > b` | |
| Comparison | `<` | Less than | | `a < b` | |
| Comparison | `>=` | Greater than or equal | | `a >= b` | |
| Comparison | `<=` | Less than or equal | | `a <= b` | |
| Comparison | `==` | Equal | | `a == b` | |
| Comparison | `!=` | Not equal | | `a != b` | |
| Logical | `AND` | Logical AND | `&&`, `&` | `a AND b` | `a && b` |
| Logical | `OR` | Logical OR | `||`, `|` | `a OR b` | `a || b` |
| Logical | `NOT` | Logical NOT | `!` | `NOT x` | `!x` |
| Conditional | `?:` | Ternary | | `cond ? x : y` | |
| Unary | Unary `+` | Unary plus | | `+x` | |
| Unary | Unary `-` | Unary minus | | `-x` | |
+--------------+-------------+-------------------------+-------------+------------------+-------------+
Logical operator names are case-insensitive.
Operator precedence:
+------------+-----------------------------+
| Precedence | Operators |
+------------+-----------------------------+
| 8 | Unary `-`, Unary `+`, `NOT` |
| 7 | `*`, `/`, `%` |
| 6 | `+`, `-` |
| 5 | `>`, `<`, `>=`, `<=` |
| 4 | `==`, `!=` |
| 3 | `AND` |
| 2 | `OR` |
| 1 | `?:` |
+------------+-----------------------------+
Operator associativity:
• Unary `+`, Unary `-`, `NOT`, and ternary are right-associative
• Other operators are left-associative
❱❱ Parentheses
Parentheses are used to group sub-expressions and override the default operator precedence.
Example:
((a + b) * c + 1) * d
❱❱ Functions
Functions are called by an identifier followed immediately by parentheses: `func(arg1, arg2)`.
Arguments are separated by commas. Each argument can be any valid expression, including another function call.
Available built-in functions:
+-------------------------------+----------+------------------------------------------------------------------------+
| Function | Args | Description |
+-------------------------------+----------+------------------------------------------------------------------------+
| `na(x)` | 1 | Returns `true` when `x` is `na`, `false` otherwise. |
| `nz(x, fallback)` | 2 | Returns `x` when it is not `na`, `fallback` otherwise. |
| `max(x1, x2, ...)` | 2..999 | Returns the largest argument. |
| `min(x1, x2, ...)` | 2..999 | Returns the smallest argument. |
| `pow(base, exponent)` | 2 | Returns `base` raised to `exponent`. |
| `sqrt(x)` | 1 | Returns the square root of `x`. |
| `clamp(x, min, max)` | 3 | Restricts `x` to the ` ` range. |
| `abs(x)` | 1 | Returns the absolute value of `x`. |
| `ceil(x)` | 1 | Rounds `x` up to the nearest integer. |
| `floor(x)` | 1 | Rounds `x` down to the nearest integer. |
| `round(x)` | 1 | Rounds `x` to the nearest integer. |
| `round_to_mintick(x)` | 1 | Rounds `x` to the symbol's minimum tick precision. |
| `log(x)` | 1 | Returns the natural logarithm of `x`. |
| `log10(x)` | 1 | Returns the base-10 logarithm of `x`. |
| `sign(x)` | 1 | Returns the sign of `x`: `1`, `0`, or `-1`. |
| `cos(x)` | 1 | Returns the cosine of `x` in radians. |
| `sin(x)` | 1 | Returns the sine of `x` in radians. |
| `tan(x)` | 1 | Returns the tangent of `x` in radians. |
| `acos(x)` | 1 | Returns the arccosine of `x` in radians. |
| `asin(x)` | 1 | Returns the arcsine of `x` in radians. |
| `atan(x)` | 1 | Returns the arctangent of `x` in radians. |
| `deg(x)` | 1 | Converts radians to degrees. |
| `rad(x)` | 1 | Converts degrees to radians. |
| `random(min, max, seed)` | 0..3 | Returns a random float. Bounds default to 0 and 1. Seed is optional. |
| `random_int(min, max, seed)` | 2..3 | Returns a random integer. Seed is optional. |
| `random_bool(seed)` | 0..1 | Returns a random boolean value. Seed is optional. |
+-------------------------------+----------+------------------------------------------------------------------------+
The number of arguments can be either fixed or variable.
For example, the `max(x1, x2, ...)` function supports 2 to 999 arguments, so the following calls to this function are valid:
max(x1, x2)
max(x1, x2, x3)
max(x1, x2, x3, x4, x5)
Other functions may have optional arguments. For example, the following calls to the `random(min, max, seed)` function are valid:
random() // Random float from 0 to 1
random(0.5) // Random float from 0.5 to 1
random(0.5, 2) // Random float from 0.5 to 2
random(0.5, 2, 777) // Random float from 0.5 to 2 with a specific seed
❱❱ Whitespace
Spaces, tabs, and line breaks are ignored between symbols. For example, an expression can be formatted across multiple lines:
price > ema_slow
AND ema_fast > ema_slow
AND (bb_lo_up OR rsi_lo_up)
█ PARSING
❱❱ Workflow
Before evaluating an expression, it must be parsed. To do this:
• Create a parser in advance using the `createExpressionParser()` function.
• Call the `parse()` method, passing the expression string as an argument.
Example:
var parser = ExprLib.createExpressionParser()
var expr1 = parser.parse("a + 2")
var expr2 = parser.parse("a + b * c")
❱❱ Error Handling
A user may enter an invalid expression. In this case, the parser will return `na` instead of a valid expression object. The parser stores the result of the last parse. You can use that result to retrieve the status and error information.
Parser and error field structures:
type ExpressionParser
bool isParsed // `true` if the last parse completed successfully, `false` otherwise.
ParseError error // Error from the last parse attempt. If the last parse was successful, then this field is `na`.
type ParseError
string message // Error message.
int index // Character index where the parser detected the error.
For example, suppose we want to display an error message on the chart if one of the expressions is invalid:
//@version=6
indicator("Parser Error Handling")
import A1trdX/ExprLib/1 as ExprLib
inputExpr1 = input.text_area("a + 2", "Expression 1")
inputExpr2 = input.text_area("a + b * c /", "Expression 2")
displayErrorMessage(string errorMessage) =>
var table errorMessageTable = na
if na(errorMessageTable)
errorMessageTable := table.new(position.top_right, 1, 1)
errorMessageTable.cell(0, 0, errorMessage,
bgcolor = color.red,
text_color = color.white,
text_halign = text.align_left,
text_formatting = text.format_bold)
checkParsed(ExprLib.ExpressionParser parser, string prefix) =>
if not parser.isParsed
displayErrorMessage(prefix + parser.error.message)
var parser = ExprLib.createExpressionParser()
var expr1 = parser.parse(inputExpr1)
checkParsed(parser, "Failed to parse expression #1: ")
var expr2 = parser.parse(inputExpr2)
checkParsed(parser, "Failed to parse expression #2: ")
A blank expression (e.g., "") is allowed and will evaluate to `na` (or `false` when returning a boolean value).
❱❱ Custom Constants
You can add your own named constants during the parsing stage. To do this:
• Create a constant pool in advance using the `createConstantPool()` function.
• Set constants and their values using the `set()` method.
• Pass the constant pool to the `parse()` method.
Example:
var constantPool = ExprLib.createConstantPool()
if barstate.isfirst
constantPool.set("one", 1)
constantPool.set("two", 2)
constantPool.set("three_p_one", 3.1)
constantPool.set("yes", true)
constantPool.set("no", false)
var parser = ExprLib.createExpressionParser()
var expr = parser.parse("one + two", constantPool)
The `set()` method returns the same constant pool object, so you can chain calls together. This is more convenient and more elegant:
var constantPool = ExprLib.createConstantPool()
.set("one", 1)
.set("two", 2)
.set("three_p_one", 3.1)
.set("yes", true)
.set("no", false) // Note that the indentation is 7 spaces (not a multiple of 4)
var parser = ExprLib.createExpressionParser()
var expr = parser.parse("one + two", constantPool)
You can also override built-in constants:
var constantPool = ExprLib.createConstantPool()
.set("true", false)
.set("false", -1)
.set("na", 0.0)
█ EVALUATION
❱❱ Type Coercion
An expression can consist of values of different data types. ExprLib does not have strict data type checking. Instead, all values are converted to `float` and then back if necessary.
Converting `bool` to `float`:
• `true` -> `1.0`
• `false` -> `0.0`
Converting `float` to `bool`:
• `0.0` or `na` -> `false`
• Any other value -> `true`
Thus, expressions that incorrectly combine different data types are allowed. For example, `true + 2` will return `3.0`. Strict typing requires additional memory as well as additional computational resources during evaluation, which is a critical concern. Therefore, it was decided not to implement it.
As in Pine Script, most operations with an `na` operand results in `na` or `false`, but logical operations first convert `na` to `false`, so their result follows boolean logic. For example:
• `3 - na` returns `na`
• `3 > na` returns `false`
• `3 <= na` also returns `false`
• `na AND true` returns `false`
• `na OR true` returns `true`
• `NOT na` returns `true`
❱❱ Workflow
To evaluate an expression:
• Create an evaluator in advance using the `createExpressionEvaluator()` function.
• Set variables and their values in the expression using the `setVariable()` method.
• Call the `evaluate()` or `evaluateToBool()` method, passing the expression as an argument.
The `evaluate()` and `evaluateToBool()` methods differ in their return types. The former returns a `float` result, while the latter returns a `bool` result. The method to call depends on the expected result type.
Example:
// Parsed expressions:
// - expr1 <= "(H - L) / 2 + L"
// - expr2 <= "rsi_oversold AND close > open"
// Initialize evaluator
var evaluator = ExprLib.createExpressionEvaluator()
// Set variables and evaluate the first expression
expr1.setVariable("H", high)
expr1.setVariable("L", low)
float result1 = evaluator.evaluate(expr1)
// Set variables and evaluate the second expression
rsi = ta.rsi(close, 14)
expr2.setVariable("open", open)
expr2.setVariable("close", close)
expr2.setVariable("rsi_oversold", rsi < 30)
expr2.setVariable("rsi_overbought", rsi > 70)
bool result2 = evaluator.evaluateToBool(expr2)
❱❱ Variables
If an expression contains an identifier that is neither a function nor a constant, and this identifier has not been assigned a variable value, then this identifier is considered a constant with the value `na` (or `false` in boolean operations).
The `setVariable()` method overrides existing constants (both built-in and custom). For example, by default, the identifier `e` is used as the constant Euler's number (~2.71828). However, you can make `e` your own variable:
// Parsed expressions:
// - expr <= "e + 1"
expr.setVariable("e", 5) // Now `e` is equal to `5` instead of `2.7182818284590452`
result = evaluator.evaluate(expr) // `6.0`
The `setVariable()` method does not need to be called on each bar if the variable's value does not change. The expression always stores and uses the last value set.
You can clear all previously set variables using the `clearVariables()` method. This can be useful if you have many variables and want to reset them all and set values for only a small subset.
❱❱ Error Handling
In some cases (for example, when dividing by zero), evaluation results in an error. In this case, `evaluate()` will return `na`, and `evaluateToBool()` will return `false`. Like the parser, the evaluator stores the result of the last evaluation.
Evaluator and error field structures:
type ExpressionEvaluator
bool isEvaluated // `true` if the last evaluation completed successfully, `false` otherwise.
EvaluationError error // Error from the last evaluation attempt. If the last evaluation was successful, then this field is `na`.
type EvaluationError
EvaluationErrorReason reason // Error reason.
string message // Error message.
enum EvaluationErrorReason
DIVISION_BY_ZERO
Example:
//@version=6
indicator("Evaluator Error Handling")
import A1trdX/ExprLib/1 as ExprLib
inputExpr1 = input.text_area("a + 2", "Expression 1")
inputExpr2 = input.text_area("a + b / c", "Expression 2")
displayErrorMessage(string errorMessage) =>
var table errorMessageTable = na
if na(errorMessageTable)
errorMessageTable := table.new(position.top_right, 1, 1)
errorMessageTable.cell(0, 0, errorMessage,
bgcolor = color.red,
text_color = color.white,
text_halign = text.align_left,
text_formatting = text.format_bold)
// Parse
checkParsed(ExprLib.ExpressionParser parser, string prefix) =>
if not parser.isParsed
displayErrorMessage(prefix + parser.error.message)
var parser = ExprLib.createExpressionParser()
var expr1 = parser.parse(inputExpr1)
checkParsed(parser, "Failed to parse expression #1: ")
var expr2 = parser.parse(inputExpr2)
checkParsed(parser, "Failed to parse expression #2: ")
// Evaluate
checkEvaluated(ExprLib.ExpressionEvaluator evaluator, string prefix) =>
if not evaluator.isEvaluated
displayErrorMessage(prefix + evaluator.error.message)
var evaluator = ExprLib.createExpressionEvaluator()
expr1.setVariable("a", open)
expr1.setVariable("b", close)
expr1.setVariable("c", 0)
result1 = evaluator.evaluate(expr1)
checkEvaluated(evaluator, "Failed to evaluate expression #1: ")
expr2.setVariable("a", open)
expr2.setVariable("b", close)
expr2.setVariable("c", 0)
result2 = evaluator.evaluate(expr2)
checkEvaluated(evaluator, "Failed to evaluate expression #2: ")
Currently, the only possible cause of this error is division by zero. You can disable this error and have the evaluator interpret the result of division by zero as `na`. To do this, disable the corresponding flag in the evaluator:
evaluator.setFailOnDivisionByZero(false)
Thus, an expression like `na(5 / 0) ? 1 : 2` will return `1` instead of an error.
█ BEST PRACTICES
• Reuse `ExpressionParser` and `ExpressionEvaluator` objects whenever possible.
• Parse expressions only once, and evaluate them as needed. Parsing is slow. Evaluation is fast.
• If certain variable values change rarely, call `setVariable()` only when necessary.
• Try to avoid excessive numbers of variables whose values change frequently. This can impact performance even if they're not used in the expression.
█ API REFERENCE
❱❱ Expression Parser
ExpressionParser
Expression parser.
Fields:
isParsed (series bool) : `true` if the last parse completed successfully, `false` otherwise.
error (ParseError) : Error from the last parse attempt. If the last parse was successful, then this field is `na`.
createExpressionParser()
Creates an expression parser.
Returns: Expression parser.
method parse(parser, exprStr, constantPool)
Parses an expression.
Namespace types: ExpressionParser
Parameters:
parser (ExpressionParser) : Expression parser.
exprStr (string) : Expression string. Can be empty, blank, or 'na'. That way expression is valid and will return `na` on evaluation.
constantPool (ExpressionConstantPool) : (Optional) Named constants.
Returns: Parsed expression. If an error occurs during parsing, then the returned expression will be `na`.
You can check validity and error details accessing parser's `isParsed` and `error` fields.
❱❱ Expression
Expression
Parsed expression.
method setVariable(expr, identifier, value)
Assigns a numeric value to a variable.
Namespace types: Expression
Parameters:
expr (Expression) : Expression.
identifier (string) : Variable name.
value (float) : Value.
Returns: This expression.
method setVariable(expr, identifier, value)
Assigns a boolean value to a variable.
Namespace types: Expression
Parameters:
expr (Expression) : Expression.
identifier (string) : Variable name.
value (bool) : Value.
Returns: This expression.
method clearVariables(expr)
Clears all variable values.
Namespace types: Expression
Parameters:
expr (Expression) : Expression.
Returns: This expression.
❱❱ Constant Pool
ExpressionConstantPool
Expression constant pool.
createConstantPool()
Creates an expression constant pool.
Returns: Expression constant pool.
method set(pool, identifier, value)
Assigns a numeric constant value.
Namespace types: ExpressionConstantPool
Parameters:
pool (ExpressionConstantPool) : Expression constant pool.
identifier (string) : Constant name.
value (float) : Value.
Returns: This expression constant pool.
method set(pool, identifier, value)
Assigns a boolean constant value.
Namespace types: ExpressionConstantPool
Parameters:
pool (ExpressionConstantPool) : Expression constant pool.
identifier (string) : Constant name.
value (bool) : Value.
Returns: This expression constant pool.
method clear(pool)
Clears all constants.
Namespace types: ExpressionConstantPool
Parameters:
pool (ExpressionConstantPool) : Expression constant pool.
Returns: This expression constant pool.
❱❱ Expression Evaluator
ExpressionEvaluator
Expression evaluator.
Fields:
isEvaluated (series bool) : `true` if the last evaluation completed successfully, `false` otherwise.
error (EvaluationError) : Error from the last evaluation attempt. If the last evaluation was successful, then this field is `na`.
result (series float) : Numeric result of the last evaluation.
boolResult (series bool) : Boolean result of the last evaluation.
createExpressionEvaluator()
Creates an expression evaluator.
Returns: Expression evaluator.
method evaluate(evaluator, expr)
Evaluates an expression.
Namespace types: ExpressionEvaluator
Parameters:
evaluator (ExpressionEvaluator) : Expression evaluator.
expr (Expression) : Expression to evaluate.
Returns: Numeric evaluation result.
For boolean-result expressions `1.0` means `true` and `0.0` means `false`.
Returns `na` if expression is empty.
method evaluateToBool(evaluator, expr)
Evaluates an expression.
Namespace types: ExpressionEvaluator
Parameters:
evaluator (ExpressionEvaluator) : Expression evaluator.
expr (Expression) : Expression to evaluate.
Returns: Boolean evaluation result.
Returns `false` if expression is empty.
method setFailOnDivisionByZero(evaluator, value)
Sets whether division or modulo by zero should fail evaluation.
Namespace types: ExpressionEvaluator
Parameters:
evaluator (ExpressionEvaluator) : Expression evaluator.
value (bool) : If `true`, division or modulo by zero fails evaluation. If `false`, it produces `na`.
Returns: This expression evaluator.
❱❱ Errors
ParseError
Error that occurred during expression parsing.
Fields:
message (series string) : Error message.
index (series int) : Character index where the parser detected the error.
EvaluationError
Error that occurred during expression evaluation.
Fields:
reason (series EvaluationErrorReason) : Error reason.
message (series string) : Error message. مكتبة

مكتبة

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 مكتبة

VoltRouter Webhook BuilderBuild TradingView alert webhook payloads for VoltRouter — a signal routing service that executes your TradingView strategy alerts directly at your broker. $0.07/signal, pay-as-you-go, no subscription required .
Supports: market, limit, stop, bracket (TP+SL), trailing stop, FLAT, and cancel-all.
How to use:
1. Sign up at voltrouter.com and connect your broker
2. Import this library in your strategy
3. Paste the output into a TradingView alert → Webhook URL field
Setup: voltrouter.com
import VoltRouterWebhook as vr
// In your strategy alert message field:
vr.market("MNQM26", "buy", 1, "ibkr", "my_strategy")
vr.bracket("MNQM26", "sell", 1, close + 10, close - 5)
vr.flat("MNQM26") مكتبة

lib_pickmytradeLibrary "lib_pickmytrade"
a simple helper to create webhook messages for alert webhooks to pickmytrade
alert_msg_exit(account_id, token)
generates a json formatted EXIT message string for an alert() call, simply closing any open trade
Parameters:
account_id (string) : the pickmytrade account id
token (string) : the pickmytrade token
Returns: a json formatted message string for the alert() call
alert_msg_trail_sl(account_id, token, is_long, trail_sl)
generates a json formatted TRAIL STOP LOSS message string for an alert() call
Parameters:
account_id (string) : the pickmytrade account id
token (string) : the pickmytrade token
is_long (bool) : trade direction
trail_sl (float) : new stop loss level
Returns: a json formatted message string for the alert() call
alert_msg_entry(account_id, token, is_long, tp1, qty1, tp2, qty2, tp3, qty3, sl, tp1_be_offset, limit_price, limit_cancel_time)
generates a json formatted ENTRY message string for an alert() call
Parameters:
account_id (string) : the pickmytrade account id
token (string) : the pickmytrade token
is_long (bool) : trade direction
tp1 (float) : tp1 target
qty1 (int) : tp1 quantity (optional)
tp2 (float) : tp2 target
qty2 (int) : tp2 quantity (optional)
tp3 (float) : tp3 target
qty3 (int) : tp3 quantity (optional)
sl (float) : sl stop
tp1_be_offset (float) : sl to be when hitting tp1, with this offset (optional, must be >= 0)
limit_price (float) : limit entry target (optional)
limit_cancel_time (int) : limit entry cancel time, if not filled (gtc) (optional)
Returns: a json formatted message string for the alert() call مكتبة

DafeRCMLibRolling Confidence Matrix Library (RCM)
A Structural Evidence Accumulation Engine for Pine Script Developers
What This Library Does
The Rolling Confidence Matrix (RCM) is a developer library that provides a stateful structural analysis engine for Pine Script indicators. It maintains rolling evidence buckets that accumulate and decay observations about market structure on every bar, then synthesizes those observations into confidence scores, a directional state classification, and a set of modulation outputs that downstream indicators can consume.
The library is designed to be algorithm-agnostic. It does not generate signals, draw lines, or produce visual output. It computes structural context that other indicators use to make better decisions — whether that indicator is a Supertrend, a moving average crossover, a Bollinger Band system, or a machine learning model.
The Problem This Solves
Traditional indicators are structurally blind. A Supertrend calculates band width from ATR alone. A moving average crossover fires regardless of whether the cross happens during a structural breakout or inside exhaustion chop. A Bollinger Band squeeze looks identical mathematically whether it precedes a genuine expansion or a false breakout.
These indicators lack the ability to evaluate what kind of price action is producing their signals. The RCM addresses this by maintaining a persistent, per-bar structural memory that any indicator can query.
How It Works: The Five Evidence Buckets
The RCM tracks five categories of structural evidence, accumulated separately for bull and bear sides (10 buckets total). Each bucket decays by a configurable rate every bar, accumulates when its specific conditions are detected, and is hard-capped to prevent runaway values.
Impulse — Detects directional thrust bars. Criteria: body exceeds the 10-bar average body by 15%, close position is in the upper 30% (bull) or lower 30% (bear) of the bar's range, and the bar's range exceeds the 10-bar average range by 5%. Volume confirmation adds additional evidence when the volume ratio exceeds 1.2x the 20-bar average.
Structure — Detects swing-level events. Criteria: price closes above the 5-bar highest high (swing break), price sweeps below a swing low and reclaims it on a bullish close (reclaim), or price wicks through a swing level but closes back inside (sweep absorption). Each event type contributes a different evidence weight, reflecting its structural significance.
Exhaustion — Detects reversal pressure. Criteria: a bearish-body bar with a lower wick exceeding 45% of the total range on volume above 1.2x average contributes bull exhaustion evidence (potential buying absorption). The inverse applies for bear exhaustion. This bucket represents counter-trend pressure building within the current move.
Continuation — Detects trend persistence. Criteria: the EMA(21) of HLC3 has a positive slope, price is above the anchor, and the current close exceeds the previous close. This bucket also has asymmetric decay: when price moves to the wrong side of the anchor, continuation evidence decays at 62% per bar instead of the standard rate. Anchor crosses trigger a 50% immediate reduction.
Compression — Detects range contraction. Criteria: the current bar's range is below 80% of the 10-bar average range, and the ATR(14) to SMA(ATR,30) ratio is below 0.95. Compression evidence accumulates on the side of the anchor (bull compression above, bear compression below), representing potential energy buildup before expansion.
Bucket Caps
Each bucket has a defined maximum to prevent any single evidence type from dominating the confidence calculation:
Impulse: 25
Structure: 30
Exhaustion: 20
Continuation: 20
Compression: 15
Confidence Computation
Bull and bear confidence scores are computed as weighted sums of their respective five buckets:
bullConf = bullImpulse × wImpulse + bullStructure × wStructure +
bullExhaustion × wExhaustion + bullContinuation × wContinuation +
bullCompression × wCompression
Default weights are: Impulse 1.20, Structure 1.35, Exhaustion 1.15, Continuation 1.00, Compression 0.90. Structure carries the highest default weight because swing-level events are the most structurally significant observations.
From these scores, the library derives:
Net Confidence: bullConf − bearConf
Activity: bullConf + bearConf (total evidence in the system)
Dominance: netConf / activity (how one-sided the evidence is, range −1 to +1)
Bull/Bear Pressure: each side's share of total activity (range 0 to 1)
The Three-State Engine
The state engine uses hysteresis to prevent flickering between states. Entering a state requires strong evidence; holding a state requires only moderate evidence.
Entry Conditions (Transition → Bull/Bear):
Net confidence exceeds the entry threshold (default: 12.0)
AND dominance exceeds the dominance threshold (default: 0.18)
Hold Conditions (Bull/Bear → Transition):
A state is lost when ANY of:
Net confidence drops below the hold threshold (default: 5.0)
Opposing pressure exceeds the flip pressure threshold (default: 0.58)
Erosion (peak confidence minus current) exceeds 35% of current confidence
This hysteresis design means the engine requires conviction to enter a directional state but gives the trend room to breathe once established.
Substates
When the engine is in Transition (state = 0), it internally classifies the type of transition based on which evidence buckets are dominant:
Early (substate 1): Within 3 bars of losing a directional state. Evidence is collapsing.
Contested (substate 2): Both bull and bear confidence exceed 50% of the entry threshold. Both sides have material evidence.
Rotational (substate 3): Exhaustion buckets represent more than 35% of total non-compression evidence. The market is churning.
Compression (substate 4): Compression buckets exceed 35% of total evidence while impulse is below 15%. Energy is building.
The external state remains 0 for all substates. Consumers who need granularity can query st.substate.
Damage Detection
When the engine is in a directional state, it evaluates structural compromise on every bar by accumulating a damage score from seven independent checks:
For a Bull state, damage accumulates from:
Price below the anchor (+1.5)
Bear impulse condition detected (+1.0)
Upper wick ratio exceeds 35% (+0.75)
Anchor slope is negative (+1.0)
Bear pressure exceeds 45% (+1.0)
Close and high are both lower than previous bar (+0.75)
Price crossed below the anchor this bar (+1.25)
Maximum possible damage score per bar: 7.25. When the score exceeds the damage threshold (default: 4.0), the trend is flagged as damaged.
Damage Response
When damage is detected, the engine modifies the active side's evidence buckets:
Continuation is reduced by (0.25 × damageDecayMult) — default removes ~44%
Impulse is multiplied by damageImpulseCut — default retains 88%
Structure is multiplied by 0.92
Opposing exhaustion receives +1.5
Opposing impulse receives +1.0
This creates a natural degradation cycle: damage weakens the active trend's evidence while strengthening the opposing side's, making a transition more likely without forcing it.
Integrity Score
The library computes a continuous structural integrity measure from 0.0 (broken) to 1.0 (fully intact), derived from four components:
Erosion component (max −0.30): How far current confidence has fallen from its peak
Damage component (max −0.30): Current damage score relative to threshold
Opposing pressure (max −0.20): Counter-trend pressure magnitude
Transition duration (max −0.15): How long the engine has been in transition state
External evidence modifiers can also adjust integrity by ±0.1.
Directional Permissions
Rather than a simple pass/fail gate, the library outputs four permission values:
allowLong (bool) : Structural permission to take long positions
allowShort (bool): Structural permission to take short positions
preferLong (float, 0−1): Strength of structural preference for longs
preferShort (float, 0−1): Strength of structural preference for shorts
In Bull state: longs are allowed, shorts are blocked unless the trend is damaged (allowing counter-trend fades). preferLong equals the confidence strength. In Bear state: the inverse. In Transition: both sides are allowed, preference leans toward whichever side has more evidence.
External Evidence Sockets
The library accepts additive evidence injection from external systems through the ExternalEvidence type. External evidence is applied after internal bucket computation but before state transitions, meaning it can influence confidence but cannot directly set state.
ev = rcm.ExternalEvidence.new(bullEvidence=3.0, source="dreamer")
st := rcm.inject(st, ev)
External evidence is reset to zero after each update() call. This prevents stale external data from persisting.
Modulation Outputs
The library provides purpose-built modulation functions for different indicator types:
Band Modulation (get_band_mod): Returns a float multiplier for band/envelope width. Bands tighten during high-confidence directional states and widen when damage is detected. Used by Supertrend, Bollinger Band, and PSAR-type indicators.
Score Modulation (get_score_mod): Returns an additive modifier for directional scores. When a score's direction aligns with the RCM state, it receives a confidence-proportional boost. When it opposes, it receives a penalty. Used by signal-scoring systems.
Signal Gate (get_gate): Returns a boolean indicating whether signals should be permitted. When transition blocking is enabled, all signals are suppressed during Transition state.
Full Package (get_modulation): Returns all outputs in a single RCMModulation struct including band mod, score mod, gate, permissions, integrity, state color, and regime label.
Configuration
The library ships with three preset configurations:
default_config(): Balanced settings suitable for 15m−1H timeframes
scalp_config(): Faster decay (0.75), lower thresholds, higher impulse weight — optimized for 1m−5m
swing_config(): Slower decay (0.88), higher thresholds, higher structure weight — optimized for 4H−Daily
All 16 configuration parameters can also be set individually through the RCMConfig constructor.
Developer Integration Guide
Step 1: Import and Initialize
import DskyzInvestments/DafeRCMLib/1 as rcm
var rcm.RCMState st = rcm.RCMState.new()
var rcm.RCMConfig cfg = rcm.default_config()
Both objects must be declared with var for state persistence across bars.
Step 2: Update Every Bar
st := rcm.update(st, cfg)
Call update() exactly once per bar. It handles all evidence detection, decay, confidence computation, damage detection, state transitions, substate classification, and integrity scoring.
Step 3: Query Modulation Outputs
For band-based indicators (Supertrend, BB, PSAR):
band := band * rcm.get_band_mod(st, 0.45, 1.10)
For score-based systems (signal scoring, ML models):
fusedScore = rawScore + rcm.get_score_mod(st, rawScore, 0.25)
For signal gating:
buySignal := buySignal and rcm.get_gate(st, true)
For directional permissions:
rcm.RCMPermissions perms = rcm.get_permissions(st)
if perms.allowLong and perms.preferLong > 0.3
// High structural preference for longs
Step 4: Optional — Inject External Evidence
if myDreamerScore > 2.0
ev = rcm.ExternalEvidence.new(bullEvidence=2.0, source="dreamer")
st := rcm.inject(st, ev)
// inject() must be called BEFORE update()
Step 5: Optional — Use Dashboard Helpers
rcm.conf_bar(st.bullConf, 130, 8) // Returns "████░░░░"
rcm.state_text(st) // Returns "▲ BULL"
rcm.damage_text(st) // Returns "Intact"
rcm.integrity_text(st) // Returns "87.3%"
rcm.state_color(st, bullCol, bearCol, transCol)
Step 6: Optional — Narrative Text
= rcm.narrative_regime(st, bullCol, bearCol, transCol, dimCol)
= rcm.narrative_kinetics(st, accentCol, dimCol)
= rcm.narrative_structure(st, bullCol, bearCol, transCol, dimCol)
What This Library Does Not Do
It does not generate buy/sell signals
It does not draw on the chart
It does not use request.security or access external timeframes
It does not use request.footprint (consumers can inject footprint-derived evidence through the external socket)
It does not persist data beyond the current chart's bar history
It does not adapt its own parameters automatically
The library computes structural context. What the consuming indicator does with that context is entirely the developer's decision.
Companion Demo
The DafeRCMLibDEMO indicator demonstrates every function and output of this library
using a simple EMA crossover system as the base indicator. It includes:
Modulated ATR bands showing get_band_mod() in action
Trade signals gated by get_permissions() and get_gate()
State shift and damage markers
Substate classification labels
Evidence bucket subplots for all 10 buckets
Confidence, integrity, and modulation output subplots
Full quantitative dashboard and narrative panel
— Dskyz, Trade with insight. Trade with anticipation. مكتبة

Vantage_News_HistoricalVantage News is a Pine Script library that provides pre-market economic event filtering defaults intended for strategies that trade on YM futures. It determines a default for whether trading should be blocked, delayed, or allowed on any given day. This Historical file contains prior years.
Core Concept
News events are pre-compiled into Pine Script data libraries organized by half-year (LO1_News2025H1, LO1_News2025H2, etc.), updated weekly on Sundays. There are no API calls — events are baked into arrays of dates, times, type IDs, and severities.
Severity System
Can be configured to define or override three default severity tiers:
- Sev 3 (CPI, NFP, FOMC) — defaults to blocks the entire day or delays, depending on policy
- Sev 2 (ISM PMI, claims) — defaults to delay trading until the event time + a configurable post-delay window
- Sev 1 (secondary indicators) — defaults to no delays
Blocking vs Delaying
- Block: No trading for the full session. WillTradeToday() returns false.
- Delay: Trading allowed after eventTime + delayMinutes. IsDelayed(currentTimeMs) returns true until the release time passes.
Provides a per-event-type policy mechanism so overrides can force any event to block, delay, or be ignored regardless of its base severity.
Next Trading Window Calculation
FindNextTradingWindow() scans forward up to 14 days, skipping weekends and blocked days based on the provided configuration. If the next tradeable day has a delay, it returns the delayed start time — so an info panel can show e.g. "Mon 7:35 AM" to indicate the next trading opening
Exception Mappings
Each half-year library can ship per-event-type overrides (different severity, custom delay minutes, tags). When the applyLibExceptionMappings configuration is enabled, these override the base severity — allowing the data to carry date-specific adjustments.
Special Handling
CME early close days are encoded as a special event type. CheckCmeEarlyClose() returns a halt timestamp so a strategy can truncate the session.
Caching
Evaluation is lazy and memoized by date string — EvaluateForDate() only recomputes when the date changes. The event cache is built once at initialization via a day index for fast date lookups. مكتبة

fsl_futuresLibrary "fsl_futures"
Futures helpers for TradingView.
Provides month code constants and utilities for determining allowed / major
contract months per futures root (e.g., SI uses HKNUZ).
allMonthCodes()
Returns the standard CME-style futures month codes as an array.
Returns: array of month codes in order: F,G,H,J,K,M,N,Q,U,V,X,Z
allMonthCodesStr()
Returns all month codes as a single string for quick membership checks.
Returns: string "FGHJKMNQUVXZ"
majorMonthsByRoot(product_root)
Returns the major month-code subset for a given futures root.
If the root is not mapped, defaults to all months.
Parameters:
product_root (string) : Futures root symbol, e.g. "SI", "ES", "CL"
Returns: string of allowed month codes (e.g., "HKNUZ" for SI), otherwise "FGHJKMNQUVXZ"
allowedMonthsByRoot(product_root)
Returns the allowed month-code subset for a given futures root.
If the root is not mapped, defaults to all months.
Parameters:
product_root (string) : Futures root symbol, e.g. "SI", "ES", "CL"
Returns: string of allowed month codes (e.g., "HKNUZ" for SI), otherwise "FGHJKMNQUVXZ"
isMajorMonth(product_root, month_code)
Checks whether a month code is major for a given futures root.
Parameters:
product_root (string) : Futures root symbol, e.g. "SI"
month_code (string) : Single-letter month code, e.g. "H"
Returns: bool true if month_code is included in the major set for that root
isAllowedMonth(product_root, month_code)
Checks whether a month code is allowed for a given futures root.
Parameters:
product_root (string) : Futures root symbol, e.g. "SI"
month_code (string) : Single-letter month code, e.g. "H"
Returns: bool true if month_code is included in the allowed set for that root مكتبة

مكتبة

SimpleTableA library for when you just want to get a table up with the least hassle.
The function `f_drawTableFromColumns()`, is intended to be the simplest possible way to draw a table with the least code in the calling script. Just pass in between one and ten arrays that contain the strings you want to show. Each string array represents one column. That's it. You get a table back.
If you want to style the table you can optionally pass colours, size, and whether the table has a header row that should be displayed differently.
An example usage section demonstrates creating a three-column table.
The function automatically sizes the table based on the number of non-na arrays and the maximum column length.
Optional styling parameters cover table position, text size, text alignment, text colour, cell background, header background, header text, and border width. If you don't supply any of these arguments, the table uses some sensible default values.
The table is created and updated on the last bar only, with caching to avoid unnecessary redraws.
Column shrink detection clears the table only when required, preventing stale cell content.
This is not a full-fledged table management library; there are already lots of those published. It is (I believe and hope) the easiest library to use. For example, you don't need to supply a matrix, or a user-defined type full of settings. The library wraps the input arrays into a map, and uses a user-defined type, but internally, so you don't need to worry about it. Just supply one or more arrays with some text.
f_drawTableFromColumnArrays(_a_col1, _a_col2, _a_col3, _a_col4, _a_col5, _a_col6, _a_col7, _a_col8, _a_col9, _a_col10, _position, _textSize, _textAlign, _textColor, _cellBgColor, _headerBgColor, _headerTextColor, _hasHeaderRow, _borderWidth)
Renders a table using up to ten string arrays. The table size is derived from the number of non-na arrays and the maximum length across the supplied arrays.
Parameters:
_a_col1 (array) : (array) Column 1 values. Supply na to omit.
_a_col2 (array) : (array) Column 2 values. Supply na to omit.
_a_col3 (array) : (array) Column 3 values. Supply na to omit.
_a_col4 (array) : (array) Column 4 values. Supply na to omit.
_a_col5 (array) : (array) Column 5 values. Supply na to omit.
_a_col6 (array) : (array) Column 6 values. Supply na to omit.
_a_col7 (array) : (array) Column 7 values. Supply na to omit.
_a_col8 (array) : (array) Column 8 values. Supply na to omit.
_a_col9 (array) : (array) Column 9 values. Supply na to omit.
_a_col10 (array) : (array) Column 10 values. Supply na to omit.
_position (string) : (TablePosition) Table position on the chart. Default is top right.
_textSize (string) : (TableTextSize) Text size for all cells. Default is normal.
_textAlign (string) : (TableTextAlign) Horizontal alignment for all cells. Default is left.
_textColor (color) : (color) Text colour for all cells. Default is chart foreground color.
_cellBgColor (color) : (color) Background colour for all cells. Uses a default if na. Default is gray 90%.
_headerBgColor (color) : (color) Background colour for the header row. Uses a default if na. Default is gray 75%.
_headerTextColor (color) : (color) Text colour for the header row. Uses a default if na.
_hasHeaderRow (bool) : (bool) If true, row 0 is treated as a header. Default is true.
_borderWidth (int) : (int) Table border width. Must be non-negative. Default is 1.
Returns: The table object, so the caller can store the table ID if required. مكتبة

مكتبة

مكتبة

AssetCorrelationUtils
- Open source Library Used for Indicators that utilize correlation between assets for divergence calculations. It has no drawing elements.
ASSET CORRELATION UTILS
PineScript library for automatic detection of correlated asset pairs and triads for multi-asset analysis.
WHAT IT DOES
This library automatically identifies correlated assets based on the current chart symbol. It returns properly configured asset pairings for use in SMT divergence detection, inter-market analysis, and multi-asset comparison tools.
HOW IT WORKS
The library matches your chart symbol against known correlation groups:
Index Futures: NQ/ES/YM/RTY triads (including micros)
Metals: Gold/Silver/Copper triads (futures and CFD)
Forex: EUR/GBP/DXY and USD/JPY/CHF triads
Energy: Crude/Gasoline/Heating Oil triads
Treasury: ZB/ZF/ZN bond triads
Crypto: BTC/ETH/TOTAL3 and major altcoin pairings
Inversion flags are automatically computed for assets that move inversely (e.g., DXY vs EUR pairs).
HOW TO USE
import fstarcapital/AssetCorrelationUtils/1 as acu
// Simple: auto-detect from current chart
config = acu.resolveCurrentChart()
// Access resolved assets
primary = config.primary
secondary = config.secondary
tertiary = config.tertiary
EXPORTED FUNCTIONS
resolveCurrentChart(): One-call auto-detection using chart syminfo
resolveAssets(): Full detection with custom parameters
resolveTriad() / resolveDyad(): Manual resolution with inversion logic
detect*() functions: Category-specific detectors for custom workflows
TYPES
AssetPairing: Core structure for primary/secondary/tertiary tickers with inversion flags
AssetConfig: Full resolution result with detection status and asset category
DISCLAIMER
This library is a utility for building multi-asset indicators. Asset correlations are not guaranteed and may change over time. Always validate pairings for your specific trading context.
Full Default Function @type and @field descriptions below.
Library "AssetCorrelationUtils"
detectIndicesFutures(ticker)
Detects Index Futures (NQ/ES/YM/RTY + micro variants)
Parameters:
ticker (string) : The ticker string to check (typically syminfo.ticker)
Returns: AssetPairing with secondary and tertiary assets configured
detectMetalsFutures(ticker)
Detects Metal Futures (GC/SI/HG + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectForexFutures(ticker)
Detects Forex Futures (6E/6B + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectEnergyFutures(ticker)
Detects Energy Futures (CL/RB/HO + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectTreasuryFutures(ticker)
Detects Treasury Futures (ZB/ZF/ZN)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectCryptoFutures(ticker)
Detects CME Crypto Futures (BTC/ETH + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectCADFutures(ticker)
Detects CAD Forex Futures (6C + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectForexCFD(ticker, tickerId)
Detects Forex CFD pairs (EUR/GBP/DXY, USD/JPY/CHF triads)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID (syminfo.tickerid) for primary asset
Returns: AssetPairing with secondary and tertiary assets configured
detectCrypto(ticker, tickerId)
Detects major Crypto assets (BTC, ETH, SOL, XRP, alts)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with secondary and tertiary assets configured
detectMetalsCFD(ticker, tickerId)
Detects Metals CFD (XAU/XAG/Copper)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with secondary and tertiary assets configured
detectIndicesCFD(ticker, tickerId)
Detects Indices CFD (NAS100/SP500/DJ30)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with secondary and tertiary assets configured
detectEUStocks(ticker, tickerId)
Detects EU Stock Indices (GER40/EU50) - Dyad only
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with secondary asset configured (tertiary empty for dyad)
getDefaultFallback(tickerId)
Returns default fallback assets (chart ticker only, no correlation)
Parameters:
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with chart ticker as primary, empty secondary/tertiary (no correlation)
applySessionModifierWithBackadjust(tickerStr, sessionType)
Applies futures session modifier to ticker WITH back adjustment
Parameters:
tickerStr (string) : The ticker to modify
sessionType (string) : The session type (syminfo.session)
Returns: Modified ticker string with session and backadjustment.on applied
applySessionModifierNoBackadjust(tickerStr, sessionType)
Applies futures session modifier to ticker WITHOUT back adjustment
Parameters:
tickerStr (string) : The ticker to modify
sessionType (string) : The session type (syminfo.session)
Returns: Modified ticker string with session and backadjustment.off applied
isTriadMode(pairing)
Checks if a pairing represents a valid triad (3 assets)
Parameters:
pairing (AssetPairing) : The AssetPairing to check
Returns: True if tertiary is non-empty (triad mode), false for dyad
getAssetTicker(tickerId)
Extracts clean ticker string from full ticker ID
Parameters:
tickerId (string) : The full ticker ID (e.g., "BITGET:BTCUSDT.P")
Returns: Clean ticker string (e.g., "BTCUSDT.P")
resolveTriad(chartTickerId, pairing)
Resolves triad asset assignments with proper inversion flags
Parameters:
chartTickerId (string) : The current chart's ticker ID (syminfo.tickerid)
pairing (AssetPairing) : The detected AssetPairing
Returns: Tuple
resolveDyad(chartTickerId, pairing)
Resolves dyad asset assignment with proper inversion flag
Parameters:
chartTickerId (string) : The current chart's ticker ID
pairing (AssetPairing) : The detected AssetPairing (dyad: tertiary is empty)
Returns: Tuple
resolveAssets(ticker, tickerId, assetType, sessionType, useBackadjust)
Main auto-detection entry point. Detects asset category and returns fully resolved config.
Parameters:
ticker (string) : The ticker string to check (typically syminfo.ticker)
tickerId (string) : The full ticker ID (typically syminfo.tickerid)
assetType (string) : The asset type (typically syminfo.type)
sessionType (string) : The session type for futures (typically syminfo.session)
useBackadjust (bool) : Whether to apply back adjustment for futures session alignment
Returns: AssetConfig with fully resolved assets, inversion flags, and detection status
resolveCurrentChart()
Simplified auto-detection using current chart's syminfo values
Returns: AssetConfig with fully resolved assets, inversion flags, and detection status
AssetPairing
Core asset pairing structure for triad/dyad configurations
Fields:
primary (series string) : The primary (chart) asset ticker ID
secondary (series string) : The secondary correlated asset ticker ID
tertiary (series string) : The tertiary correlated asset ticker ID (empty for dyad)
invertSecondary (series bool) : Whether secondary asset should be inverted for divergence calc
invertTertiary (series bool) : Whether tertiary asset should be inverted for divergence calc
AssetConfig
Full asset resolution result with mode detection and computed values
Fields:
detected (series bool) : Whether auto-detection succeeded
isTriadMode (series bool) : True if triad (3 assets), false if dyad (2 assets)
primary (series string) : The resolved primary asset ticker ID
secondary (series string) : The resolved secondary asset ticker ID
tertiary (series string) : The resolved tertiary asset ticker ID (empty for dyad)
invertSecondary (series bool) : Computed inversion flag for secondary asset
invertTertiary (series bool) : Computed inversion flag for tertiary asset
assetCategory (series string) : String describing the detected asset category مكتبة
