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通りの組み合わせループを構築し、本ライブラリの評価を通過させることで、最もスコアの高い役を正確に抽出することが推奨されます。
Library

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

Library

Library

Library

Library

Library

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. Library

Library

ZT_Dashboard_LibCompanion library for the Alpha Flow Zone Trader (AFZT) invite-only indicator. Provides the table-rendering helpers for the AFZT on-chart dashboard — splits the rendering code out of Core so the indicator stays under PulseWire's per-script token limit.
Exports:
• renderFlow(table, ...) — fills the FLOW tab: grade, zone, entry/stop/TPs, unrealized R, optional stats, optional Ichimoku, optional local rec, optional TV-Pack row.
• renderOps(table, ...) — fills the OPS tab: engine state, vol regime, zones, tick health, signal status, last trade.
All exports are pure table.cell() writers — they receive a pre-created table object and color palette from the Core, write rows into it, and return. No plots, no alerts, no series state. Library

ZT_Telemetry_LibCompanion library for the Alpha Flow Zone Trader (AFZT) invite-only indicator. Provides telemetry-encoding helpers used by the AFZT Core script when emitting webhook payloads.
Exports:
• tfCode(tfStr) — maps a PulseWire timeframe string ("1", "5", "15", "60", "D", etc.) to a stable integer code.
• buildMasks_v22(scoreNorm, atrMult, entryAtr, riskTicks, zoneWidthTicks, hasCisd) — returns bitmask triples encoding which stop/BE/TP policies are eligible for the current setup.
• zoneCodeDemand / zoneCodeSupply — maps a zone name + auto-zone index to a stable integer code (1100+ for auto-detected, 101-103 / 201-203 for manual DZ/SZ slots).
All exports are pure functions — no plots, no alerts, no series state. Library

Library

ZT_Webhook_LibCompanion library for the Alpha Flow Zone Trader (AFZT) invite-only indicator. Provides the AFZT webhook payload encoders — formats the AFZT|... pipe-delimited strings the Core script sends in its alert() messages on entry, breakeven, close, and S-event signals.
Exports:
• encode_entry_v1038 — entry-event payload (zone code, base type, confidence, touch count, zone age, entry & stop prices).
• encode_be_v1038 — breakeven-event payload.
• encode_close_v1038 / encode_close_v1041 / encode_close_v1043_v2 — close-event payloads with progressively richer telemetry (R-multiple, MFE/MAE, zone metadata, stop/BE/TP masks, ATR/risk/zone-width).
• encode_signal_v1 / encode_signal_v2 — S-Event signal payload with filter masks (v2 adds 4 upstream ML features: sweep flag, trend bias, HTF direction, liquidity distance).
All exports are pure string-formatting functions — no plots, no alerts, no state mutation. Library

Library

Library

Library

ValidationUtilitiesValidationUtilities Library
🌸 Part of GoemonYae Trading System (GYTS) 🌸
🌸 --------- 1. INTRODUCTION --------- 🌸
💮 What Does This Library Contain?
ValidationUtilities is a centralised validation framework for Pine Script. It replaces scattered, ad-hoc input checks with a single, structured validation pass that catches every misconfiguration before a script begins operating.
The library spans the full validation workflow: framework lifecycle, configuration checks, position sizing guards, and signal completeness verification.
💮 Key Categories
The library contains:
Core Framework : the ValidationFramework UDT and its lifecycle methods (init, collect, report)
Standalone Utilities : bounded-buffer push and division-by-zero guard
Configuration Validation : range, ordering, exclusivity, lookback, source, and timeframe checks
Position Sizing & Risk : order size constraints, progressive risk alerts, allocation distribution, and Martingale safety
Signal & Timing : signal source completeness and cooldown gating
🌸 --------- 2. ADDED VALUE --------- 🌸
💮 Consistent, Readable Error Messages
Every error and warning follows the same Message format. Users see clear, categorised feedback instead of cryptic runtime error strings. A single validation pass surfaces all issues at once, so there is no need to fix one error only to hit the next on re-run.
💮 Single Import, Full Coverage
One import replaces dozens of inline validation blocks. Range checks, allocation constraints, timeframe guards, and position sizing validations are all available immediately.
💮 Errors and Warnings, Separated
Hard/soft boundary separation lets developers enforce critical constraints (errors halt execution via runtime.error() ) whilst still surfacing non-critical suggestions (warnings display as chart labels). The framework handles formatting, counting, and display.
💮 Proven in Production
ValidationUtilities underpins the validation layer of a strategy with an extensive configuration surface (12+ validated parameter groups). The methods have been refined against real misconfiguration scenarios including floating-point allocation sums, multiplier escalation, and unconnected data streams.
🌸 --------- 3. CORE FRAMEWORK --------- 🌸
💮 ValidationFramework (UDT)
The central data structure that collects validation results. It holds two string arrays, errors (critical, halt execution) and warnings (advisory, continue execution), alongside convenience flags has_errors and has_warnings .
Declare once with var , then call init() to reset state before each validation cycle:
var framework = vu.ValidationFramework.new()
framework.init()
💮 init()
Resets the framework: clears both arrays and resets flags to false . Call at the start of each validation cycle.
💮 add_error() and add_warning()
Building blocks for custom validation beyond the built-in methods. Both accept a category and message , formatting them as Message . Use add_error() for constraints that must halt execution and add_warning() for advisory messages.
framework.add_error("Position Sizing", "Order exceeds account equity.")
framework.add_warning("Risk", "Position represents 35% of equity — monitor carefully.")
💮 trigger_errors()
Fires runtime.error() with the first collected error and a count of any remaining. Always call after all validations have run so every misconfiguration is detected in a single pass.
💮 display_warnings()
Renders warnings as orange chart labels (below bar by default). Displays the first warning with a count of additional warnings, then clears state to prevent repetition. Accepts an optional yloc_arg for label placement.
↑ Runtime error dialog showing a categorised validation error with count of additional issues
↑ Warning labels displayed on the chart via display_warnings()
🌸 --------- 4. STANDALONE UTILITIES --------- 🌸
These functions are independent of the ValidationFramework and can be used anywhere.
💮 push_limited()
A FIFO bounded-buffer push: appends a value and evicts the oldest entry when the array exceeds a specified limit. Available for both float and int arrays.
vu.push_limited(price_buffer, close, 50) // Keeps the last 50 closes
💮 safe_denominator()
Returns math.max(value, floor) to guard against division by zero. Default floor is 1e-9 .
ratio = numerator / vu.safe_denominator(denominator)
🌸 --------- 5. CONFIGURATION VALIDATION --------- 🌸
These methods validate user-facing settings before a script begins operating. Each accepts the framework as self and a category string for error grouping. Refer to the source code for full parameter details.
💮 validate_range()
Checks that a value falls within hard bounds (error if violated) and optional soft bounds (warning if outside the optimal range). Supports a value_unit label for message clarity. Returns true if within hard bounds.
💮 validate_exclusive_selection()
Ensures exactly one boolean flag is active among a set of mutually exclusive options. Produces an error listing which options were found active, or that none were selected.
💮 validate_ascending_order()
Verifies that an array of values is in ascending order. Supports strict (default) or non-strict comparison. Skips na values.
💮 validate_minimum_lookback()
Checks that a lookback parameter meets a caller-derived minimum. Accepts an optional fix_hint for the error message. Returns true if met.
💮 validate_source_connected()
Detects when an input.source() has no external indicator connected (it silently defaults to close ). Uses a 2-bar close heuristic. Accepts an is_enabled flag to skip the check when the relevant feature is disabled. Returns true if the source appears connected.
💮 validate_higher_timeframe()
Validates that a user-selected timeframe is sufficiently higher than the chart timeframe. Returns the integer multiplier, useful for scaling lookback periods. Produces an error if below min_multiplier (default 1.0).
🌸 --------- 6. POSITION SIZING & RISK --------- 🌸
These methods guard against position sizing errors and excessive risk exposure. See the source code for parameter details and default thresholds.
💮 validate_order_size_constraints()
Checks a proposed order against account equity and position size limits. Errors if the order exceeds equity or a hard cap; warns if the position exceeds a configurable percentage of equity. Returns true if no errors were added.
💮 validate_multiplied_sizing_risk()
Progressive risk alerting for scripts that scale position sizes with multipliers (Martingale, Anti-Martingale, or any multiplicative sizing). Applies three escalating thresholds:
Warning (default 25%): elevated risk
Error (default 50%): high risk
Critical (default 75%): exceeds safe limits
Also warns when the multiplier itself exceeds a configurable threshold. Returns true if no errors were added.
💮 validate_martingale_settings()
Validates Martingale/Anti-Martingale parameter consistency: multiplier range, streak bounds, and maximum possible escalation. Warns when maximum escalation exceeds 100×.
💮 validate_allocations()
Validates percentage distributions (0–1 scale) for take-profit levels, portfolio weights, or any system that divides a whole into parts. Checks individual allocations and total against 1.0 with floating-point tolerance. Supports both mandatory full allocation and partial allocation.
🌸 --------- 7. SIGNAL & TIMING --------- 🌸
These methods verify signal completeness and enforce cooldown periods. See the source code for parameter details.
💮 validate_signal_configuration()
Completeness check for signal sources. Validates that an enabled signal has a connected primary data stream, a secondary stream (if required), at least one signal mapping, and activity in at least one market regime (when regime filtering is enabled).
💮 validate_timing_cooldown()
Gating check for entry timing. Verifies that enough bars have elapsed since the last relevant event and that a valid entry signal is present. Both conditions produce warnings rather than errors.
🌸 --------- 8. USAGE EXAMPLE --------- 🌸
A typical validation lifecycle: import, initialise, run validations, then trigger errors and display warnings.
import GoemonYae/ValidationUtilities/1 as vu
// Declare once, reset each bar
var framework = vu.ValidationFramework.new()
framework.init()
// Configuration validation
framework.validate_range("Config", "ATR Lookback", i_atr_lookback, 1, 500, 10, 50, "bars")
framework.validate_exclusive_selection("Distance", "TP Mode",
array.from(i_use_pct, i_use_atr, i_use_hl),
array.from("Percentage", "ATR", "High/Low"), "method")
// Allocation validation
framework.validate_allocations("TP Settings", "Take Profit",
array.from(i_tp1_alloc, i_tp2_alloc, i_tp3_alloc),
array.from("TP1", "TP2", "TP3"), true)
// Position sizing guard
framework.validate_order_size_constraints("Sizing",
order_size, close, strategy.equity, max_pos, 50.0)
// Report results
framework.trigger_errors() // Halts if any errors found
framework.display_warnings() // Shows warnings on chart
When all inputs are valid, trigger_errors() does nothing and execution continues; display_warnings() draws no labels. A correctly configured script simply runs with a clean chart.
🌸 --------- 9. PRACTICAL USAGE NOTES --------- 🌸
💮 Errors vs Warnings
Use add_error() for constraints that make the script unsafe or logically broken (missing data streams, impossible parameter combinations, equity-exceeding orders). Use add_warning() for suboptimal but non-dangerous configurations (values outside the recommended range, elevated risk percentages). Errors halt execution; warnings inform via chart labels.
💮 Single-Pass Collection
Always run all validations before calling trigger_errors() . The framework collects every error in a single pass so the user sees the total count of issues.
💮 Integration with Other GYTS Libraries
ValidationUtilities complements the GYTS library ecosystem:
FiltersToolkit : smoothing and signal processing
VolatilityToolkit : volatility estimation and regime detection
ColourUtilities : dynamic colour mapping
MathTransform : mathematical transformations and normalisation
Each library handles its own domain; ValidationUtilities handles the validation layer that sits above them.
💮 Limitations
A few constraints to keep in mind:
The validate_source_connected() heuristic (2-bar close comparison) can produce false positives if a source genuinely tracks price closely. It is a best-effort detection, not a guarantee.
Pine Script libraries cannot import other libraries. So ValidationUtilities is designed for indicators and strategies.
The framework validates configuration state, not runtime state. It catches misconfigurations at the input level; it does not monitor runtime behaviour.
Library

Library

Library

Library

Library
