PessimisticSimLibrary "PessimisticSim"
Broker-agnostic pessimistic fill simulator. Runs a shadow account
alongside any indicator or strategy, filling every signal at the
worst plausible price (half-spread + slippage + a fraction of the
adverse bar excursion) so you can see whether an edge survives
real-world friction.
Instrument-agnostic: set pointValue for futures, pick a commission
model, pick a sizing model, pick a fill model. Defaults reproduce
spot crypto / stock behaviour (multiplier 1, percent commission,
risk-based sizing, next-bar-open fills).
newState(cfg)
Creates a fresh shadow account seeded from `cfg`.
Parameters:
cfg (SimConfig) : Configuration object.
Returns: A SimState ready to pass to step().
commissionFor(cfg, price, qty)
Commission for one fill under the configured model.
Parameters:
cfg (SimConfig) : Configuration object.
price (float) : Fill price.
qty (float) : Units filled.
Returns: Commission in account currency. Zero when qty <= 0.
qtyFor(cfg, equity, stopDist, price, openRisk)
Position size under the configured sizing model, with an optional
leverage cap and quantity-step rounding. Host scripts should call
this for their live orders too, so both engines size identically.
Parameters:
cfg (SimConfig) : Configuration object.
equity (float) : Account equity to size against.
stopDist (float) : Distance from entry to stop, in PRICE units. Only used by
SizeMode.riskStop; pass 0 in the other modes.
price (float) : Fill price, used by the leverage cap and equityPct sizing.
openRisk (float) : Risk already committed by open positions, in CURRENCY
(i.e. qty * stopDist * pointValue). riskStop only.
Returns: Units to trade, rounded down to qtyStep. Zero when unsizable.
buyFillPrice(cfg, refPrice, advHigh)
Worst-case buy fill: reference price + half-spread + slippage +
a slice of the adverse upward excursion.
Parameters:
cfg (SimConfig) : Configuration object.
refPrice (float) : Reference price (bar open, or close under signalClose).
advHigh (float) : Adverse extreme to price against. Pass the bar high under
nextOpen; pass refPrice under signalClose to disable it.
Returns: The pessimistic buy price.
sellFillPrice(cfg, refPrice, advLow)
Worst-case sell fill: reference price - half-spread - slippage -
a slice of the adverse downward excursion.
Parameters:
cfg (SimConfig) : Configuration object.
refPrice (float) : Reference price (bar open, or close under signalClose).
advLow (float) : Adverse extreme to price against. Pass the bar low under
nextOpen; pass refPrice under signalClose to disable it.
Returns: The pessimistic sell price.
method closeAt(s, cfg, exitPrice)
Flattens the position at `exitPrice`, books PnL and updates stats.
No-op when flat.
Namespace types: SimState
Parameters:
s (SimState) : Shadow account state.
cfg (SimConfig) : Configuration object.
exitPrice (float) : Fill price for the exit.
Returns: Void.
method openAt(s, cfg, dir, fillPrice, stopDist)
Opens a position, or adds a unit while `units < cfg.maxUnits`.
Add-ons blend into a volume-weighted average entry and are sized
against the risk already committed.
Namespace types: SimState
Parameters:
s (SimState) : Shadow account state.
cfg (SimConfig) : Configuration object.
dir (int) : 1 to go long, -1 to go short.
fillPrice (float) : Pessimistic fill price.
stopDist (float) : Distance from entry to stop, in price units. Pass 0 under
fixedUnits / equityPct sizing.
Returns: Void.
method mark(s, cfg, price)
Marks the account to market and updates equity peak and drawdown.
Namespace types: SimState
Parameters:
s (SimState) : Shadow account state.
cfg (SimConfig) : Configuration object.
price (float) : Current mark price, normally close.
Returns: Void.
method stepAt(s, cfg, longIn, longOut, shortIn, shortOut, buyPrice, sellPrice, markPrice, stopDistLong, stopDistShort)
General escape hatch: processes one bar against explicit fill prices.
Use when your execution model is neither FillMode case — limit fills,
stop fills, VWAP, session opens, anything.
Order is exits, then reversals, then entries, then mark-to-market.
Namespace types: SimState
Parameters:
s (SimState) : Shadow account state.
cfg (SimConfig) : Configuration object.
longIn (bool) : Long entry signal.
longOut (bool) : Long exit signal.
shortIn (bool) : Short entry signal.
shortOut (bool) : Short exit signal.
buyPrice (float) : Price paid when buying.
sellPrice (float) : Price received when selling.
markPrice (float) : Price for the mark-to-market update.
stopDistLong (float) : Stop distance for longs, price units.
stopDistShort (float) : Stop distance for shorts, price units.
Returns: Void.
method step(s, cfg, longIn, longOut, shortIn, shortOut, o, h, l, c, stopDistLong, stopDistShort)
Processes one bar using the configured FillMode. Call once per
confirmed bar.
FillMode.nextOpen — pass PRIOR-bar signals (sig ); this bar's
open is the fill, its high/low the excursion.
FillMode.signalClose — pass CURRENT-bar signals; the close is the
fill and advFrac is inert.
Getting this pairing wrong produces plausible-but-wrong results, so
check it first when a comparison looks strange.
Namespace types: SimState
Parameters:
s (SimState) : Shadow account state.
cfg (SimConfig) : Configuration object.
longIn (bool) : Long entry signal, shifted per FillMode.
longOut (bool) : Long exit signal, shifted per FillMode.
shortIn (bool) : Short entry signal, shifted per FillMode.
shortOut (bool) : Short exit signal, shifted per FillMode.
o (float) : Bar open.
h (float) : Bar high.
l (float) : Bar low.
c (float) : Bar close.
stopDistLong (float) : Stop distance for longs, price units.
stopDistShort (float) : Stop distance for shorts, price units.
Returns: Void.
pf(gp, gl)
Profit factor with safe handling of an empty loss column.
Parameters:
gp (float) : Gross profit.
gl (float) : Gross loss, as a positive number.
Returns: gp/gl, 999 when there are no losses, 0 when there is nothing.
method netProfit(s, cfg)
Net profit of the shadow account, in currency.
Namespace types: SimState
Parameters:
s (SimState) : Shadow account state.
cfg (SimConfig) : Configuration object.
Returns: equity - initCap.
method profitFactor(s)
Profit factor of the shadow account.
Namespace types: SimState
Parameters:
s (SimState) : Shadow account state.
Returns: Profit factor.
method winRatePct(s)
Win rate of the shadow account, percent.
Namespace types: SimState
Parameters:
s (SimState) : Shadow account state.
Returns: Percentage of closed trades that were profitable.
method avgTradePct(s)
Average per-trade return, percent of equity-before-trade.
Namespace types: SimState
Parameters:
s (SimState) : Shadow account state.
Returns: Mean trade return, percent.
method rtCostPct(cfg)
Round-trip friction as a percent of notional. Only meaningful under
CommMode.pct — flat commissions do not scale with notional, so this
returns na under the other models. Compare against avgTradePct():
if the average trade does not clear this, the edge is smaller than
the cost of trading it.
Namespace types: SimConfig
Parameters:
cfg (SimConfig) : Configuration object.
Returns: Round-trip cost, percent, or na under flat commission models.
rowLabels()
Row labels matching the order of rowValues(). Lay out an audit table
in the host script from these, so strategy.* calls stay in the host.
Returns: Array of ten label strings.
method rowValues(s, cfg)
Preformatted metric strings for the shadow account, aligned to rowLabels().
Namespace types: SimState
Parameters:
s (SimState) : Shadow account state.
cfg (SimConfig) : Configuration object.
Returns: Array of ten value strings.
method verdict(s, cfg, strategyPF, strategyNet)
Compares a host strategy's headline numbers against the shadow
account and returns a verdict string.
Namespace types: SimState
Parameters:
s (SimState) : Shadow account state.
cfg (SimConfig) : Configuration object.
strategyPF (float) : Host strategy profit factor.
strategyNet (float) : Host strategy net profit.
Returns: "DIVERGED — investigate", "SURVIVES", or "NO EDGE".
SimConfig
Instrument, cost, sizing and execution assumptions for the shadow account.
Fields:
spreadPct (series float) : Assumed FULL spread, percent. Half is charged per side.
slipPct (series float) : Extra slippage percent per side.
advFrac (series float) : Fraction of the fill bar's adverse excursion added to the fill.
commMode (series CommMode) : Commission model.
commPct (series float) : Commission percent of notional, per side.
commPerUnit (series float) : Flat commission per contract or share, per side.
commMin (series float) : Minimum commission per fill. Applied only when qty > 0.
pointValue (series float) : Currency value of one full point of price movement, per unit.
qtyStep (series float) : Rounds size DOWN to this increment. 0 = no rounding.
initCap (series float) : Starting equity of the shadow account.
sizeMode (series SizeMode) : Position sizing model.
riskPct (series float) : Risk per trade, percent of equity. SizeMode.riskStop only.
maxTotalPct (series float) : Ceiling on total open risk, percent of equity. riskStop only.
fixedUnits (series float) : Units per entry. SizeMode.fixedUnits only.
equityPct (series float) : Notional as percent of equity. SizeMode.equityPct only.
useLevCap (series bool) : Apply the leverage cap on top of the chosen sizing model.
maxLeverage (series float) : Max notional / equity.
maxUnits (series int) : Max entries per position. MUST equal the host strategy's
fillMode (series FillMode) : Execution assumption. Determines which signals step() wants.
SimState
Mutable state of the shadow account. Create with newState().
Fields:
equity (series float) : Realised equity, commissions already deducted.
dir (series int) : 1 long, -1 short, 0 flat.
entry (series float) : Volume-weighted average entry price.
qty (series float) : Total units held.
units (series int) : Number of fills making up the current position.
trades (series int) : Closed trades.
wins (series int) : Closed trades with net > 0.
grossP (series float) : Sum of winning net PnL.
grossL (series float) : Sum of absolute losing net PnL.
commPaid (series float) : Total commission paid, both sides.
peak (series float) : Mark-to-market equity high water mark.
maxDD (series float) : Worst mark-to-market drawdown, as a negative fraction.
consecL (series int) : Current consecutive-loss run.
maxConsL (series int) : Longest consecutive-loss run.
sumTrPct (series float) : Sum of per-trade returns, percent of equity-before-trade.
skipped (series int) : Entry signals dropped because sizing returned zero units. Library

Arbor_Gradient_Boosting_GainzAlgoGainzAlgo is excited to bring the ability to perform gradient boosting and feature importance selection to Pine Script. Currently, there are no native capabilities within Pine Script for gradient boosting or feature importance selection. Arbor fills this significant gap by introducing a from-scratch Gradient Boosting Machine (GBM) engineered with XGBoost-style mechanics.
Designed to support both classification and regression tasks, and building on our Random Forest approach to Pinescript, Arbor utilizes depth-1 stumps, meaning it performs one split per round without column subsampling.
Because PulseWire automatically lists the exported types and function parameters, the following outlines the core mechanics and capabilities you unlock by importing Arbor.
Core Mechanics
Arbor brings advanced machine-learning concepts directly into your Pine Script workflows:Advanced Training: Utilizes Newton leaf steps (second-order hessian weighting) and the exact XGBoost gain formula.
Regularization & Pruning: Integrates L2 regularization (lambda), minimum gain pruning (gamma), and minimum child weight checks to manage model complexity and prevent overfitting.
Stochasticity: Implements Fisher-Yates row subsampling to provide genuine round-to-round stochasticity matching XGBoost's subsample behavior.
Reproducibility: You can pass an optional seed to any fit function to ensure reproducible training runs across reloads.
Model Tiers
The library supports models scaled across three specific feature tiers:
GBM (1 Feature): Built for rapid classification or regression implementations.
GBM3 (3 Features): Purpose-built specifically for classification tasks.
GBM4 (4 Features): Supports both classification and regression, and uniquely offers XGBoost-style, gain-based feature importance evaluation.
Library "Arbor_Gradient_Boosting_GainzAlgo"
Arbor — gradient boosting for Pine Script. From-scratch GBM v2
with XGBoost-style mechanics: Fisher-Yates row subsampling, Newton leaf steps
(second-order hessian weighting), exact XGBoost gain formula with L2
regularization (lambda), minimum gain pruning (gamma), and minimum child
weight. Trees are depth-1 stumps (one split per round) and there is no
column (feature) subsampling — this is an XGBoost-style boosting scheme,
not a full XGBoost reimplementation. Supports classification and regression
across three feature tiers:
- GBM (1 feature) : gbm_fit / gbm_predict
classification or regression via is_classifier
- GBM3 (3 features) : gbm3_fit / gbm3_predict
classification only
- GBM4 (4 features) : gbm4_fit / gbm4_predict / gbm4_importance_pct
classification or regression with XGBoost-style
gain-based feature importance
All variants use Newton leaf steps, exact gain formula, L2 regularization,
Fisher-Yates shuffle subsampling, and gamma/min_child_weight pruning. Pass
an optional seed to any fit function for reproducible training runs.
gbm_fit(feat, target, n_rounds, lr, n_thresh, is_classifier, lambda, gamma, min_child_w, subsample, seed)
Fits a single-feature gradient-boosted stump ensemble using
XGBoost-style mechanics: Newton leaf steps (second-order hessian weighting),
exact gain formula with L2 regularization, gamma pruning, minimum child
weight, and Fisher-Yates row subsampling. Each round fits one depth-1 stump
(this is not a full multi-level tree, and there is no column subsampling).
Supports both binary classification (log-odds + sigmoid) and regression (MSE).
Parameters:
feat (array) : Array of feature values, one per training row
target (array) : Array of targets — 0.0/1.0 for classification, continuous for regression
n_rounds (int) : Number of boosting rounds / stumps to fit
lr (float) : Learning rate / shrinkage applied to each round's leaf contribution
n_thresh (int) : Candidate split thresholds to scan per round
is_classifier (bool) : True = binary classification, False = squared-error regression
lambda (float) : L2 leaf regularization — Ridge-style shrinkage toward zero (XGBoost default: 1.0)
gamma (float) : Minimum gain required to accept a split — prunes weak splits (XGBoost default: 0.0)
min_child_w (float) : Minimum hessian sum per child node — prevents tiny noisy splits (XGBoost default: 1.0)
subsample (float) : Fraction of rows randomly sampled per round via Fisher-Yates (default: 1.0 = all rows)
seed (int) : Optional seed for the row-subsampling shuffle — pass a fixed value for reproducible fits across reloads (default: na = unseeded/random each time)
Returns: Fitted GBM object ready for gbm_predict()
gbm_predict(model, x)
Scores a single feature value against a fitted GBM ensemble.
Parameters:
model (GBM) : A GBM object previously returned by gbm_fit()
x (float) : Feature value to score (same feature definition used in training)
Returns: Predicted probability if classifier, raw predicted value if regressor
gbm3_fit(feat1, feat2, feat3, target, n_rounds, lr, n_thresh, lambda, gamma, min_child_w, subsample, seed)
Fits a 3-feature gradient-boosted classifier using XGBoost-style
mechanics: Newton leaf steps, exact gain formula, L2 regularization, gamma
pruning, minimum child weight, and Fisher-Yates row subsampling. Selects the
best (feature, threshold) pair each round and boosts in log-odds space.
Each round fits a single depth-1 stump; there is no column subsampling.
Parameters:
feat1 (array) : Array of feature 1 values, one per training row
feat2 (array) : Array of feature 2 values, one per training row
feat3 (array) : Array of feature 3 values, one per training row
target (array) : Array of binary targets (0.0 or 1.0), one per training row
n_rounds (int) : Number of boosting rounds
lr (float) : Learning rate / shrinkage
n_thresh (int) : Candidate thresholds scanned per feature per round
lambda (float) : L2 leaf regularization (Ridge shrinkage, XGBoost default: 1.0)
gamma (float) : Minimum gain to accept a split (XGBoost default: 0.0)
min_child_w (float) : Minimum hessian sum per child node (XGBoost default: 1.0)
subsample (float) : Row sampling fraction per round via Fisher-Yates (default: 1.0)
seed (int) : Optional seed for the row-subsampling shuffle — pass a fixed value for reproducible fits across reloads (default: na = unseeded/random each time)
Returns: Fitted GBM3 object ready for gbm3_predict()
gbm3_predict(model, x1, x2, x3)
Scores 3 feature values against a fitted GBM3 classifier.
Parameters:
model (GBM3) : GBM3 object from gbm3_fit()
x1 (float) : Current value of feature 1
x2 (float) : Current value of feature 2
x3 (float) : Current value of feature 3
Returns: Predicted probability
gbm4_fit(feat1, feat2, feat3, feat4, target, n_rounds, lr, n_thresh, is_classifier, lambda, gamma, min_child_w, subsample, seed)
Fits a 4-feature gradient-boosted ensemble with Newton steps, exact gain
formula, L2 regularization, gamma pruning, minimum child weight, Fisher-Yates
row subsampling, and gain-based feature importance tracking.
Supports both binary classification and regression. Each round fits a single
depth-1 stump; there is no column subsampling.
Parameters:
feat1 (array) : Array of feature 1 values, one per training row
feat2 (array) : Array of feature 2 values, one per training row
feat3 (array) : Array of feature 3 values, one per training row
feat4 (array) : Array of feature 4 values, one per training row
target (array) : Array of targets — 0.0/1.0 for classification, continuous for regression
n_rounds (int) : Number of boosting rounds
lr (float) : Learning rate / shrinkage
n_thresh (int) : Candidate thresholds scanned per feature per round
is_classifier (bool) : True = binary classification, False = regression
lambda (float) : L2 leaf regularization (Ridge shrinkage, XGBoost default: 1.0)
gamma (float) : Minimum gain to accept a split (XGBoost default: 0.0)
min_child_w (float) : Minimum hessian sum per child node (XGBoost default: 1.0)
subsample (float) : Row sampling fraction per round via Fisher-Yates (default: 1.0)
seed (int) : Optional seed for the row-subsampling shuffle — pass a fixed value for reproducible fits across reloads (default: na = unseeded/random each time)
Returns: Fitted GBM4 object with importance scores, ready for gbm4_predict() / gbm4_importance_pct()
gbm4_predict(model, x1, x2, x3, x4)
Scores 4 feature values against a fitted GBM4 ensemble.
Parameters:
model (GBM4) : GBM4 object from gbm4_fit()
x1 (float) : Current value of feature 1
x2 (float) : Current value of feature 2
x3 (float) : Current value of feature 3
x4 (float) : Current value of feature 4
Returns: Predicted probability if classifier, raw predicted value if regressor
gbm4_importance_pct(model, feat_idx)
Returns normalized feature importance as % of total gain for one feature.
Importance = accumulated gain credited to this feature across all boosting rounds,
matching XGBoost's xgb.importance() Gain column definition.
Parameters:
model (GBM4) : GBM4 object from gbm4_fit()
feat_idx (int) : Feature index to query (0-3)
Returns: Percentage of total ensemble gain attributed to this feature (0.0–100.0)
GBM
Holds a fitted gradient-boosted stump ensemble (1 feature).
Fields:
thresh (array) : Split threshold for each round's stump
left_val (array) : Newton leaf value when feature < threshold
right_val (array) : Newton leaf value when feature >= threshold
base_score (series float) : Log-odds of training mean (classifier) or mean (regressor)
lr (series float) : Learning rate stored for inference
is_classifier (series bool) : True = sigmoid probability output, False = raw regression output
GBM3
Holds a fitted 3-feature gradient-boosted stump ensemble (classification only).
Fields:
stump_feat (array) : Which feature index (0-2) each round's stump split on
thresh (array) : Split threshold for each round's stump
left_val (array) : Newton leaf value when feature < threshold
right_val (array) : Newton leaf value when feature >= threshold
base_score (series float) : Log-odds of training mean
lr (series float) : Learning rate stored for inference
GBM4
Holds a fitted 4-feature gradient-boosted ensemble with gain-based importance.
Fields:
stump_feat (array) : Which feature index (0-3) each round's stump split on
thresh (array) : Split threshold for each round's stump
left_val (array) : Newton leaf value when feature < threshold
right_val (array) : Newton leaf value when feature >= threshold
importance (array) : Accumulated gain per feature (indices 0-3), raw — normalize via gbm4_importance_pct()
base_score (series float) : Log-odds (classifier) or mean (regressor)
lr (series float) : Learning rate stored for inference
is_classifier (series bool) : True = sigmoid probability output, False = raw regression output Library

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

BitLangLangData08Library "BitLangLangData08"
contains(pair)
Parameters:
pair (string)
loadSummary(pair, aSym, aSeq, aDir, aLev, aOpenT, aCloseT, aOpenP, aCloseP, aRet, aPnl, aMargin)
Parameters:
pair (string)
aSym (array)
aSeq (array)
aDir (array)
aLev (array)
aOpenT (array)
aCloseT (array)
aOpenP (array)
aCloseP (array)
aRet (array)
aPnl (array)
aMargin (array)
loadDetails(pair, aFillStart, aFillCount, aFillT, aFillP, aFillQ, aFillAction)
Parameters:
pair (string)
aFillStart (array)
aFillCount (array)
aFillT (array)
aFillP (array)
aFillQ (array)
aFillAction (array) Library

BitLangLangData07Library "BitLangLangData07"
contains(pair)
Parameters:
pair (string)
loadSummary(pair, aSym, aSeq, aDir, aLev, aOpenT, aCloseT, aOpenP, aCloseP, aRet, aPnl, aMargin)
Parameters:
pair (string)
aSym (array)
aSeq (array)
aDir (array)
aLev (array)
aOpenT (array)
aCloseT (array)
aOpenP (array)
aCloseP (array)
aRet (array)
aPnl (array)
aMargin (array)
loadDetails(pair, aFillStart, aFillCount, aFillT, aFillP, aFillQ, aFillAction)
Parameters:
pair (string)
aFillStart (array)
aFillCount (array)
aFillT (array)
aFillP (array)
aFillQ (array)
aFillAction (array) Library

BitLangLangData06Library "BitLangLangData06"
contains(pair)
Parameters:
pair (string)
loadSummary(pair, aSym, aSeq, aDir, aLev, aOpenT, aCloseT, aOpenP, aCloseP, aRet, aPnl, aMargin)
Parameters:
pair (string)
aSym (array)
aSeq (array)
aDir (array)
aLev (array)
aOpenT (array)
aCloseT (array)
aOpenP (array)
aCloseP (array)
aRet (array)
aPnl (array)
aMargin (array)
loadDetails(pair, aFillStart, aFillCount, aFillT, aFillP, aFillQ, aFillAction)
Parameters:
pair (string)
aFillStart (array)
aFillCount (array)
aFillT (array)
aFillP (array)
aFillQ (array)
aFillAction (array) Library

BitLangLangData05Library "BitLangLangData05"
contains(pair)
Parameters:
pair (string)
loadSummary(pair, aSym, aSeq, aDir, aLev, aOpenT, aCloseT, aOpenP, aCloseP, aRet, aPnl, aMargin)
Parameters:
pair (string)
aSym (array)
aSeq (array)
aDir (array)
aLev (array)
aOpenT (array)
aCloseT (array)
aOpenP (array)
aCloseP (array)
aRet (array)
aPnl (array)
aMargin (array)
loadDetails(pair, aFillStart, aFillCount, aFillT, aFillP, aFillQ, aFillAction)
Parameters:
pair (string)
aFillStart (array)
aFillCount (array)
aFillT (array)
aFillP (array)
aFillQ (array)
aFillAction (array) Library

BitLangLangData04Library "BitLangLangData04"
contains(pair)
Parameters:
pair (string)
loadSummary(pair, aSym, aSeq, aDir, aLev, aOpenT, aCloseT, aOpenP, aCloseP, aRet, aPnl, aMargin)
Parameters:
pair (string)
aSym (array)
aSeq (array)
aDir (array)
aLev (array)
aOpenT (array)
aCloseT (array)
aOpenP (array)
aCloseP (array)
aRet (array)
aPnl (array)
aMargin (array)
loadDetails(pair, aFillStart, aFillCount, aFillT, aFillP, aFillQ, aFillAction)
Parameters:
pair (string)
aFillStart (array)
aFillCount (array)
aFillT (array)
aFillP (array)
aFillQ (array)
aFillAction (array) Library

BitLangLangData03Library "BitLangLangData03"
contains(pair)
Parameters:
pair (string)
loadSummary(pair, aSym, aSeq, aDir, aLev, aOpenT, aCloseT, aOpenP, aCloseP, aRet, aPnl, aMargin)
Parameters:
pair (string)
aSym (array)
aSeq (array)
aDir (array)
aLev (array)
aOpenT (array)
aCloseT (array)
aOpenP (array)
aCloseP (array)
aRet (array)
aPnl (array)
aMargin (array)
loadDetails(pair, aFillStart, aFillCount, aFillT, aFillP, aFillQ, aFillAction)
Parameters:
pair (string)
aFillStart (array)
aFillCount (array)
aFillT (array)
aFillP (array)
aFillQ (array)
aFillAction (array) Library

BitLangLangData02Library "BitLangLangData02"
contains(pair)
Parameters:
pair (string)
loadSummary(pair, aSym, aSeq, aDir, aLev, aOpenT, aCloseT, aOpenP, aCloseP, aRet, aPnl, aMargin)
Parameters:
pair (string)
aSym (array)
aSeq (array)
aDir (array)
aLev (array)
aOpenT (array)
aCloseT (array)
aOpenP (array)
aCloseP (array)
aRet (array)
aPnl (array)
aMargin (array)
loadDetails(pair, aFillStart, aFillCount, aFillT, aFillP, aFillQ, aFillAction)
Parameters:
pair (string)
aFillStart (array)
aFillCount (array)
aFillT (array)
aFillP (array)
aFillQ (array)
aFillAction (array) Library

BitLangLangData01Library "BitLangLangData01"
contains(pair)
Parameters:
pair (string)
loadSummary(pair, aSym, aSeq, aDir, aLev, aOpenT, aCloseT, aOpenP, aCloseP, aRet, aPnl, aMargin)
Parameters:
pair (string)
aSym (array)
aSeq (array)
aDir (array)
aLev (array)
aOpenT (array)
aCloseT (array)
aOpenP (array)
aCloseP (array)
aRet (array)
aPnl (array)
aMargin (array)
loadDetails(pair, aFillStart, aFillCount, aFillT, aFillP, aFillQ, aFillAction)
Parameters:
pair (string)
aFillStart (array)
aFillCount (array)
aFillT (array)
aFillP (array)
aFillQ (array)
aFillAction (array) Library

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

ContractResolverLibrary "ContractResolver"
Classify a PulseWire symbol (stock / crypto / future / etc.) and, for
continuous futures, resolve the real front-month contract ticker with a
4-digit year (e.g. "MNQ1!" -> "MNQU2026"). Prefers the built-in
syminfo.current_contract (authoritative, roll-aware) and falls back to a
calendar estimate only when current_contract is na.
monthCode(m)
Month number (1-12) -> futures month-code letter. Returns na if out of range.
Parameters:
m (int) : Month number, 1-12.
Returns: Single-letter month code, or na.
monthNumber(code)
Month-code letter -> month number (1-12). Returns na if not a valid code.
Parameters:
code (string) : Single-letter month code (case-insensitive).
Returns: Month number 1-12, or na.
resolve(ticker, exchange, symType, currentContract, refTime, rollDay)
Resolve a symbol into its asset class and, for continuous futures, the
front-month contract ticker. Pass syminfo.current_contract for an exact,
roll-aware result; if it is na, a calendar estimate is used (approximated=true).
Parameters:
ticker (string) : Symbol without exchange prefix (e.g. syminfo.ticker).
exchange (string) : Exchange / prefix (e.g. syminfo.prefix).
symType (string) : syminfo.type ("stock","crypto","futures","forex","fund","index","dr"...).
currentContract (string) : syminfo.current_contract (na when chart is not a continuous future).
refTime (int) : Reference time (ms) for the estimate fallback; 0 -> use timenow.
rollDay (int) : Day-of-month threshold for rolling to the next contract in the fallback.
Returns: A Contract object.
resolveChart(rollDay)
Convenience wrapper: resolve the chart's own symbol from its syminfo.* fields.
Parameters:
rollDay (int) : Day-of-month threshold used only by the estimate fallback.
Returns: A Contract object for the current chart symbol.
format(c, pattern)
Build a custom string from a resolved Contract using a placeholder pattern.
Placeholders: {root} {mc} {m} {mm} {yyyy} {yy} {ticker} {exch} {class}
e.g. format(c, "{exch}:{root}{mc}{yyyy}") -> "CME_MINI:MNQU2026"
Parameters:
c (Contract) : A Contract (typically from resolve / resolveChart).
pattern (string) : Template string containing any of the placeholders above.
Returns: The pattern with placeholders substituted (missing fields -> "").
Contract
Parsed/resolved symbol.
Fields:
ticker (series string) : Original ticker without exchange prefix (e.g. "MNQ1!").
exchange (series string) : Exchange / prefix (e.g. "CME_MINI").
assetClass (series string) : "stock" | "crypto" | "future" | "forex" | "index" | "fund" | "other".
isContinuous (series bool) : True when the ticker is a continuous future (ends with "!").
root (series string) : Futures root (e.g. "MNQ"); na for non-futures.
monthCode (series string) : Futures month letter (F,G,H,J,K,M,N,Q,U,V,X,Z); na for non-futures.
contractMonth (series int) : Contract month 1-12; na for non-futures.
contractYear (series int) : 4-digit contract year; na for non-futures.
resolved (series string) : Final ticker: real contract for futures, unchanged for stock/crypto/other.
approximated (series bool) : True when month/year were estimated by calendar (not from current_contract). Library

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

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

pbkr_commonLibrary "pbkr_common"
f_clamp(v, lo, hi)
Parameters:
v (float)
lo (float)
hi (float)
f_roc(src, len)
Parameters:
src (float)
len (int)
f_dcr(h, l, c)
Parameters:
h (float)
l (float)
c (float)
f_tick(p)
Parameters:
p (float)
f_round_up(p)
Parameters:
p (float)
f_round_down(p)
Parameters:
p (float)
f_nzmax(a, b)
Parameters:
a (float)
b (float)
f_best_support(entry, a, b, c, d, e)
Parameters:
entry (float)
a (float)
b (float)
c (float)
d (float)
e (float)
f_ma_pack()
f_launch_conv(sma10, ema21, sma50, sma200, ref_price)
Parameters:
sma10 (float)
ema21 (float)
sma50 (float)
sma200 (float)
ref_price (float)
f_vol_pack()
f_vol_dryup(vol10, vol50, mult)
Parameters:
vol10 (float)
vol50 (float)
mult (float)
f_hv1(vol, vol50, mult)
Parameters:
vol (float)
vol50 (float)
mult (float)
f_pocket_pivot_vol(lookback)
Parameters:
lookback (simple int)
f_adr20()
f_tight_range(short_n, long_n, ratio)
Parameters:
short_n (int)
long_n (int)
ratio (float)
f_high_low_pack()
f_phase_code(lookback)
Parameters:
lookback (int)
f_phase_txt(phase)
Parameters:
phase (int)
f_px(v)
Parameters:
v (float)
f_pct(v)
Parameters:
v (float)
MAPack
Fields:
sma10 (series float)
ema21 (series float)
sma50 (series float)
sma150 (series float)
sma200 (series float)
VolPack
Fields:
vol50 (series float)
vol10 (series float)
vol5 (series float)
rvol (series float)
run_rate (series float)
HighLowPack
Fields:
hh52 (series float)
ll52 (series float)
off_52h_pct (series float)
off_52l_pct (series float) Library

Library

LogLibLibrary "LogLib"
LogLib — unified logger with BUFFERED / PER_BAR / OFF modes,
bit-packed plot encoders, perf timing (tick/tock), load timer.
Step 2 patch: enum LogMode + LogLevel, method-first API, preserved facades.
f_logger_mode_off()
f_logger_mode_buffered()
f_logger_mode_stream()
f_logger_mode_per_bar()
f_q_unsigned(x, scale, maxv)
Quantize unsigned float to N-bit integer
Parameters:
x (float)
scale (float)
maxv (int)
f_q_signed(x, scale, bias, maxv)
Quantize signed float to N-bit integer with bias offset
Parameters:
x (float)
scale (float)
bias (int)
maxv (int)
f_pack3x10(a, b, c)
Pack three 10-bit values into single float for data window
Parameters:
a (int)
b (int)
c (int)
f_pack4x8(a, b, c, d)
Pack four 8-bit values into single float for data window
Parameters:
a (int)
b (int)
c (int)
d (int)
f_unpack3x10_a(packed)
Parameters:
packed (int)
f_unpack3x10_b(packed)
Parameters:
packed (int)
f_unpack3x10_c(packed)
Parameters:
packed (int)
f_unpack4x8_a(packed)
Parameters:
packed (int)
f_unpack4x8_b(packed)
Parameters:
packed (int)
f_unpack4x8_c(packed)
Parameters:
packed (int)
f_unpack4x8_d(packed)
Parameters:
packed (int)
f_encode_flags(s0, s1, s2, s3, s4, s5, s6, s7)
Encode 8 binary flags into 8-bit int
Parameters:
s0 (bool)
s1 (bool)
s2 (bool)
s3 (bool)
s4 (bool)
s5 (bool)
s6 (bool)
s7 (bool)
f_encode_ternary(s0, s1, s2, s3, s4)
Encode 5 ternary states (0,1,2) into base-3 integer
Parameters:
s0 (int)
s1 (int)
s2 (int)
s3 (int)
s4 (int)
f_decode_flag(encoded, bit_index)
Parameters:
encoded (int)
bit_index (int)
f_decode_ternary(encoded, state_index)
Parameters:
encoded (int)
state_index (int)
f_logger_new(mode, label, header, max_lines)
Initialize Logger (legacy signature, preserved)
Parameters:
mode (simple int) : 0=OFF/STREAM-alias, 1=BUFFERED, 2=PER_BAR
label (simple string)
header (simple string)
max_lines (simple int)
f_logger_new_enum(mode, label, header, max_lines)
Enum-aware factory (preferred for new code)
Parameters:
mode (simple LogMode)
label (simple string)
header (simple string)
max_lines (simple int)
f_new_logger_buffered(label, header)
Quick BUFFERED logger with default thresholds (4000 chars / 2500 lines)
Parameters:
label (simple string)
header (simple string)
f_new_logger_per_bar(label, header)
Quick PER_BAR logger
Parameters:
label (simple string)
header (simple string)
f_new_logger_off()
Quick OFF logger (no-op, for production builds)
method append(l, row)
Append a row to the log; routes by mode.
@details OFF: discarded. BUFFERED: auto-flush when chars/lines threshold hit.
PER_BAR: caller must invoke flush() on barstate.isconfirmed.
Namespace types: Logger
Parameters:
l (Logger)
row (string)
method flush(l)
Explicit flush — drains any non-empty buffer.
@details Does NOT depend on barstate.islast. Caller invokes at natural
boundaries (RCOM completion, manual checkpoint, barstate.isconfirmed
for PER_BAR). BUFFERED mode primary flush remains automatic via append().
Namespace types: Logger
Parameters:
l (Logger)
method reset(l)
Reset buffer without flushing (drops accumulated content)
Namespace types: Logger
Parameters:
l (Logger)
method kv(l, key, val)
Append key=value diagnostic line
Namespace types: Logger
Parameters:
l (Logger)
key (string)
val (float)
method event(l, event_type, payload)
Append tagged event with bar_index prefix
Namespace types: Logger
Parameters:
l (Logger)
event_type (string)
payload (string)
method debug(l, msg)
Severity-tagged writers (level prefix added)
Namespace types: Logger
Parameters:
l (Logger)
msg (string)
method info(l, msg)
Namespace types: Logger
Parameters:
l (Logger)
msg (string)
method warn(l, msg)
Namespace types: Logger
Parameters:
l (Logger)
msg (string)
method error(l, msg)
ERROR — appends + immediate flush (drains accumulated buffer too)
Namespace types: Logger
Parameters:
l (Logger)
msg (string)
method tick(l, tag)
Namespace types: Logger
Parameters:
l (Logger)
tag (string)
method tock(l, tag)
Namespace types: Logger
Parameters:
l (Logger)
tag (string)
method get_last_timing(l)
Namespace types: Logger
Parameters:
l (Logger)
f_load_timer_new()
method update(lt)
Namespace types: LoadTimer
Parameters:
lt (LoadTimer)
method get_time(lt)
Namespace types: LoadTimer
Parameters:
lt (LoadTimer)
method get_formatted(lt)
Namespace types: LoadTimer
Parameters:
lt (LoadTimer)
method get_color(lt)
Namespace types: LoadTimer
Parameters:
lt (LoadTimer)
method log_time(lt, prefix)
Namespace types: LoadTimer
Parameters:
lt (LoadTimer)
prefix (string)
method log_to_logger(lt, logger)
Namespace types: LoadTimer
Parameters:
lt (LoadTimer)
logger (Logger)
method add_to_table(lt, t, col, row)
Namespace types: LoadTimer
Parameters:
lt (LoadTimer)
t (table)
col (int)
row (int)
Logger
Logger state. Mode field stays int for backward compat with persisted
Fields:
mode (series int) : 0=OFF, 1=BUFFERED, 2=PER_BAR (matches LogMode ordinal)
buffer (series string)
line_count (series int)
max_lines (series int)
max_chars (series int)
header (series string)
header_written (series bool)
label (series string)
markers (map)
last_delta_ms (series float)
last_tag (series string)
LoadTimer
Fields:
start_ms (series int)
load_secs_latched (series float)
captured (series bool) Library

ICOptimizerLibLibrary "ICOptimizerLib"
ICOptimizerLib v2 — IC-based parameter optimization with 4 Bayesian strategies.
Publish target: ICOptimizer/2 (hard break from v1 — see §A below).
Layer 1: primitive IC estimators (Pearson, Spearman, Kendall, Partial).
Layer 2: Optimizer UDT with 4 strategies: argmax | ucb | thompson | bayesian.
Layer 3: RegimeGate, ObjectiveWeights, composite scoring, serialize/restore.
Layer 4: diagnostics table and panel.
L2 library — depends only on NumLib.
─── §A v1 BACKWARD-COMPAT DECISION (follow-up 1) ────────────────────────
HARD BREAK. v1 (ICOptimizer/1) used bare strings ("argmax", "ucb", …).
v2 uses the OptimizerKind enum. Reason: Pine v6 enums are type-safe and
produce CE10 errors at compile time if a caller passes an invalid string,
whereas bare strings fail silently at runtime. The compat shim route
(string→enum dispatch wrapper) was considered and rejected: it would
re-introduce series-string branching inside a hot method, defeating the
purpose of the enum migration.
Migration for v1 callers:
OLD: f_find_optimal_param(params, ics, cur, 0.2) ← v1 API
NEW: opt = f_optimizer_new(OptimizerKind.ARGMAX, …) ← v2 API
idx = opt.propose()
opt.observe(idx, ic)
The free function f_find_optimal_param() is retained in §4 as a one-line
compat wrapper producing identical output to v1 findOptimalParam() for
callers that only used ARGMAX and do not need the UDT.
Publish target: ICOptimizer/2 (same publisher namespace as kNNLib/28,
LearningLib/1, etc. Parallel to v1, not a rename.)
─── §B UDT INDEPENDENCE AUDIT (follow-up 2) ─────────────────────────────
All 4 UDTs are independently constructable with no required coupling:
UDT Constructor Depends on
─────────────── ─────────────────────────── ────────────────────────────
Optimizer f_optimizer_new(…) nothing (grid is caller-owned)
RollingIC f_rolling_ic_new(capacity) nothing
RegimeGate f_regime_gate_new(…) nothing
ObjectiveWeights f_obj_weights_new(…) nothing
Valid combinations:
• Optimizer alone — minimal usage (ARGMAX strategy, no IC classification)
• Optimizer + RollingIC — IC classification per bar, classify() method
• Optimizer + ObjectiveWeights — composite scoring for multi-objective grids
• Optimizer + RegimeGate — gate-filtered observe() calls
• All 4 — full stack
Initialization order: any order; there are no cross-UDT init dependencies.
The caller is responsible for pushing IC values into RollingIC before
calling classify(); a fresh buffer returns 0.0 thresholds (safe default).
─── §C GP MATH VERIFICATION (follow-up 3) ───────────────────────────────
Jacobi solver convergence domain: guaranteed for diagonally dominant K.
K is diagonally dominant when kernel_noise > 0 (K = kernel(xi,xi) +
noise ≥ 1 + noise > Σ_{j≠i} kernel(xi,xj) for RBF/Matern52 with ls > 0).
NaN propagation guard: f_optimizer_new() enforces noise ≥ 1e-6 at
construction (see implementation below). NaN in ic_sample is gated by
the na(ic_sample) check in observe() before any array writes.
Grid size constraints (enforced at f_optimizer_new):
grid_size == 1 → runtime.error (BAYESIAN is undefined for a single cell)
grid_size > 30 → runtime.error for BAYESIAN only (Jacobi O(n²×20) budget)
grid_size ≥ 2 → all strategies valid
ARGMAX/UCB/THOMPSON have no upper grid-size constraint.
Unit test specification (see test_icoptimizer_v2_unit.pine):
T1: grid= + BAYESIAN → should hit error log (na guard)
T2: grid= + BAYESIAN, 50 observe() calls → ic_var shrinks
T3: grid size=30 + BAYESIAN → no silent NaN on bar 500 / 1000
T4: rising IC synthetic trajectory → propose() returns idx 6 after warmup
T5: peak-in-middle IC → propose() converges to idx 3 (center)
─── §D v5→v6 DELTA (Phase E-2a) ─────────────────────────────────────────
1. //@version=5 → //@version=6
2. type ICOptimizer → decomposed to 4 independent UDTs (§B)
3. `series float` qualifiers explicit; `simple int` for all ta.* lengths (CE10297)
4. Enum OptimizerKind / KernelKind / ReturnMode replaces bare strings
5. classifyIC scalar bug → RollingIC ring buffer + sort-based percentile
6. detectAndAdjustDomination orphan → method check_domination on Optimizer
7. Monotonic counter → reset_decay(decay) method
8. S9: all multi-line ternaries collapsed to single lines
9. f_ma_for_idx() dispatch in demo for simple-int ta.sma constraint
10. Nested array.get() in f_build_gram / observe() split to locals (COMMA_STATEMENTS)
f_ic_pearson(signal, ret, n)
Pearson IC: correlation of signal with forward return
Parameters:
signal (float) : Signal series (e.g. z-score oscillator)
ret (float) : Forward return series (aligned: ret = realized return for signal )
n (simple int) : Rolling window (simple int — required by ta.correlation)
f_ic_spearman(signal, ret, n)
Spearman IC via rank correlation approximation
Parameters:
signal (float) : Signal series
ret (float) : Forward return series
n (simple int) : Rolling window
Returns: Spearman rank-correlation approximation
f_ic_kendall(signal, ret, n)
Kendall IC approximation (via concordant/discordant sign correlation)
Parameters:
signal (float) : Signal series
ret (float) : Forward return series
n (simple int) : Rolling window
Returns: Kendall tau approximation
f_ic_partial(signal, ret, control, n)
Partial IC: correlation of signal with ret after removing control variable
Parameters:
signal (float) : Signal series
ret (float) : Forward return series
control (float) : Control variable to partial out
n (simple int) : Rolling window
Returns: Partial Pearson IC
f_forward_return(src, horizon, mode, benchmark)
Compute forward return from source series
Parameters:
src (float) : Source price series
horizon (simple int) : Look-forward bars
mode (series ReturnMode) : ReturnMode enum
benchmark (float) : Optional benchmark (used only in EXCESS mode; pass na otherwise)
f_label_from_signal(sig, ret, eps)
Label from signal × return sign match
Parameters:
sig (float) : Signal value
ret (float) : Realized return
eps (float) : Dead-zone threshold (returns within ±eps labelled 0)
Returns: 1 = correct direction, -1 = wrong direction, 0 = inside dead-zone
f_rolling_ic_new(capacity)
Create a new RollingIC buffer
Parameters:
capacity (simple int) : Number of IC samples to retain
method push(self, ic_val)
Push a new IC observation into the ring buffer
Namespace types: RollingIC
Parameters:
self (RollingIC)
ic_val (float)
method classify(self, ic_val, good_pct, bad_pct)
Classify current IC against ring buffer distribution
Namespace types: RollingIC
Parameters:
self (RollingIC) : RollingIC buffer (must have been pushed at least once)
ic_val (float) : Current IC to classify
good_pct (float) : Percentile above which IC is "good" (0–100)
bad_pct (float) : Percentile below which IC is "bad" (0–100)
Returns:
f_optimizer_new(kind, grid, lr, c_ucb, cooldown, kernel_kind, kernel_ls, kernel_noise)
Create a new Optimizer
Parameters:
kind (series OptimizerKind) : Strategy
grid (array) : Parameter grid (array, size ≤ 30 for BAYESIAN)
lr (float) : EWM learning rate for ic_ema / ic_var updates (0–1)
c_ucb (float) : UCB exploration constant (ignored for non-UCB)
cooldown (simple int) : Minimum bars between switches
kernel_kind (series KernelKind) : Kernel for BAYESIAN (ignored otherwise)
kernel_ls (float) : Kernel lengthscale (ignored otherwise)
kernel_noise (float) : Observation noise (ignored otherwise)
method propose(self)
Propose next parameter index to try
Namespace types: Optimizer
Parameters:
self (Optimizer)
Returns: Selected grid index
method observe(self, idx, ic_sample)
Record observed IC for a grid cell and update posterior
Namespace types: Optimizer
Parameters:
self (Optimizer)
idx (int) : Grid index that was evaluated
ic_sample (float) : Observed IC value
method reset_decay(self, decay)
Apply exponential decay to ic_ema and ic_var (prevents monotonic drift)
Namespace types: Optimizer
Parameters:
self (Optimizer)
decay (float) : Decay factor 0..1 (e.g. 0.95 = retain 95% of past)
method check_domination(self, long_n, short_n, ratio_threshold)
Detect directional signal domination and bump current grid index
Namespace types: Optimizer
Parameters:
self (Optimizer)
long_n (int) : Count of long signals in evaluation window
short_n (int) : Count of short signals in evaluation window
ratio_threshold (float) : Domination ratio (e.g. 4 = 4:1 imbalance)
Returns: direction_str = "long" | "short" | "none"
method current_param(self)
Get current parameter value from grid
Namespace types: Optimizer
Parameters:
self (Optimizer)
f_find_optimal_param(testParams, icValues, currentParam, smoothing)
Find optimal parameter from arrays (v1-compatible, wraps Optimizer.propose)
Parameters:
testParams (array) : Grid array
icValues (array) : IC values for each grid cell (same size)
currentParam (float) : Current param (for EWM smoothing)
smoothing (simple float) : EWM lr (0–1)
Returns:
f_regime_gate_new(mode, threshold, confirm_bars)
Create RegimeGate
Parameters:
mode (string)
threshold (float)
confirm_bars (simple int)
method is_open(self, ic_val, bars_above)
Check if gate is open given current IC and a rolling counter
Namespace types: RegimeGate
Parameters:
self (RegimeGate) : RegimeGate
ic_val (float) : Current IC
bars_above (int) : Rolling bars-above-threshold counter (caller maintains)
Returns: bool gate_open
f_obj_weights_new(w_ic, w_hitrate, w_freq_penalty, w_drawdown_penalty)
Create ObjectiveWeights
Parameters:
w_ic (float)
w_hitrate (float)
w_freq_penalty (float)
w_drawdown_penalty (float)
f_composite_score(w, ic, hitrate, freq, drawdown)
Compute composite score for a grid cell
Parameters:
w (ObjectiveWeights) : ObjectiveWeights
ic (float) : IC value for cell
hitrate (float) : Hit rate 0..1 for cell
freq (float) : Signal frequency 0..1 (higher = more signals = penalized)
drawdown (float) : Max drawdown magnitude (positive float)
Returns: Composite score (higher = better)
f_optimizer_serialize(self)
Serialize Optimizer state to a compact CSV string
Parameters:
self (Optimizer) : Optimizer to serialize
Returns: string blob (pass to f_optimizer_restore to reconstruct ic_ema/ic_var)
f_optimizer_restore(self, blob)
Restore ic_ema/ic_var/visits from serialized blob into an existing Optimizer
Parameters:
self (Optimizer) : Optimizer (grid must already be initialized with correct size)
blob (string) : String from f_optimizer_serialize
Returns: self (mutated in place)
f_diag_table(self, gate, weights, pos, max_rows)
Render diagnostics table for Optimizer state
Parameters:
self (Optimizer) : Optimizer
gate (RegimeGate) : RegimeGate (pass na if unused)
weights (ObjectiveWeights) : ObjectiveWeights (pass na if unused)
pos (string) : Table position (e.g. position.bottom_right)
max_rows (simple int) : Maximum grid rows to display (capped at array.size(grid))
Returns: table reference
f_diag_panel(self, height)
Render sparkline-style panel (one plot bar per grid cell, height = ic_ema)
Parameters:
self (Optimizer) : Optimizer
height (float) : Panel height in price units (caller scales)
Returns: label(na) (renders labels directly)
f_kind_str(k)
Parameters:
k (series OptimizerKind)
f_kernel_str(k)
Parameters:
k (series KernelKind)
f_return_mode_str(m)
Parameters:
m (series ReturnMode)
RollingIC
Rolling IC ring buffer for proper percentile computation
Fields:
samples (array) : Circular buffer of IC observations
head (series int) : Write head (mod capacity)
capacity (series int) : Max samples to retain
Optimizer
Optimizer — unified UDT for all 4 strategies
Fields:
kind (series OptimizerKind) : Strategy: ARGMAX | UCB | THOMPSON | BAYESIAN
grid (array) : Discrete parameter grid (size ≤ 30 for BAYESIAN)
ic_ema (array) : Posterior mean per cell (EWM updated)
ic_var (array) : Posterior variance per cell (UCB/Thompson/Bayes)
visits (array) : Visit count per cell
lr (series float) : EWM learning rate for ic_ema / ic_var updates
c_ucb (series float) : Exploration coefficient (UCB only)
cooldown (series int) : Minimum bars between parameter changes
last_change_bar (series int) : Bar index of last change
current_idx (series int) : Currently selected grid index
kernel_matrix (array) : Flattened len(grid)² Gram matrix (BAYESIAN only)
kernel_kind (series KernelKind) : RBF | MATERN52 (BAYESIAN only)
kernel_ls (series float) : Kernel lengthscale (BAYESIAN only)
kernel_noise (series float) : Observation noise σ² (BAYESIAN only)
total_visits (series int) : Cumulative visit count (for UCB log normalizer)
decay_factor (series float) : EWM decay applied by reset_decay (0..1; 1=no decay)
RegimeGate
RegimeGate — IC regime filter
Fields:
mode (series string) : "positive" | "any" | "top_pct"
threshold (series float) : IC threshold for "positive" or percentile for "top_pct"
confirm_bars (series int) : Bars IC must stay above threshold before gate opens
ObjectiveWeights
ObjectiveWeights — composite scoring weights
Fields:
w_ic (series float) : Weight on IC component
w_hitrate (series float) : Weight on hit-rate component
w_freq_penalty (series float) : Penalty for excessive signal frequency
w_drawdown_penalty (series float) : Penalty for drawdown Library

ChopEngineLibrary "ChopEngine"
chopBase(_high, _low, _len)
Parameters:
_high (float)
_low (float)
_len (simple int)
gaugeFromCi(_ci, _tl, _cl)
Parameters:
_ci (float)
_tl (simple float)
_cl (simple float)
chopGauge(_high, _low, _tl, _cl, _len)
Parameters:
_high (float)
_low (float)
_tl (simple float)
_cl (simple float)
_len (simple int)
getChopBase(_sym, _tf)
Parameters:
_sym (simple string)
_tf (simple string)
getChop(_ciPrev, _ci, _tl, _cl)
Parameters:
_ciPrev (simple float)
_ci (simple float)
_tl (simple float)
_cl (simple float)
chgStateLabel(_g)
Parameters:
_g (float)
chgColor(_chg)
Parameters:
_chg (float)
chgCell(_chg, _prefix)
Parameters:
_chg (float)
_prefix (string)
method init(this, _ciPrev, _ci, _tl, _cl)
Namespace types: Chop
Parameters:
this (Chop)
_ciPrev (float)
_ci (float)
_tl (simple float)
_cl (simple float)
method update(this, _ciPrev, _ci, _tl, _cl)
Namespace types: Chop
Parameters:
this (Chop)
_ciPrev (float)
_ci (float)
_tl (simple float)
_cl (simple float)
method chgVsPrev(this)
Namespace types: Chop
Parameters:
this (Chop)
method chgVsEod(this)
Namespace types: Chop
Parameters:
this (Chop)
method state(this)
Namespace types: Chop
Parameters:
this (Chop)
method isTrending(this)
Namespace types: Chop
Parameters:
this (Chop)
method isChoppy(this)
Namespace types: Chop
Parameters:
this (Chop)
method isImproving(this)
Namespace types: Chop
Parameters:
this (Chop)
method isDeteriorating(this)
Namespace types: Chop
Parameters:
this (Chop)
Chop
Fields:
now (series float)
prev (series float)
eod (series float) Library

Library

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 Library

Library
