腳本庫

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

StocksDeveloperAlertsLibrary "StocksDeveloperAlerts"
AutoTrader Web alert builder by Stocks Developer — turn TradingView alerts into real broker orders across many accounts and brokers. Ready-made functions for single orders, options the easy way, 8 option structures (straddle/strangle/spreads/iron condor/iron fly), custom multi-leg, account or group targeting, and your own risk limits. No alert-text typing. stocksdeveloper.in
order(symbol, exchange, producttype, tradetype, account, group, lots, quantity, ordertype, price, triggerprice, validity, amo, optiontype, strike, expiry, spothint, usespot, onslicefailure, risk, extra)
Build an alert message for a single order (stock, futures or one option leg). This is the full builder; equity() and option() are shorter wrappers over it. Set exactly one of account/group and exactly one of lots/quantity. Add optiontype to make it an option order.
Parameters:
symbol (string) : (series string) Broker-independent symbol, e.g. "NIFTY", "BANKNIFTY", "SBIN". For options, pass the underlier (e.g. "NIFTY"), not a full contract.
exchange (string) : (series string) Exchange code, e.g. "NSE"/"BSE" for stocks, "NFO" for options and futures.
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
tradetype (string) : (series string) BUY or SELL.
account (string) : (series string) Place in this single account. Set this OR group.
group (string) : (series string) Place in every live account in this group. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
ordertype (string) : (series string) MARKET (default), LIMIT, STOP_LOSS or SL_MARKET.
price (float) : (series float) Limit price (required for LIMIT).
triggerprice (float) : (series float) Trigger price (for stop-loss orders).
validity (string) : (series string) DAY (default) or IOC.
amo (bool) : (series bool) true for an after-market order.
optiontype (string) : (series string) CE for a call, PE for a put. Adding this makes it an option order.
strike (string) : (series string) ATM (default), ATM+1 / ATM-2, OTM / OTM2, ITM / ITM2, or an exact strike like "24500". Requires optiontype.
expiry (string) : (series string) weekly (default), next, monthly, or an exact date like "10-JUL-2026". Requires optiontype.
spothint (string) : (series string) Advanced: a spot price to help option-strike selection.
usespot (bool) : (series bool) Advanced: use the spot hint for strike selection.
onslicefailure (string) : (series string) Advanced: continue (default), alert or retry, if a large order that was auto-split has a slice fail.
risk (string) : (series string) A risk block from risk() — for example risk=atw.risk(maxloss=5000).
extra (string) : (series string) Advanced: any extra "key=value" lines to pass through unchanged (one per line).
Returns: (series string) The ready-to-send alert message.
equity(symbol, exchange, producttype, tradetype, account, group, lots, quantity, ordertype, price, triggerprice, validity, amo, risk, extra)
Build an alert for a single stock or futures order (no option fields). Set exactly one of account/group and exactly one of lots/quantity.
Parameters:
symbol (string) : (series string) Broker-independent symbol, e.g. "SBIN".
exchange (string) : (series string) Exchange code, e.g. "NSE" or "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
tradetype (string) : (series string) BUY or SELL.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
ordertype (string) : (series string) MARKET (default), LIMIT, STOP_LOSS or SL_MARKET.
price (float) : (series float) Limit price (required for LIMIT).
triggerprice (float) : (series float) Trigger price (for stop-loss orders).
validity (string) : (series string) DAY (default) or IOC.
amo (bool) : (series bool) true for an after-market order.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
option(symbol, exchange, producttype, tradetype, optiontype, strike, expiry, account, group, lots, quantity, ordertype, price, triggerprice, validity, amo, spothint, usespot, risk, extra)
Build an option order the easy way — give the underlier and pick the strike + expiry; no need to type the full option symbol. Set exactly one of account/group and exactly one of lots/quantity.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY", "BANKNIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
tradetype (string) : (series string) BUY or SELL.
optiontype (string) : (series string) CE for a call, PE for a put.
strike (string) : (series string) ATM (default), ATM+1 / ATM-2, OTM / OTM2, ITM / ITM2, or an exact strike like "24500".
expiry (string) : (series string) weekly (default), next, monthly, or an exact date like "10-JUL-2026".
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
ordertype (string) : (series string) MARKET (default), LIMIT, STOP_LOSS or SL_MARKET.
price (float) : (series float) Limit price (required for LIMIT).
triggerprice (float) : (series float) Trigger price (for stop-loss orders).
validity (string) : (series string) DAY (default) or IOC.
amo (bool) : (series bool) true for an after-market order.
spothint (string) : (series string) Advanced: a spot price to help strike selection.
usespot (bool) : (series bool) Advanced: use the spot hint for strike selection.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
straddle(symbol, exchange, producttype, account, group, lots, quantity, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Straddle — buy (or sell) a call and a put at the money. direction "BUY" = long straddle, "SELL" = short straddle.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) builds the structure as named; SELL flips every leg.
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue, if one leg cannot be placed.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
strangle(symbol, exchange, producttype, account, group, lots, quantity, width, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Strangle — buy (or sell) an out-of-the-money call and put, each 'width' strikes out. direction "BUY" = long strangle, "SELL" = short strangle.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
width (int) : (series int) How far out of the money the legs sit, in strike steps (default 2).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
bullCall(symbol, exchange, producttype, account, group, lots, quantity, width, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Bull call spread — buy a call at the money and sell a call 'width' strikes out. Use direction "SELL" to reverse.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
width (int) : (series int) Distance between the two strikes, in strike steps (default 2).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
bearPut(symbol, exchange, producttype, account, group, lots, quantity, width, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Bear put spread — buy a put at the money and sell a put 'width' strikes out. Use direction "SELL" to reverse.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
width (int) : (series int) Distance between the two strikes, in strike steps (default 2).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
bullPut(symbol, exchange, producttype, account, group, lots, quantity, width, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Bull put spread (credit) — sell a put at the money and buy a put 'width' strikes out. Use direction "SELL" to reverse.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
width (int) : (series int) Distance between the two strikes, in strike steps (default 2).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
bearCall(symbol, exchange, producttype, account, group, lots, quantity, width, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Bear call spread (credit) — sell a call at the money and buy a call 'width' strikes out. Use direction "SELL" to reverse.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
width (int) : (series int) Distance between the two strikes, in strike steps (default 2).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
ironCondor(symbol, exchange, producttype, account, group, lots, quantity, width, wing, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Iron condor — sell a call and a put 'width' strikes out, and buy a call and a put 'width'+'wing' strikes out as protection. direction "BUY" builds this credit condor; "SELL" reverses it.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
width (int) : (series int) How far out the sold legs sit, in strike steps (default 2).
wing (int) : (series int) Extra distance out to the protective legs, in strike steps (defaults to width).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
ironFly(symbol, exchange, producttype, account, group, lots, quantity, wing, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Iron fly — sell a call and a put at the money, and buy a call and a put 'wing' strikes out as protection. direction "BUY" builds this credit fly; "SELL" reverses it.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
wing (int) : (series int) How far out the protective legs sit, in strike steps (default 2).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
leg(optiontype, strike, tradetype, multiplier)
Build one option leg string for use with multiLeg(), e.g. atw.leg("CE", "ATM+2", "SELL", 2) -> "CE ATM+2 SELL x2".
Parameters:
optiontype (string) : (series string) CE for a call, PE for a put.
strike (string) : (series string) ATM, ATM+2, OTM2, ITM1, or an exact strike like "24500".
tradetype (string) : (series string) BUY or SELL for this leg.
multiplier (int) : (series int) Size multiplier for this leg (default 1).
Returns: (series string) The leg descriptor.
multiLeg(symbol, exchange, producttype, legs, account, group, lots, quantity, expiry, ordertype, price, onlegfailure, risk, extra)
Build an alert for a fully custom multi-leg order from a list of legs (1 to 10) made with leg(). Set exactly one of account/group and exactly one of lots/quantity.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
legs (array) : (array) The legs, e.g. array.from(atw.leg("PE","ATM-2","SELL"), atw.leg("PE","ATM-6","BUY")).
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
riskLimits(maxloss, forceexit, entrywindow, blockExpiry)
Build a risk-limits block to attach to any order via risk=. Example: risk=atw.riskLimits(maxloss=5000). These are your own limits; see the Alert Automation guide for exactly how each one behaves.
Parameters:
maxloss (float) : (series float) Maximum day loss for the account, in your account currency.
forceexit (string) : (series string) A square-off time as "HH:mm", e.g. "15:15".
entrywindow (string) : (series string) An allowed entry-time window "HH:mm-HH:mm", e.g. "09:30-14:30".
blockExpiry (bool) : (series bool) Block new entries on the instrument's expiry day.
Returns: (series string) The risk lines, ready to pass as risk=. 腳本庫

StrategyWebhookJsonOverview
Open-source Pine library that builds JSON strings for strategy alert_message webhooks. Use it when a strategy should send structured trade signals to an external webhook receiver instead of plain alert text.
What it does
The library formats JSON payloads for three actions:
• open — new position (side, volume, stop loss, take profit, symbol, price)
• close — close by signal id
• modify — update stop loss and take profit for an existing signal id
Each payload includes secret, signalId, action, and symbol (from syminfo.ticker). Optional fields are omitted when not applicable. Strings are JSON-escaped.
Delivery modes (Mode enum)
• LocalOnly — returns an empty string (no JSON in alert_message)
• CloudOnly — returns JSON for webhook alerts
• Both — same as CloudOnly for alert_message output
How to use
1. Import the library into your strategy.
2. Call init(secret, mode) once and store the result in a var Config.
3. Pass the result of openMsg, closeMsg, or modifyMsg to strategy.entry, strategy.close, or strategy.exit via the alert_message parameter.
4. Create a strategy alert and set the webhook URL in TradingView alert settings (TradingView Plus or higher required for webhook URL field).
Example pattern
var cfg = init("YOUR_SECRET", Mode.CloudOnly)
strategy.entry("Long", strategy.long,
alert_message = openMsg(cfg, "Long", "buy", 0.1, sl, tp))
strategy.close("Long",
alert_message = closeMsg(cfg, "Long"))
Requirements
• Pine Script v6
• A strategy script (not an indicator)
• Webhook URL configured on the alert, not inside this library
Notes
signalId should be stable and unique per logical order so close and modify can target the correct open. The secret is included in the JSON body for authentication at the receiver. 腳本庫

OrderTicketBuilderLibrary "OrderTicketBuilder"
Assembles broker order ticket payloads as JSON strings.
BuildTicket(licenseId, symbol, action, orderType, tradeType, size, price, tp, sl, risk, trailPrice, trailOffset)
BuildTicket assembles a JSON order ticket string for downstream execution.
Parameters:
licenseId (string) : License identifier
symbol (string) : Symbol to trade
action (string) : "MRKT" or "PENDING"
orderType (string) : "BUY" or "SELL"
tradeType (string) : "SPREAD" or "SINGLE"
size (float) : (Optional) Trade size
price (float) : (Optional) Price for pending orders
tp (float) : (Optional) Take profit
sl (float) : (Optional) Stop loss
risk (float) : (Optional) Percent risk if size unspecified
trailPrice (float) : (Optional) Trailing-stop trigger price
trailOffset (float) : (Optional) Trailing-stop offset
Returns: JSON order ticket string 腳本庫

TPOLibLibrary "TPOLib"
TPOLib — Classical Time Price Opportunity (TPO) primitives.
Provides tick/row conversion, POC/Value Area calculation, TPO letter encoding,
Initial Balance tracking, and profile shape classification.
Note: Function bodies for f_price_to_tick, f_tick_to_row, f_row_to_price,
f_calc_row_ticks, f_poc_from_vals, f_value_area, and f_find_key_sorted are
copied from TPOSmartMoneyLib/3 (immutable on TradingView). No extraction or
migration - legacy consumers unaffected.
Architecture: L0 (no library dependencies, uses ta.* and math.* primitives only)
f_price_to_tick(p)
Convert price to tick
Parameters:
p (float) : Price value
Returns: Tick value
f_tick_to_row(t, row_ticks_in)
Convert tick to row
Parameters:
t (int) : Tick value
row_ticks_in (int) : Number of ticks per row
Returns: Row index
f_row_to_price(row, row_ticks_in)
Convert row to price (midpoint)
Parameters:
row (int) : Row index
row_ticks_in (int) : Number of ticks per row
Returns: Price at row midpoint
f_calc_row_ticks(natr_ref, row_gran_mult)
Calculate dynamic row size based on normalized ATR
Parameters:
natr_ref (float) : Daily normalized ATR reference value
row_gran_mult (float) : Row granularity multiplier
Returns: Number of ticks per row
f_poc_from_vals(keys, vals)
Calculate Point of Control from volume distribution
Parameters:
keys (array) : Sorted array of row keys
vals (array) : Array of volume values
Returns: POC row key
f_value_area(keys, vals, poc_key, va_pct)
Calculate Value Area from volume distribution
Parameters:
keys (array) : Sorted array of row keys
vals (array) : Array of volume values
poc_key (int) : POC row key
va_pct (float) : Value Area percentage (typically 0.70)
Returns: Tuple of
f_find_key_sorted(keys, target)
Find key in sorted array using binary search
Parameters:
keys (array) : Sorted array of keys
target (int) : Target key to find
Returns: Index of key, or -1 if not found
f_tpo_letter_idx(bracket_idx)
Get TPO letter for bracket index (A-Z, then AA-AZ, etc.)
Parameters:
bracket_idx (int) : Bracket index (0-based)
Returns: Letter string
f_initial_balance_from_brackets(brackets, ib_bracket_count, row_ticks)
Calculate Initial Balance from first N brackets
Parameters:
brackets (array) : Array of TPOBracket (sorted by time)
ib_bracket_count (int) : Number of brackets in IB period (typically 2 for 1hr)
row_ticks (int) : Number of ticks per row
Returns: InitialBalance
f_detect_tpo_singles(brackets)
Detect TPO singles (rows with only one TPO print)
Parameters:
brackets (array) : Array of TPOBracket
Returns: Array of row indices that are singles
f_classify_profile(poc, val, vah, range_low, range_high)
Classify profile shape based on POC position and VA width
Parameters:
poc (int) : POC row
val (int) : VAL row
vah (int) : VAH row
range_low (int) : Lowest row in profile
range_high (int) : Highest row in profile
Returns: ProfileShape
TPOBracket
TPO bracket (single time period at a price level)
Fields:
letter (series string) : Letter identifier (A-Z for 30min brackets in RTH session)
row (series int) : Row index (price level)
volume (series float) : Volume accumulated in this bracket
ValueArea
Value Area calculation result
Fields:
poc (series int) : Point of Control (row with highest volume)
val (series int) : Value Area Low (row)
vah (series int) : Value Area High (row)
poc_volume (series float) : Volume at POC
va_volume (series float) : Total volume in Value Area
InitialBalance
Initial Balance (first hour of RTH session)
Fields:
ib_high (series float) : Highest price in IB period
ib_low (series float) : Lowest price in IB period
ib_range (series float) : IB range (high - low)
extended_up (series bool) : IB extended upward
extended_down (series bool) : IB extended downward
ProfileShape
Profile shape classification
Fields:
shape (series string) : "normal", "b_shape", "p_shape", "d_shape", "neutral"
poc_position (series float) : POC position relative to range (0.0=low, 1.0=high)
va_width (series float) : Value Area width as % of total range 腳本庫

SimTradeIndicatorsLibrary "SimTradeIndicators"
SimTrade indicator library — exact parity with Python pipeline (TA-Lib + pandas_ta).
Each function replicates the formula used in base.py / signals.py so that
TradingView charts match the GPU hunt / validator / live engine outputs.
Formula sources:
TA-Lib → RSI, ATR, EMA, MACD, CCI, Stoch, WILLR, MFI, ADX, PSAR, OBV, BBANDS, AROON, PPO, AD
pandas_ta → SuperTrend, Vortex, Ichimoku, Donchian, HMA, TSI, CMF, EFI, CHOP, Heikin-Ashi
Manual → Keltner (EMA+ATR Wilder), TTM Squeeze, Chandelier Exit, VWAP reset, Pivot Points
Known intentional deviations (documented):
- Stoch trigger 11 uses Full %D (double-smoothed), not single %K
- OBV filter 206 uses windowed 800-bar OBV (GPU-aligned, not cumulative)
- Pivot Points use rolling window, not session-based (see pivot_pp notes)
- EMA has longer warmup in TA-Lib (~50 bars unstable period) vs TW (from bar 1); steady-state identical
smma(src, length)
SMMA / Wilder RMA. alpha = 1/length. Matches talib "RMA" used for ATR/RSI internally.
Parameters:
src (float) : Source series
length (simple int) : Period
Returns: RMA value
hma(src, length)
HMA (Hull Moving Average). HMA = WMA(2·WMA(N/2) − WMA(N), √N). Matches pandas_ta.hma.
Parameters:
src (float) : Source series
length (simple int) : Period
Returns: HMA value
dema(src, length)
DEMA (Double EMA) = 2·EMA − EMA(EMA). Matches talib.DEMA.
Parameters:
src (float) : Source series
length (simple int) : Period
Returns: DEMA value
tema(src, length)
TEMA (Triple EMA) = 3·EMA − 3·EMA² + EMA³. Matches talib.TEMA.
Parameters:
src (float) : Source series
length (simple int) : Period
Returns: TEMA value
atr_wilder(length)
ATR using Wilder RMA. Identical to talib.ATR and TW ta.atr.
Parameters:
length (simple int) : Period (default 14)
Returns: ATR value
atr_percentile_pct(length, lookback)
ATR percentile rank over a rolling window. Matches Python vol_filter 201.
Logic: for each bar count how many ATR values in are <= current ATR,
return that fraction as 0..100. Warmup bars (< lookback + length) return 50.0.
Parameters:
length (simple int) : ATR period / Wilder RMA (default 14). Matches params .
lookback (simple int) : Rolling window for percentile rank (default 30). Matches params .
Returns: Percentile rank 0..100 (pass filter when >= pct_min / params )
bbands(src, length, mult)
Bollinger Bands. Returns .
mid = SMA. Matches talib.BBANDS (matype=0 = SMA).
Parameters:
src (float) : Source series (typically close)
length (simple int) : Period (default 20)
mult (float) : Standard deviation multiplier (default 2.0)
Returns:
bb_pctb(src, length, mult)
Bollinger Bands %B = (close − lower) / (upper − lower).
Returns 0.5 during warmup (matches Python _nan50 fallback in base.bb_pctb).
Parameters:
src (float) : Source series
length (simple int) : Period (default 20)
mult (float) : Multiplier (default 2.0)
Returns: %B value
bb_width_x1000(src, length, mult)
BB bandwidth × 1000 / mid. Used by vol filter 202 (bb_width).
Parameters:
src (float) : Source series
length (simple int) : Period (default 20)
mult (float) : Multiplier (default 2.0)
Returns: (upper − lower) / |mid| × 1000
keltner(ema_period, atr_period, mult)
Keltner Channel. mid = EMA(close, ema_period), band = ATR(atr_period) Wilder RMA.
IMPORTANT: this is the TW-standard formula. NOT pandas_ta kc(mamode="ema") which uses EMA(TR).
That version produces ~40% narrower bands than TW. This library uses the correct RMA(ATR) band.
Parameters:
ema_period (simple int) : EMA period for midline (default 20)
atr_period (simple int) : ATR period for band width (default 10)
mult (float) : ATR multiplier (default 1.5)
Returns:
keltner_width_x1000(period, mult)
Keltner Channel bandwidth × 1000 / mid. Used by vol filter 204 (keltner_width).
Parameters:
period (simple int) : Period for both EMA and ATR (default 20)
mult (float) : ATR multiplier (default 1.5)
Returns: (upper − lower) / |mid| × 1000
choppiness(length)
Choppiness Index. CHOP = 100·log10(Σ ATR1 / (HH − LL)) / log10(N).
Matches pandas_ta.chop and TW built-in CHOP. Returns 50.0 during warmup.
Parameters:
length (simple int) : Period (default 14)
Returns: CHOP value
rsi_val(src, length)
RSI using Wilder RMA. Identical to talib.RSI and TW ta.rsi.
Returns 50.0 during warmup (matches Python _nan50 fallback).
Parameters:
src (float) : Source series (typically close)
length (simple int) : Period (default 14)
Returns: RSI value
cci_val(length)
CCI = (typical − SMA(typical)) / (0.015 · mean_deviation). Matches talib.CCI.
Returns 0.0 during warmup (matches Python _nan0 fallback).
Parameters:
length (simple int) : Period (default 20)
Returns: CCI value
stoch_raw_k(k_period)
Stochastic raw %K (no smoothing). Matches base.stoch_k (talib slowk_period=1).
NOTE: TW ta.stoch default smooths %K with SMA(3). This is the unsmoothed fast %K.
Used by filter 103 (stoch_k_below).
Parameters:
k_period (simple int) : Lookback period (default 14)
Returns: Raw %K (50.0 during warmup)
stoch_full_d(k_period, d_period)
Full Stochastic %D = SMA(SMA(raw%K, d_period), d_period). Matches talib.STOCH output.
Used by trigger 11 (stoch_cross). NOT single-smoothed %K — lag is +2-3 bars vs TW default.
Parameters:
k_period (simple int) : Raw %K lookback (default 14)
d_period (simple int) : Smoothing applied twice (default 3)
Returns: Full Stochastic %D (50.0 during warmup)
williams_r(length)
Williams %R = −100 · (HH − close) / (HH − LL). Matches talib.WILLR.
Range: −100 to 0. Returns −50.0 during warmup.
Parameters:
length (simple int) : Period (default 14)
Returns: Williams %R value
mfi_val(length)
MFI (Money Flow Index). Matches talib.MFI.
Returns 50.0 during warmup.
Parameters:
length (simple int) : Period (default 14)
Returns: MFI value
macd_val(src, fast, slow, signal_period)
MACD. Returns . Identical to talib.MACD.
All NaN values replaced with 0.0 (matches Python _nan0).
Parameters:
src (float) : Source series
fast (simple int) : Fast EMA period (default 12)
slow (simple int) : Slow EMA period (default 26)
signal_period (simple int) : Signal EMA period (default 9)
Returns:
ppo_val(src, fast, slow)
PPO = (EMA(fast) − EMA(slow)) / EMA(slow) × 100. Matches talib.PPO.
Returns 0.0 during warmup.
Parameters:
src (float) : Source series
fast (simple int) : Fast period (default 12)
slow (simple int) : Slow period (default 26)
Returns: PPO value
tsi_val(src, long_period, short_period)
TSI (True Strength Index). Matches pandas_ta.tsi parameter order.
TSI = 100 · EMA(EMA(Δclose, slow), fast) / EMA(EMA(|Δclose|, slow), fast)
slow is the OUTER (first) smoothing, fast is the INNER (second). Same as TW.
Parameters:
src (float) : Source series
long_period (simple int) : Outer (slow) EMA period (default 25)
short_period (simple int) : Inner (fast) EMA period (default 13)
Returns: TSI value (0.0 during warmup)
adx_di(length)
ADX + DI lines. Returns . Matches talib.ADX/PLUS_DI/MINUS_DI.
Uses Wilder RMA (identical to TW ta.dmi / ta.adx).
Parameters:
length (simple int) : Period (default 14)
Returns: — 0.0 during warmup
supertrend_val(length, mult)
SuperTrend direction and value. Matches pandas_ta.supertrend (RMA ATR).
Returns : direction = 1 (bull) or −1 (bear).
Parameters:
length (simple int) : ATR period (default 10)
mult (float) : ATR multiplier (default 3.0)
Returns:
psar_val(start, inc, max_af)
Parabolic SAR. Returns . Matches talib.SAR.
direction = 1 if close > SAR (bull), −1 bear.
Parameters:
start (simple float) : Initial AF / step (default 0.02)
inc (simple float) : AF increment per bar (default 0.02)
max_af (simple float) : Maximum AF cap (default 0.2)
Returns:
aroon_val(length)
Aroon Up and Down. Returns . Matches talib.AROON.
ta.aroon does not exist in Pine v6 — computed manually:
Aroon Up = (length − bars since highest high over length+1 bars) / length × 100
Aroon Down = (length − bars since lowest low over length+1 bars) / length × 100
This is identical to talib.AROON and TradingView's built-in Aroon indicator.
Returns 50.0 during warmup (matches Python _nan50).
Parameters:
length (simple int) : Period (default 25)
Returns:
vortex_diff(length)
Vortex Indicator difference (VI+ − VI−). Matches base.vortex.
Positive = bullish regime, negative = bearish. Returns 0.0 during warmup.
Parameters:
length (simple int) : Period (default 14)
Returns: VI+ minus VI−
linreg_slope(src, length)
Linear Regression Slope. Matches talib.LINEARREG_SLOPE exactly.
Computes OLS slope for x = 0..N-1 (oldest=0, newest=N-1).
Positive = uptrend, negative = downtrend. Returns 0.0 during warmup.
Parameters:
src (float) : Source series
length (simple int) : Period (default 20)
Returns: Slope value
obv_val()
OBV (On-Balance Volume). Cumulative. Matches talib.OBV.
Returns: Cumulative OBV
vwap_reset(reset_bars)
VWAP with periodic session reset. Matches base.vwap(reset_bars).
reset_bars=24 on H1 ≈ daily VWAP (crypto 24/7). reset_bars=6 on H4 ≈ daily.
reset_bars=0 uses TW built-in ta.vwap (session anchor).
Parameters:
reset_bars (simple int) : Bars per session (0 = TW session anchor, 24 = H1 daily, 6 = H4 daily)
Returns: VWAP value
cmf_val(length)
CMF (Chaikin Money Flow) = Σ(CLV·vol) / Σvol. Matches pandas_ta.cmf.
CLV = ((close − low) − (high − close)) / (high − low). Returns 0.0 during warmup.
Parameters:
length (simple int) : Period (default 20)
Returns: CMF value (−1 to 1)
ad_val()
Accumulation/Distribution Line. Matches talib.AD.
Returns: Cumulative A/D value
efi_val(length)
EFI (Elder Force Index). EFI = EMA((close − close ) · volume, length).
Matches pandas_ta.efi. Returns 0.0 during warmup.
Parameters:
length (simple int) : EMA period (default 13)
Returns: EFI value
ichimoku_val(tenkan_period, kijun_period, senkou_b_period)
Ichimoku lines. Returns .
Matches pandas_ta.ichimoku with CORRECTED column mapping (ISA, ISB, ITS, IKS, ICS).
senkou_a/b are plotted 26 bars AHEAD in TW — values here are for current bar alignment.
Parameters:
tenkan_period (simple int) : Tenkan-sen period (default 9)
kijun_period (simple int) : Kijun-sen period (default 26)
senkou_b_period (simple int) : Senkou B period (default 52)
Returns:
donchian_val(length)
Donchian Channel. Returns .
upper = highest(high, N), lower = lowest(low, N). Matches pandas_ta.donchian.
NOTE: lookback may differ ±1 bar from TA-Lib; consistent across all pipeline stages.
Trigger 37 (donchian_break) compares close > upper — use upper in Pine.
Parameters:
length (simple int) : Period (default 20)
Returns:
ttm_squeeze_val(bb_period, bb_mult, kc_period, kc_mult)
TTM Squeeze. Returns .
squeeze_on: BB inside KC (volatility compression).
momentum: ta.linreg(close − (donchian_mid + SMA) / 2, bb_period)
EXACT match with John Carter formula and base.ttm_squeeze after fix.
Parameters:
bb_period (simple int) : BB period (default 20)
bb_mult (float) : BB multiplier (default 2.0)
kc_period (simple int) : KC period — same for EMA midline and ATR band (default 20)
kc_mult (float) : KC ATR multiplier (default 1.5)
Returns:
chandelier_val(period, mult)
Chandelier Exit. Returns .
long_exit = highest(high, period) − mult · ATR(period)
short_exit = lowest(low, period) + mult · ATR(period)
Exact match with base.chandelier_exit. Both include current bar in rolling max/min.
Trigger 45 fires when close crosses long_exit or short_exit (up = bull, down = bear).
Parameters:
period (simple int) : Lookback and ATR period (default 22)
mult (float) : ATR multiplier (default 3.0)
Returns:
ha_close()
Heikin Ashi close. HA_close = (open + high + low + close) / 4. Matches pandas_ta.ha.
Returns: HA close value
ha_open()
Heikin Ashi open. HA_open = (HA_open + HA_close ) / 2.
Trigger 48 fires on HA candle color flip: HA_close vs HA_open.
Returns: HA open value
pivot_pp(period)
Rolling Pivot Point (floor method). Matches base.pivot_points.
pp = (max(high, period bars ago) + min(low, period bars ago) + close ) / 3
NOTE: Rolling window, NOT session-based. H1 default period=24 ≈ 1 day (crypto 24/7).
For H4 set period=6 (6 × 4h = 1 day). TW Pivot Points use session H/L/C — differs.
Parameters:
period (simple int) : Rolling lookback (default 24)
Returns: Pivot point value
pivot_r1_s1(period)
Rolling R1 and S1 levels. Matches base.pivot_points r1/s1.
r1 = 2·pp − lowest_low, s1 = 2·pp − highest_high
Parameters:
period (simple int) : Rolling lookback (default 24)
Returns: 腳本庫

NeuraLib Expansion: Advanced Model LayersNeuraLib_Models is the companion model expansion for NeuraLib .
NeuraLib provides the runtime: tensors, graph execution, datasets, scalers, losses, optimizers, training, inference, and validation tools. NeuraLib_Models builds on that foundation with higher-level neural architectures that are difficult and repetitive to write by hand.
The purpose of this expansion is to keep the main NeuraLib runtime clean, compact, and general, while giving researchers ready-to-use model families for sequence learning, attention, temporal pattern extraction, and Reinforcement Learning workflows.
----------------------------------------------------------------------------------------------------------------
🔷 HOW IT FITS INTO NEURALIB
NeuraLib_Models is built entirely on top of the public NeuraLib API. It does not replace the main runtime and it does not introduce a separate training engine.
After importing NeuraLib_Models, its fluent methods become available directly on NeuraLib `Sequential` models. The expansion alias can remain unused in the layer chain.
//@version=6
indicator("NeuraLib Models Quick Start", overlay = false, calc_bars_count = 600)
import Alien_Algorithms/NeuraLib/1 as nl
import Alien_Algorithms/NeuraLib_Models/1 as models
var nl.Sequential model = nl.sequential("advanced_model")
var float qLong = na
var float qFlat = na
var float qShort = na
if barstate.isfirst
model := model
.input(array.from(8), "sequence")
.temporalConvStack(4, 2, 2, 2, 1, 1, nl.ActivationKind.relu, 0.0, "temporal")
.globalAvgPool1d(3, 2, "pool")
.duelingQHead(4, 3, nl.ActivationKind.relu, "dueling_head")
.build(nl.rng(7))
float ret0 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret1 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret2 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret3 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float atrValue = ta.atr(14)
float atr0 = close == 0.0 ? 0.0 : atrValue / close
float atr1 = close == 0.0 ? 0.0 : atrValue / close
float atr2 = close == 0.0 ? 0.0 : atrValue / close
float atr3 = close == 0.0 ? 0.0 : atrValue / close
bool ready = not na(ret3) and not na(atr3)
if ready
nl.Tensor state = nl.vector(array.from(ret3, atr3, ret2, atr2, ret1, atr1, ret0, atr0), "state_window")
nl.Tensor qValues = model.predict(state)
qLong := qValues.get1d(0)
qFlat := qValues.get1d(1)
qShort := qValues.get1d(2)
plot(qLong, "Q long", color = color.lime, linewidth = 2)
plot(qFlat, "Q flat", color = color.gray)
plot(qShort, "Q short", color = color.red, linewidth = 2)
hline(0.0, "Zero", color = color.new(color.gray, 70))
The model is still a normal NeuraLib model. You still call `.compile()`, `.trainOnBatch()`, `.predict()`, `.evaluate()`, `.getWeightsArray()`, and `.softUpdateFrom()` from the main library.
----------------------------------------------------------------------------------------------------------------
🔷 WHY THIS EXPANSION EXISTS
The main NeuraLib library is the foundation. It exposes a graph engine powerful enough to create custom architectures, but repeatedly building LSTM gates, attention projections, residual blocks, Conv1D stacks, or Transformer paths from raw graph operations would be too verbose for everyday research.
NeuraLib_Models packages those patterns into readable blocks:
Temporal models : Conv1D blocks, temporal convolution stacks, global average pooling, and global max pooling for flattened sequence inputs.
Recurrent models : LSTM and GRU blocks for compact sequence memory.
Attention models : Self-attention, multi-head self-attention, cross-attention, Transformer encoder blocks, Transformer encoder stacks, and Transformer decoder blocks.
Residual models : Residual dense blocks for deeper feedforward paths.
Reinforcement Learning heads : Q-head blocks and dueling Q-heads for action-value style outputs.
Replay utilities : Deterministic Prioritized Experience Replay for reproducible Pine research.
Sequence helpers : Positional encoding for token, sequence, and attention workflows.
----------------------------------------------------------------------------------------------------------------
🔷 PRACTICAL EXAMPLES
🔸 Temporal Conv Model With Dueling Q-Head
This pattern is useful when a flattened sequence contains recent market states and the output represents action values.
//@version=6
indicator("NeuraLib Models Temporal Q Example", overlay = false, calc_bars_count = 600)
import Alien_Algorithms/NeuraLib/1 as nl
import Alien_Algorithms/NeuraLib_Models/1 as models
var nl.Sequential qModel = nl.sequential("temporal_q_model")
var nl.WindowDataset qDataset = nl.windowDataset(8, 3, 400, "q_rows")
var float qDown = na
var float qNeutral = na
var float qUp = na
var float qLoss = na
if barstate.isfirst
nl.CompileConfig cfg = nl.compileConfig()
cfg := cfg
.presetQValues()
.optimizer(nl.adamW(0.001))
.withTrainingGate(true)
qModel := qModel
.input(array.from(8), "state_window")
.temporalConvStack(4, 2, 2, 2, 1, 1, nl.ActivationKind.relu, 0.0, "temporal")
.globalAvgPool1d(3, 2, "pool")
.duelingQHead(4, 3, nl.ActivationKind.relu, "dueling_head")
.compile(cfg)
qDataset := qDataset
.setInputScaler(nl.ScalerKind.zScore)
.setTargetScaler(nl.ScalerKind.none)
float ret0 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret1 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret2 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret3 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret4 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float atrValue = ta.atr(14)
float atr0 = close == 0.0 ? 0.0 : atrValue / close
float atr1 = close == 0.0 ? 0.0 : atrValue / close
float atr2 = close == 0.0 ? 0.0 : atrValue / close
float atr3 = close == 0.0 ? 0.0 : atrValue / close
float atr4 = close == 0.0 ? 0.0 : atrValue / close
bool rowReady = not na(ret4) and not na(atr4)
if rowReady
array features = array.from(ret4, atr4, ret3, atr3, ret2, atr2, ret1, atr1)
float downTarget = math.max(-ret0, 0.0)
float neutralTarget = math.max(0.002 - math.abs(ret0), 0.0)
float upTarget = math.max(ret0, 0.0)
qDataset := qDataset.pushRow(features, array.from(downTarget, neutralTarget, upTarget))
if qDataset.ready(48)
if barstate.islastconfirmedhistory
nl.Batch train = qDataset.trainBatch(12)
qModel := qModel.trainOnBatch(train.inputTensor, train.targetTensor)
qLoss := qModel.trainStats.lastLoss
nl.Tensor liveState = nl.vector(array.from(ret3, atr3, ret2, atr2, ret1, atr1, ret0, atr0), "live_state")
nl.Tensor scaledState = qDataset.scaleInput(liveState)
nl.Tensor qValues = qModel.predict(scaledState)
qDown := qValues.get1d(0)
qNeutral := qValues.get1d(1)
qUp := qValues.get1d(2)
plot(qDown, "Q down", color = color.red, linewidth = 2)
plot(qNeutral, "Q neutral", color = color.gray)
plot(qUp, "Q up", color = color.lime, linewidth = 2)
plot(qLoss, "Training loss", color = color.orange)
hline(0.0, "Zero", color = color.new(color.gray, 70))
Input shape `array.from(8)` represents a flattened 4 step by 2 feature sequence. The temporal stack extracts short sequence structure, pooling compresses the sequence, and the dueling head separates value and advantage paths before producing action scores. The example trains only on the last confirmed historical bar so it remains safe to paste onto long charts.
🔸 Transformer Encoder For Token Rows
Attention models are useful when each row is a token or time step, and each column is a feature dimension.
//@version=6
indicator("NeuraLib Models Transformer Encoder Example", overlay = false, calc_bars_count = 600)
import Alien_Algorithms/NeuraLib/1 as nl
import Alien_Algorithms/NeuraLib_Models/1 as models
var nl.Sequential encoder = nl.sequential("encoder_model")
var float tokenSignal = na
var float tokenContext = na
var float tokenVolatility = na
if barstate.isfirst
encoder := encoder
.input(array.from(4), "tokens")
.multiHeadSelfAttention(4, 2, true, "mha")
.transformerEncoder(4, true, 2, nl.ActivationKind.geluApprox, "encoder", 0.05, 2)
.build(nl.rng(11))
float emaValue = ta.ema(close, 21)
float atrValue = ta.atr(14)
float ret0 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret1 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret2 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret3 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float emaGap0 = emaValue == 0.0 ? 0.0 : close / emaValue - 1.0
float emaGap1 = emaValue == 0.0 ? 0.0 : close / emaValue - 1.0
float emaGap2 = emaValue == 0.0 ? 0.0 : close / emaValue - 1.0
float emaGap3 = emaValue == 0.0 ? 0.0 : close / emaValue - 1.0
float atr0 = close == 0.0 ? 0.0 : atrValue / close
float atr1 = close == 0.0 ? 0.0 : atrValue / close
float atr2 = close == 0.0 ? 0.0 : atrValue / close
float atr3 = close == 0.0 ? 0.0 : atrValue / close
bool ready = not na(ret3) and not na(emaGap3) and not na(atr3)
if ready
nl.Tensor tokens = nl.vector(array.from(
ret3, emaGap3, atr3, -1.0,
ret2, emaGap2, atr2, -0.33,
ret1, emaGap1, atr1, 0.33,
ret0, emaGap0, atr0, 1.0), "tokens").reshape(array.from(4, 4))
nl.Tensor encoded = encoder.predict(tokens)
tokenSignal := encoded.get1d(12)
tokenContext := encoded.get1d(13)
tokenVolatility := encoded.get1d(14)
plot(tokenSignal, "Latest token signal", color = color.aqua, linewidth = 2)
plot(tokenContext, "Latest token context", color = color.purple)
plot(tokenVolatility, "Latest token volatility", color = color.orange)
hline(0.0, "Zero", color = color.new(color.gray, 70))
In this example, each input row has 4 features. `headCount` is 2, so the model dimension is split into two attention heads.
Attention rule: `modelDim` must be divisible by `headCount`, and the current implementation supports up to 8 heads.
🔸 Prioritized Experience Replay
Prioritized Experience Replay stores examples with priorities, then returns reproducible weighted samples. This is especially useful for Reinforcement Learning experiments where high-error transitions should be revisited more often.
//@version=6
indicator("NeuraLib Models PER Example", overlay = false, calc_bars_count = 1200)
import Alien_Algorithms/NeuraLib/1 as nl
import Alien_Algorithms/NeuraLib_Models/1 as models
var models.PrioritizedReplayBuffer replay = models.prioritizedReplayBuffer(4, 2, 300, "replay")
var nl.Sequential replayModel = nl.sequential("replay_q_model")
var float replayLoss = na
var float firstImportanceWeight = na
var float replayRows = na
if barstate.isfirst
nl.CompileConfig cfg = nl.compileConfig()
cfg := cfg
.presetQValues()
.optimizer(nl.adamW(0.001))
.trainEveryCall()
replayModel := replayModel
.input(array.from(4), "state")
.dense(8, nl.ActivationKind.relu, "hidden")
.qHead(2, nl.ActivationKind.linear, "q_values")
.compile(cfg)
float rsiValue = ta.rsi(close, 14)
float emaValue = ta.ema(close, 21)
float atrValue = ta.atr(14)
float atrPct = close == 0.0 ? 0.0 : atrValue / close
float momentum = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float nextReturn = na(close ) ? 0.0 : nl.nextReturnValue(close , close)
bool rowReady = not na(rsiValue ) and not na(emaValue ) and not na(atrPct ) and not na(momentum )
if rowReady
float prevEma = emaValue
float priceVsEma = prevEma == 0.0 ? 0.0 : close / prevEma - 1.0
array stateFeatures = array.from(rsiValue / 100.0, priceVsEma, atrPct , momentum )
array targetValues = array.from(math.max(-nextReturn, 0.0), math.max(nextReturn, 0.0))
float priority = math.abs(nextReturn) + 0.0001
replay := replay.pushExperience(stateFeatures, targetValues, priority)
replayRows := float(replay.size())
if replay.ready(32)
models.PrioritizedReplaySample sample = replay.sampleBatch(32, 0.6, 0.4, 17)
replayModel := replayModel.trainOnBatch(sample.batch.inputTensor, sample.batch.targetTensor)
replayLoss := replayModel.trainStats.lastLoss
firstImportanceWeight := sample.weightArray.size() > 0 ? sample.weightArray.get(0) : na
if sample.indexArray.size() > 0
replay := replay.updatePriority(sample.indexArray.get(0), replayLoss + 0.0001)
plot(replayLoss, "Replay training loss", color = color.orange, linewidth = 2)
plot(firstImportanceWeight, "First sample weight", color = color.aqua)
The returned sample includes:
batch : A normal NeuraLib `Batch` containing sampled inputs and targets.
indexArray : Logical replay indices that can be passed back to `updatePriority()`.
weightArray : Normalized importance weights for custom loss weighting or diagnostics.
sampleRows : Number of sampled rows.
PER sampling is deterministic for a given buffer, `batchSize`, and `seed`. That makes Pine tests and live research easier to reproduce.
----------------------------------------------------------------------------------------------------------------
🔷 MODEL FAMILIES
🔸 Residual Dense Blocks
`residualDense()` adds a feedforward residual block. Residual paths help preserve information through deeper models and reduce the chance that a dense stack destroys useful features too early.
🔸 Conv1D And Temporal Convolution Stacks
`conv1d()` and `temporalConvStack()` operate on flattened sequence inputs. A sequence with `timeSteps = 4` and `featureCount = 2` is represented as 8 input features. These blocks are useful for local temporal structure, short rolling windows, feature rhythm, and compact pattern extraction.
🔸 Global Pooling
`globalAvgPool1d()` and `globalMaxPool1d()` compress flattened sequence outputs into feature-level summaries. Average pooling captures broad sequence behavior, while max pooling emphasizes the strongest activation per feature.
🔸 LSTM And GRU Blocks
`lstm()` and `gru()` provide recurrent sequence memory over flattened time-series inputs. They are useful when the order of recent states matters more than a single snapshot.
🔸 Attention And Transformers
`selfAttention()`, `multiHeadSelfAttention()`, `crossAttention()`, `transformerEncoder()`, `transformerEncoderStack()`, and `transformerDecoder()` bring attention-style modeling into Pine. They are designed for compact token matrices, packed target-memory layouts, and small Transformer-style research models that fit TradingView limits.
🔸 Q-Heads And Dueling Q-Heads
`qHeadBlock()` creates action-value style outputs. `duelingQHead()` splits the model into value and advantage branches, then recombines them into Q-values. This is useful when you want the model to estimate both the overall state value and the relative value of each action.
🔸 Positional Encoding
`pushPositionalEncoding()` adds sinusoidal position features to a NeuraLib `FeatureBuilder`. This helps attention-style models distinguish where a token or time step sits in a sequence.
----------------------------------------------------------------------------------------------------------------
🔷 FEATURE QUICK REFERENCE
Built on NeuraLib : Uses the main NeuraLib graph, tensor, training, optimizer, dataset, and inference runtime.
Fluent API : Adds methods directly to NeuraLib `Sequential` models after import.
Block factories : Provides standalone `GraphBlock` factories for users who want lower-level composition.
Temporal modeling : Conv1D, temporal convolution stacks, and 1D pooling.
Recurrent modeling : LSTM and GRU sequence blocks.
Attention modeling : Self-attention, multi-head self-attention, cross-attention, encoders, encoder stacks, and decoders.
Reinforcement Learning support : Q-heads, dueling Q-heads, target-model soft updates through NeuraLib, and Prioritized Experience Replay.
Reproducible replay : PER sampling is deterministic for a given seed.
Shape guardrails : Advanced builders validate expected model feature counts and attention head compatibility.
----------------------------------------------------------------------------------------------------------------
🔷 IMPORTANT USAGE NOTES
Import order matters : Import `NeuraLib` first, then `NeuraLib_Models`.
The alias can be unused : The imported expansion registers methods on NeuraLib types, so `.lstm()`, `.gru()`, `.transformerEncoder()`, and similar methods can be called in the model chain.
Keep models compact : Pine Script has execution limits. Start with small hidden sizes, short sequences, and low head counts.
Control chart history : Use `calc_bars_count = 600` in `indicator()` when needed to balance available training history against model size and execution time.
Respect sequence shapes : Conv1D, temporal stacks, LSTM, and GRU methods expect flattened sequence sizes of `timeSteps * featureCount`.
Respect attention shapes : Attention methods expect each input row to have `modelDim` columns. Cross-attention and decoder blocks use packed rows.
Use NeuraLib guardrails : Train/validation splits, scalers, EarlyStopper, training gates, and gradient clipping remain part of the main NeuraLib workflow.
----------------------------------------------------------------------------------------------------------------
🔷 API REFERENCE
🔸 Sequential Methods
residualDense(hiddenUnits, activationKind, dropoutRate, name) : Adds a residual dense block.
duelingQHead(hiddenUnits, actionCount, activationKind, name) : Adds a dueling value/advantage Q-head.
conv1d(timeSteps, featureCount, filters, kernelSize, stride, activationKind, name) : Adds a Conv1D block for flattened sequences.
temporalConvStack(timeSteps, featureCount, filters, kernelSize, layers, stride, activationKind, dropoutRate, name) : Adds stacked temporal Conv1D layers.
globalAvgPool1d(timeSteps, featureCount, name) : Adds global average pooling over a flattened 1D sequence.
globalMaxPool1d(timeSteps, featureCount, name) : Adds global max pooling over a flattened 1D sequence.
lstm(timeSteps, featureCount, units, activationKind, name) : Adds an LSTM scan block.
gru(timeSteps, featureCount, units, activationKind, name) : Adds a GRU scan block.
selfAttention(modelDim, causal, name) : Adds row-wise self-attention.
multiHeadSelfAttention(modelDim, headCount, causal, name) : Adds multi-head self-attention.
crossAttention(queryRows, memoryRows, modelDim, headCount, name) : Adds packed query-memory cross-attention.
transformerEncoder(modelDim, causal, ffMultiplier, activationKind, name, dropoutRate, headCount) : Adds one Transformer encoder block.
transformerEncoderStack(modelDim, layers, causal, ffMultiplier, activationKind, dropoutRate, headCount, name) : Adds repeated Transformer encoder blocks.
transformerDecoder(targetRows, memoryRows, modelDim, headCount, ffMultiplier, activationKind, dropoutRate, name) : Adds a packed target-memory Transformer decoder.
🔸 GraphBlock Factories
qHeadBlock(inputFeatures, actionCount, activationKind, name) : Creates a Q-head block.
duelingQHeadBlock(inputFeatures, hiddenUnits, actionCount, activationKind, name) : Creates a dueling Q-head block.
residualDenseBlock(inputFeatures, hiddenUnits, activationKind, dropoutRate, name) : Creates a residual dense block.
conv1dBlock(timeSteps, featureCount, filters, kernelSize, stride, activationKind, name) : Creates a Conv1D block.
temporalConvStackBlock(timeSteps, featureCount, filters, kernelSize, layers, stride, activationKind, dropoutRate, name) : Creates a temporal convolution stack.
globalAvgPool1dBlock(timeSteps, featureCount, name) and globalMaxPool1dBlock(timeSteps, featureCount, name) : Create pooling blocks.
lstmBlock(timeSteps, featureCount, units, activationKind, name) and gruBlock(timeSteps, featureCount, units, activationKind, name) : Create recurrent blocks.
selfAttentionBlock(modelDim, causal, name) , multiHeadSelfAttentionBlock(modelDim, headCount, causal, name) , and crossAttentionBlock(queryRows, memoryRows, modelDim, headCount, name) : Create attention blocks.
transformerEncoderBlock(modelDim, causal, ffMultiplier, activationKind, name, dropoutRate, headCount) and transformerDecoderBlock(targetRows, memoryRows, modelDim, headCount, ffMultiplier, activationKind, dropoutRate, name) : Create Transformer blocks.
🔸 Prioritized Experience Replay
prioritizedReplayBuffer(featureCount, targetCount, maxRows, name) : Creates a replay buffer.
pushExperience(featureRowArray, targetRowArray, priority) : Adds or overwrites one replay row.
sampleBatch(batchSize, alpha, beta, seed) : Returns a deterministic weighted sample.
updatePriority(index, priority) : Updates a sampled row priority.
toBatch() : Returns all replay rows in chronological order.
ready(minRows) , size() , and clear() : Replay buffer utilities.
🔸 Feature Helpers
pushPositionalEncoding(position, dimensions, maxPeriod, featurePrefix) : Appends sinusoidal positional encoding values to a NeuraLib `FeatureBuilder`.
NeuraLib_Models is for Pine Script developers who want higher-level neural architecture blocks without leaving the NeuraLib runtime. It is built for compact research models inside TradingView's execution limits, not for oversized GPU-style networks.
All the diagrams in this publication are rendered natively on TradingView using Pine3D
----------------------------------------------------------------------------------------------------------------
This work is licensed under (CC BY-NC-SA 4.0) , meaning usage is free for non-commercial purposes given that Alien_Algorithms is credited in the description for the underlying software. For commercial use licensing, contact Alien_Algorithms
腳本庫

NeuraLib: A Native AI and Deep Learning RuntimeNeuraLib is a tensor-based, auto-differentiating Machine Learning runtime built natively for Pine Script™.
It brings real Deep Learning mechanisms that power modern Artificial Intelligence systems into TradingView. Instead of relying on fixed formulas, static regressions, or rigid structures, NeuraLib gives Pine developers a different tool: a compact neural runtime that can learn from the features you feed it, using the architecture you define.
This means users are no longer limited to classical methods like Linear Regression, Logistic Regression, KNN, Naive Bayes, Kalman Filters, or Markov Chains. One can build adaptive architectures perfectly suited for custom indicators, strategies, regime detection, directional prediction, price transforms, and AI-assisted signal generation.
Using NeuraLib, one can build a model, collect market data, normalize it, run predictions, train through backpropagation, track validation behavior, and update weights directly inside TradingView.
Furthermore, it is not necessary to directly display trained variables. The process can be a part of a larger script functionality, where AI-powered decision making changes how an indicator behaves.
The goal is to make real neural network workflows usable in Pine Script without hiding the important controls, being scalable with evolving market dynamics, and abstracting away the complexity that comes with such software. The provided API is highly modular and intuitive, using chained object-oriented programming for easy readability and use. The backend is engineered with fault-tolerance in mind, providing users with sanity checks and preventing common pitfalls by default.
Think of NeuraLib as a comprehensive machine learning ecosystem, containing:
A Model Builder : Define neural networks with readable chained calls like `.input()`, `.dense()`, and `.dropout()`.
An In-Pine Training Engine : Models calculate losses, backpropagate gradients, update weights, and produce predictions directly on chart data.
Automated Data Pipelines : Built-in datasets handle feature collection, robust scaling (Z-Score, Min-Max), validation holdout splits, and time-series rolling windows.
Finance-Native Loss Functions : Beyond standard error metrics, the engine includes Directional, Quantile, Multi-Horizon Weighted, and Sharpe-style losses tailored for trading.
Practical Training Controls : Layer Normalization, AdamW weight decay, gradient clipping, gradient accumulation, and early stopping are built in to prevent overfitting.
Advanced Optimizers : Train networks using RMSProp, Adam, or AdamW, paired with learning rate schedules like Warmup Cosine and Step Decay.
For newer users, this means you can start with a simple dense model. For advanced users, the same runtime exposes graph operations, custom blocks, tensors, matrix operations, optimizers, schedules, losses, and extension hooks.
In plain terms, a model receives a row of numbers called features, compares its output against a target, measures the error with a loss function, and then adjusts its internal weights to reduce that error next time.
----------------------------------------------------------------------------------------------------------------
🔷 WHAT MAKES IT DIFFERENT
🔸 Parity-tested neural math
NeuraLib’s core operations have been tested against established Machine Learning Runtimes outside of TradingView (Such as Keras / TensorFlow / PyTorch).
The goal was not to imitate the appearance of Machine Learning, but to reproduce the math that is proven to work. Standard forward passes, gradients, losses, and optimizer behavior were checked for 1:1 algorithmic parity, with negligible differences coming from normal floating-point behavior.
That means the matrix math, backpropagation, and gradient updates running on your chart follow the same underlying logic expected from professional Machine Learning environments.
🔸 Matrix-first computation
NeuraLib uses tensor and matrix abstractions as the foundation of the runtime. Under the hood, it supports the operations needed for neural computation, including matrix multiplication, broadcasting, activation functions, softmax, slicing, concatenation, reductions, normalization, attention scoring, convolution-style operations, and recurrent scan blocks.
🔸 Auto-differentiating graph engine
NeuraLib makes the computational graph a first-class object.
You can use high-level Sequential models, or build custom GraphBlocks from lower-level operations. Once a custom block is connected to a model, the same runtime handles the backward pass. That means your custom architecture can be trained with the same `.trainOnBatch()` workflow as standard layers.
----------------------------------------------------------------------------------------------------------------
🔷 CUSTOM GRAPHS
The Sequential API is the easiest way to start, but NeuraLib is not just a list of built-in layers.
You can create a `GraphBlock`, add operations, set an output node, and plug that block into a model. Once connected, the runtime handles the backward pass and parameter updates.
Useful graph operations include:
Matrix multiplication, transpose, add, subtract, multiply, divide, and scale.
Activation functions and softmax.
Layer Normalization and Dropout.
Causal masking, slicing, concatenation, row reduction, and column reduction.
Global average pooling and global max pooling for 1D sequences.
Attention score and attention apply operations.
Conv1D, LSTM scan, and GRU scan primitives.
This is the foundation that allows companion model libraries to add advanced AI and Machine Learning architectures without changing the main NeuraLib runtime.
----------------------------------------------------------------------------------------------------------------
🔷 BUILT-IN DATA GUARDRAILS
NeuraLib is not only a training mechanism. It also includes guardrails for cleaner research:
Invalid rows are rejected : Dataset rows must match the configured feature and target counts, and rows containing `na` values are not inserted.
Shape checks protect model calls : Forward, training, backward, and evaluation paths validate input and target shapes before running expensive graph code.
Train and validation splits are separated : `trainBatch()` and `validationBatch()` use holdout rows instead of blending all rows into one batch.
Scaler leakage is controlled : Validation batches are scaled from the training-side profile where the dataset split requires it, so validation normalization does not learn from the holdout slice.
Rolling windows respect time order : `RollingDataset` supports target offsets and wrapped ring buffers while preserving chronological reads.
These checks help reduce common data poisoning and data leakage mistakes: wrong row widths, missing values, validation contamination, target-offset leakage, and accidental overtraining across every historical bar.
----------------------------------------------------------------------------------------------------------------
🔷 A FIRST MODEL
The basic API is intentionally readable. This creates a small model with dropout, one hidden layer, Huber loss, AdamW optimization, and MAE tracking.
//@version=6
indicator("NeuraLib Basic Model", overlay = false, calc_bars_count = 600)
import Alien_Algorithms/NeuraLib/1 as nl
var nl.Sequential model = nl.sequential("basic_model")
var float modelOutput = na
if barstate.isfirst
nl.CompileConfig cfg = nl.compileConfig()
cfg := cfg
.optimizer(nl.adamW(0.001))
.loss(nl.LossKind.huber)
.metric(nl.MetricKind.mae)
.withTrainingGate(true)
model := model
.input(array.from(4), "features")
.dropout(0.15)
.dense(8, nl.ActivationKind.relu, "hidden")
.dense(1, nl.ActivationKind.linear, "output")
.compile(cfg)
float rsiValue = ta.rsi(close, 14)
float emaValue = ta.ema(close, 21)
float atrValue = ta.atr(14)
float atrPct = close == 0.0 ? 0.0 : atrValue / close
float momentum = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
bool ready = not na(rsiValue) and not na(emaValue) and not na(atrPct) and not na(momentum)
if ready
float priceVsEma = emaValue == 0.0 ? 0.0 : close / emaValue - 1.0
nl.Tensor inputTensor = nl.vector(array.from(rsiValue, priceVsEma, atrPct, momentum), "features")
nl.Tensor outputTensor = model.predict(inputTensor)
modelOutput := outputTensor.get1d(0)
plot(modelOutput, "Untrained model output", color = color.aqua, linewidth = 2)
hline(0.0, "Zero", color = color.new(color.gray, 70))
The same model can then receive scaled batches from a dataset and train with `.trainOnBatch()`. The plot in this first example is the untrained forward output, included so the block can be pasted directly into an indicator.
----------------------------------------------------------------------------------------------------------------
🔷 A PRACTICAL DATA FLOW
Machine Learning models usually fail when the data pipeline is careless. Price, volume, volatility, and oscillators often live on very different scales. NeuraLib includes dataset and scaling helpers so the common workflow stays explicit:
Build a feature row.
Build a target row.
Push the row into a dataset.
Request a training batch.
Request a validation batch when needed.
Train, evaluate, predict, and inverse-scale targets when appropriate.
//@version=6
indicator("NeuraLib Return Validation Example", overlay = false, calc_bars_count = 600)
import Alien_Algorithms/NeuraLib/1 as nl
var nl.Sequential model = nl.sequential("returns_model")
var nl.WindowDataset dataset = nl.windowDataset(4, 1, 500, "returns_dataset")
var float predictedReturn = na
var float validationLossValue = na
var float trainingLossValue = na
if barstate.isfirst
nl.CompileConfig cfg = nl.compileConfig()
cfg := cfg
.optimizer(nl.adamW(0.003))
.loss(nl.LossKind.huber)
.metric(nl.MetricKind.mae)
.trainEveryCall()
model := model
.input(array.from(4), "features")
.dense(8, nl.ActivationKind.relu, "hidden")
.dropout(0.10, "dropout")
.dense(1, nl.ActivationKind.linear, "next_return")
.compile(cfg)
dataset := dataset
.setInputScaler(nl.ScalerKind.zScore)
.setTargetScaler(nl.ScalerKind.zScore)
float rsiValue = ta.rsi(close, 14)
float emaValue = ta.ema(close, 21)
float atrValue = ta.atr(14)
float atrPct = close == 0.0 ? 0.0 : atrValue / close
float momentum = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float realizedReturn = na(close ) ? na : nl.nextReturnValue(close , close)
bool rowReady = not na(rsiValue ) and not na(emaValue ) and not na(atrPct ) and not na(momentum ) and not na(close )
if rowReady
float prevEma = emaValue
float priceVsEma = prevEma == 0.0 ? 0.0 : close / prevEma - 1.0
array features = array.from(
rsiValue ,
priceVsEma,
atrPct ,
momentum )
array target = array.from(nl.nextReturnValue(close , close))
dataset := dataset.pushRow(features, target)
if dataset.ready(64)
nl.Batch train = dataset.trainBatch(16)
nl.Batch validation = dataset.validationBatch(16)
model := model.trainOnBatch(train.inputTensor, train.targetTensor)
trainingLossValue := model.trainStats.lastLoss
nl.LossResult validationLoss = model.evaluate(validation.inputTensor, validation.targetTensor)
validationLossValue := validationLoss.value
bool liveReady = not na(rsiValue) and not na(emaValue) and not na(atrPct) and not na(momentum)
if liveReady
float livePriceVsEma = emaValue == 0.0 ? 0.0 : close / emaValue - 1.0
array liveFeatures = array.from(rsiValue, livePriceVsEma, atrPct, momentum)
nl.Tensor liveInput = nl.vector(liveFeatures, "live_features")
nl.Tensor scaledInput = dataset.scaleInput(liveInput)
nl.Tensor scaledPrediction = model.predict(scaledInput)
nl.Tensor rawPrediction = dataset.inverseScaleTarget(scaledPrediction)
predictedReturn := rawPrediction.get1d(0)
plot(realizedReturn, "Last realized return", color = color.gray)
plot(predictedReturn, "Predicted next return", color = color.aqua, linewidth = 2)
plot(validationLossValue, "Validation loss", color = color.orange)
plot(trainingLossValue, "Training loss", color = color.new(color.blue, 35))
hline(0.0, "Zero", color = color.new(color.gray, 70))
This example trains from completed historical pairs. The feature row comes from the previous bar, and the target is the return from that previous bar to the current bar. That keeps the example easy to inspect and avoids using future information in the feature row. When pasted into an indicator, it plots the last realized return, the model's predicted next return, training loss, and validation loss.
----------------------------------------------------------------------------------------------------------------
🔷 TWO PRACTICAL EXECUTION MODES
Deep Learning in Pine requires careful execution control. NeuraLib supports two main workflows.
🔸 1. Live-edge training
Use this when you want safer execution for larger models.
The dataset can collect rows across the chart, while the expensive training step only runs on the last confirmed historical bar. This helps avoid timeouts while still allowing the model to learn from recent prepared data.
cfg := cfg.withTrainingGate(true)
Use this for:
Larger models
More features
Rolling sequence inputs
Heavier architectures
Safer live-edge updates
🔸 2. Full-history training and inference
Use this when the model is intentionally small.
The model can train and infer across historical bars, which makes it possible to create lightweight adaptive indicators, such as an AI Moving Average that learns from recent local structure instead of using a fixed smoothing formula.
cfg := cfg.trainEveryCall()
Use this for:
Tiny dense models
Small batches
Fast adaptive filters
AI-assisted moving averages
Lightweight feature transforms
For full-history workflows, start small. A shallow model with 4 to 8 hidden units and a batch size of 8 or 16 is usually a better starting point than a deep architecture.
----------------------------------------------------------------------------------------------------------------
🔷 ADVANCED MODEL EXPANSION
NeuraLib is designed to act as the foundation for larger model libraries and community-built extensions.
To demonstrate this, NeuraLib Expansion: Advanced Model Layers is built entirely on top of the public NeuraLib API and is launched in parallel on day one. The expansion library is published as NeuraLib_Models . It extends the runtime with higher-level builders for LSTMs, GRUs, temporal convolution stacks, residual dense blocks, dueling Q-heads for Reinforcement Learning, Transformer-style attention blocks, and Prioritized Experience Replay utilities.
The important part is architectural: advanced models plug into the same runtime. NeuraLib remains the foundation for tensors, graph execution, optimization, training, inference, datasets, and scaling. After importing `NeuraLib_Models`, its fluent methods become available on NeuraLib `Sequential` models, so the expansion alias does not need to be referenced directly in the layer chain.
//@version=6
indicator("NeuraLib Models Extension Demo", overlay = false, calc_bars_count = 600)
import Alien_Algorithms/NeuraLib/1 as nl
import Alien_Algorithms/NeuraLib_Models/1 as models
var nl.Sequential model = nl.sequential("advanced_demo")
if barstate.isfirst
model := model
.input(array.from(8), "sequence")
.temporalConvStack(4, 2, 3, 2, 2, 1, nl.ActivationKind.relu, 0.0, "temporal")
.globalAvgPool1d(2, 3, "pool")
.duelingQHead(4, 2, nl.ActivationKind.relu, "q_head")
.build(nl.rng(7))
----------------------------------------------------------------------------------------------------------------
🔷 FEATURE QUICK REFERENCE
Runtime : Matrix-first auto-differentiating neural graph runtime for Pine Script.
Model API : Chainable `Sequential` builder with `input`, `dense`, `dropout`, `layerNorm`, `activation`, `flatten`, `reshape`, and custom `block` support.
Training : Forward pass, loss calculation, backpropagation, gradient accumulation, optimizer steps, train stats, and history buffers.
Inference : `.predict()` for deterministic inference and `.predictMC()` for dropout-based uncertainty sampling.
Datasets : `WindowDataset` for flat rows and `RollingDataset` for time-series windows.
Scaling : None, Z-Score, Min-Max, Running Z-Score scalers, dataset input scaling, target scaling, and inverse target scaling.
Optimizers : SGD, Momentum, RMSProp, Adam, and AdamW.
Schedulers : Constant, Step Decay, Cosine Decay, and Warmup Cosine.
Activations : Linear, ReLU, Leaky ReLU, ELU, GELU Approx, Sigmoid, Tanh, Softplus, Swish, and Softmax.
Losses : MSE, MAE, Huber, LogCosh, Binary Cross Entropy, Binary Cross Entropy From Logits, Categorical Cross Entropy, Softmax Cross Entropy From Logits, Directional, Quantile, Multi-Horizon Weighted, and Sharpe.
Metrics : MAE, RMSE, Directional Accuracy, Binary Accuracy, Binary Accuracy From Logits, Categorical Accuracy, and Cosine Similarity.
Guardrails : Shape validation, invalid-row rejection, train/validation split helpers, leakage-aware scaler profiles, training gates, gradient clipping, and EarlyStopper.
Advanced expansion : Conv1D, temporal stacks, recurrent blocks, attention, Transformers, dueling Q-heads, positional encodings, and Prioritized Experience Replay.
----------------------------------------------------------------------------------------------------------------
🔷 IMPORTANT CONSIDERATIONS
Start small : Pine Script is not a GPU training environment. Compact models are the right starting point.
Control chart history : Use `calc_bars_count = 600` in `indicator()` when needed to balance available training history against model size and execution time.
Use the training gate : For heavier models, use `.withTrainingGate(true)` so backpropagation runs only at the confirmed historical edge.
Scale your inputs : Raw market features often differ by orders of magnitude. Use dataset scalers unless you have a deliberate reason not to.
Validate separately : Use `trainBatch()` and `validationBatch()` to monitor generalization instead of only watching training loss.
Avoid lookahead : Build feature rows only from information available at the time of the row. Use completed target rows for training.
Treat outputs as research signals : NeuraLib provides model mechanics. Strategy design, risk management, and market assumptions remain the user's responsibility.
----------------------------------------------------------------------------------------------------------------
🔷 API REFERENCE
🔸 Model Setup
sequential(name) : Creates an empty `Sequential` model.
compileConfig() : Creates a model configuration object.
build(rng) : Builds model parameters with a deterministic random stream.
compile(config) : Builds the model when needed and applies the training configuration.
rng(seed, streamId) : Creates a deterministic random stream.
🔸 Sequential Methods
input(dimsArray, name) : Defines the input shape.
dense(units, activation, name) : Adds a fully connected layer.
qHead(actionCount, activation, name) : Adds a Q-value output head.
activation(activationKind, alpha, name) : Adds an activation block.
dropout(rate, name) : Adds dropout regularization.
layerNorm(name) : Adds layer normalization.
flatten(name) and reshape(outputDimsArray, name) : Adjust model shape metadata.
block(graphBlock) : Adds a custom `GraphBlock`.
trainOnBatch(inputTensor, targetTensor) : Runs training when the active gate allows it.
backward(targetTensor) : Accumulates gradients from the last forward pass without stepping.
step() : Applies the optimizer step to accumulated gradients.
predict(inputTensor) : Runs inference.
predictMC(inputTensor, samples) : Runs dropout-enabled Monte Carlo prediction and returns mean and variance.
evaluate(inputTensor, targetTensor) : Calculates loss without updating weights.
fitDataset(dataset) and fitRollingDataset(dataset, targetOffset) : Train through dataset adapters.
getWeightsArray() and setWeightsArray(weightsArray) : Export and import flat model weights.
softUpdateFrom(sourceModel, tau) : Soft-update parameters from another model.
🔸 CompileConfig Methods
optimizer(optimizerState) : Sets the optimizer.
schedule(scheduleState) : Sets the learning-rate schedule.
loss(lossKind) : Sets the training loss.
reduction(reductionKind) : Sets loss reduction behavior.
metric(metricKind) : Adds a metric.
batchSize(size) , epochsPerBar(count) , evalStride(stride) , and historyLength(length) : Store batch and cadence preferences, and set the metric history length.
clipNorm(value) and clipValue(value) : Apply gradient clipping.
gradAccumSteps(steps) : Accumulates gradients before stepping.
withTrainingGate(enabled) : Restricts training to the last confirmed historical bar when enabled.
trainEveryCall() : Allows training whenever `.trainOnBatch()` is called.
presetPriceRegression() , presetReturnRegression() , presetBinaryDirection() , presetBinaryDirectionLogits() , presetQValues() , and presetSharpe() : Apply common loss and metric presets.
🔸 Datasets
windowDataset(featureCount, targetCount, maxRows, name) : Stores flat feature and target rows.
rollingDataset(timeSteps, featureCount, targetCount, maxRows, name) : Stores time-series windows.
pushRow(featureArray, targetArray) : Adds one validated row.
pushBuilderRow(featureBuilder, targetArray) : Adds a row from a `FeatureBuilder`.
pushNextReturnRow(featureBuilder, currentValue, futureValue) : Adds a next-return target.
pushNextDirectionRow(featureBuilder, currentValue, futureValue, threshold, zeroOne) : Adds a direction target.
ready(minRows or minWindows, targetOffset) and size() : Check dataset readiness.
lastBatch(batchSize) : Returns the most recent scaled rows from a `WindowDataset`.
toBatch() : Returns all rows from a `WindowDataset`.
unrollBatch(targetOffset) : Returns all rolling windows from a `RollingDataset`.
trainBatch(validationRows or validationWindows, targetOffset) : Returns the training side of the split.
validationBatch(validationRows or validationWindows, targetOffset) : Returns the validation side of the split.
setInputScaler(kind) , setTargetScaler(kind) , scaleInput(tensor) , scaleTarget(tensor) , and inverseScaleTarget(tensor) : Configure and apply scaling.
clear() : Clears stored rows.
🔸 Tensor, Matrix, and Feature Helpers
scalar(value) , vector(valuesArray) , matrix2d(rows, cols, fillValue) , zeros(shape) , ones(shape) , and full(shape, fillValue) : Create tensors.
shapeFromDims(dimsArray) : Creates a shape.
matrixTensor(tensor) , matrixTensor2d(rows, cols, fillValue) , and matrixTensorFromMatrix(sourceMatrix) : Create matrix tensors.
reshape(dimsArray) , flatten() , row(rowIndex) , get1d(index) , sum() , mean() , variance() , normL2() , argmax() , and dot(other) : Tensor methods.
matmul() , transpose() , add() , subtract() , multiply() , divide() , scale() , activate() , softmax() , sliceRows() , sliceCols() , concatRows() , concatCols() , globalAvgPool1d() , and globalMaxPool1d() : MatrixTensor methods.
featureBuilder(name) , push(value, featureName) , addFeature(value, featureName) , toTensor(tensorName) , toArray() , size() , and clear() : Feature row helpers.
🔸 Scalers, Optimizers, and Schedules
zScoreScaler() , minMaxScaler() , runningZScoreScaler() , and noneScaler() : Standalone scaler states.
fit(tensor) , partialFit(tensor) , transform(tensor) , and inverseTransform(tensor) : Scaler methods.
sgd(learningRate) , momentum(learningRate, momentum) , rmsprop(learningRate, rho, epsilon) , adam(learningRate, beta1, beta2, epsilon) , and adamW(learningRate, beta1, beta2, epsilon, weightDecay) : Optimizers.
constantSchedule(learningRate) , stepDecay(baseLearningRate, decaySteps, gamma) , cosineDecay(baseLearningRate, minLearningRate, decaySteps) , and warmupCosine(baseLearningRate, minLearningRate, warmupSteps, decaySteps) : Schedules.
currentRate(stepCount) : Reads a schedule's learning rate at a step.
paramBank() , append() , zeroGrad() , globalGradNorm() , step(optimizerState) , and softUpdateFrom(sourceBank, tau) : Low-level parameter bank utilities.
🔸 Losses and Metrics
mse() , mae() , huber() , logCosh() , binaryCrossEntropy() , binaryCrossEntropyFromLogits() , categoricalCrossEntropy() , softmaxCrossEntropyFromLogits() , directionalLoss() , quantileLoss() , multiHorizonWeighted() , and sharpeLoss() : Direct loss helpers.
metricValue(metricKind, predictionTensor, targetTensor) : Direct metric helper.
earlyStopper(patience, minDelta) , update(validationLoss) , and reset() : Validation stopping helper.
nextReturnValue(currentValue, futureValue) and nextDirectionValue(currentValue, futureValue, threshold, zeroOne) : Common target helpers.
🔸 GraphBlock Operations
graphBlock(name) : Creates a custom trainable graph block.
input() , param() , constScalar() , constMatrix() , and output() : Define graph inputs, parameters, constants, and output metadata.
matmul() , add() , subtract() , multiply() , divide() , scale() , activate() , softmax() , transpose() , layerNorm() , and dropout() : NeuraLib graph math.
causalMask() , sliceRows() , concatRows() , sliceCols() , concatCols() , reduceRows() , and reduceCols() : Structural graph operations.
globalAvgPool1d() , globalMaxPool1d() , attentionScore() , attentionApply() , conv1d() , scanLstm() , and scanGru() : Sequence and architecture primitives.
🔸 NeuraLib_Models API
prioritizedReplayBuffer(featureCount, targetCount, maxRows, name) : Creates a replay buffer.
pushExperience(featureRowArray, targetRowArray, priority) , sampleBatch(batchSize, alpha, beta, seed) , updatePriority(index, priority) , toBatch() , ready(minRows) , size() , and clear() : Prioritized Experience Replay helpers.
pushPositionalEncoding(position, dimensions, maxPeriod, featurePrefix) : Adds positional encoding values to a `FeatureBuilder`.
residualDense() , duelingQHead() , conv1d() , temporalConvStack() , globalAvgPool1d() , globalMaxPool1d() , lstm() , gru() , selfAttention() , multiHeadSelfAttention() , crossAttention() , transformerEncoder() , transformerEncoderStack() , and transformerDecoder() : NeuraLib_Models `Sequential` methods.
NeuraLib is for Pine Script developers who want to move beyond fixed formulas and experiment with real neural network workflows directly inside TradingView. It is a research framework, not a guarantee of market performance. Use validation, avoid lookahead, control risk, and keep models small enough for Pine's execution limits.
All the diagrams in this publication are rendered natively on TradingView using Pine3D
----------------------------------------------------------------------------------------------------------------
This work is licensed under (CC BY-NC-SA 4.0) , meaning usage is free for non-commercial purposes given that Alien_Algorithms is credited in the description for the underlying software. For commercial use licensing, contact Alien_Algorithms
腳本庫

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

rangeBreakoutLibrary "rangeBreakout"
markRange(trackTimePeriod, drawTimePeriod, highLineColor, lowLineColor, middleLineColor, maxLookbackDays)
Parameters:
trackTimePeriod (simple string) : - Time range for which the high and low values are tracked. This is the range; any breakout above/below this period can indicate a potential long/short entry condition.
drawTimePeriod (simple string) : - Time range for which the range is valid, this is typically from the end of the `trackTimePeriod` to the end of the day (or session) for security.
highLineColor (color)
lowLineColor (color)
middleLineColor (color)
maxLookbackDays (simple int) : - Number of historic days to retain the range value.
Returns: - Values to print the range values, and a boolean indicator that indicates if the current time is within the tracking time period.
The library can then be forward integrated into other indicators, strategies, and other libraries of TradingView, thus one function can be used globally. 腳本庫

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 腳本庫

Vantage_PairedSizingVantage_PairedSizing — Position sizing for strategies that pair a primary trade with a recovery trade under a daily loss budget.
─────────────────────────────────────────
WHAT IT DOES
Answers the question "how many contracts can I take on the primary trade so that, if it stops out, a correctly-sized recovery trade still fits within my daily loss limit?" The library scans candidate quantities top-down and returns the largest one whose worst case (primary stop + recovery stop) stays inside the budget, subject to one of four risk-reward modes.
─────────────────────────────────────────
WHAT IT PROVIDES
A single entry-point auto-sizer that takes the primary leg's entry/stop/target, the recovery leg's entry/stop/target, a daily loss budget, and a sizing mode — and returns a result record with primary quantity, recovery quantity, per-leg dollar risk, worst-case dollar exposure, and net-if-recovery-wins. The scan falls through a mode ladder (MatchPrimaryProfit → MatchPct → NetGreen) and a no-recovery fallback before giving up, so callers get a usable answer in marginal cases instead of a flat rejection.
Four named sizing modes covering the common risk-reward shapes: largest size under a drawdown cap, largest size where the recovery win leaves the session net-green, largest size where the recovery win matches the primary's target profit, and a percentage variant of the match mode.
Two utility functions for the dollar math — risk and profit for a given quantity between two prices — so strategies don't have to redo the tick-size / point-value arithmetic themselves.
─────────────────────────────────────────
HOW TO USE
A complete example call is in the comment block at the top of the source file — import the library, copy the pattern, plug in your primary and recovery price levels. Hover any exported type, enum, or function in the Pine Editor for per-parameter documentation. 腳本庫

Vantage_PickMyTrade_IntegrationVantage_PickMyTrade_Integration — Webhook integration library for Pine Script strategies routing orders through PickMyTrade.
─────────────────────────────────────────
WHAT IT DOES
Constructs and emits JSON webhook payloads in the PickMyTrade format. The library provides a strongly-typed Pine Script interface and emits the alert for you, so your strategy never has to hand-build JSON strings, remember exact field values, or track which fields are conditional.
─────────────────────────────────────────
WHAT IT PROVIDES
Strong types for every PickMyTrade enumeration — order actions (buy / sell / close), order types (market / limit / stop / stop-limit), and bracket-mode specification (price / dollar / percent). Using a typed enum catches typos at compile time.
High-level send functions covering the common order patterns — a stop entry with bracket (pre-placed at the exchange), a market or limit entry with bracket, targeted close by comment tag, a full-flatten for a symbol, and in-place SL/TP modification on an existing position. All share a single underlying builder that handles field ordering, conditional fields, and token-in-body authentication.
─────────────────────────────────────────
HOW TO USE
A complete example call is in the comment block at the top of the source file — import the library, copy the pattern, adjust to your strategy. Hover any exported type or function in the Pine Editor for per-parameter documentation. 腳本庫

Vantage_TradersPostVantage_TradersPost — Webhook integration library for Pine Script strategies routing orders through TradersPost.
─────────────────────────────────────────
WHAT IT DOES
Constructs and emits JSON webhook payloads in the TradersPost format. The library provides a strongly-typed Pine Script interface and emits the alert for you, so your strategy never has to hand-build JSON strings, remember exact enum values, or track which fields are conditional.
─────────────────────────────────────────
WHAT IT PROVIDES
Strong types for every TradersPost enumeration — order actions, order types, quantity types, position sentiment, stop-loss types, time-in-force, and the options fields. Using a typed enum in your strategy catches typos at compile time instead of at trade time.
High-level send functions covering the common order patterns — a single-call bracket (entry + TP + SL), an advanced send with every TradersPost field exposed, a no-cancel variant, a sentiment-based position-management send, a cancel-all, and two-leg OTO and OCO helpers.
─────────────────────────────────────────
HOW TO USE
A complete example call is in the comment block at the top of the source file — import the library, copy the pattern, adjust to your strategy. Hover any exported type or function in the Pine Editor for per-parameter documentation.
─────────────────────────────────────────
Maintenance of this library was taken over at the request of adam_overton. 腳本庫

Vantage_UtilsVantage_Utils — Non-trading utilities for Pine Script strategies. A news-calendar state machine and a per-trade P&L tracker, both built as UDT pseudo-classes you instantiate and drive from your script.
─────────────────────────────────────────
WHAT IT DOES
Two capabilities are packaged as instantiable objects (UDT pseudo-classes) so your script holds the state and calls methods rather than threading raw values and globals: a news-calendar state machine that tells you whether the current bar is blocked or delayed by an economic event, and a P&L tracker that accumulates per-trade, session, and daily totals with on-chart labels.
─────────────────────────────────────────
WHAT IT PROVIDES
A news-calendar state machine that consolidates the Vantage_News_Types vocabulary and the Vantage_News / Vantage_News_Historical calendar data behind a single NewsState object. Your strategy asks whether the current bar is blocked or delayed, or when the next trading window starts, and gets the answer back — no need to join event rows against a severity table yourself. Per-type policy overrides and per-severity defaults are configurable. Allows avoiding trading news volatile moments in back testing and live trading.
A P&L tracker (PnLTracker) that computes realized trade P&L with commission, accumulates session and daily totals, detects day boundaries for automatic reset, and manages the per-trade P&L label lifecycle on the chart.
─────────────────────────────────────────
HOW TO USE
A minimal usage example is in the comment block at the top of the source file — import the library, copy the pattern, adjust to your strategy. Hover any exported type or function in the Pine Editor for per-parameter documentation.
Imports Vantage_News, Vantage_News_Historical, and Vantage_News_Types to expose the consolidated news calendar. 腳本庫

腳本庫

腳本庫

APExitManagerLibrary "APExitManager"
apExitManager(entryID, isLong, rangeSize, rangeHigh, rangeLow, slMethod, tpMethod, slPercent, tpPercent, atrMultSL, atrMultTP, stackedCount, stackedTotalPercent, usePartial, partialPct, atrLength, superLength, superFactor)
Parameters:
entryID (string)
isLong (bool)
rangeSize (float)
rangeHigh (float)
rangeLow (float)
slMethod (string)
tpMethod (string)
slPercent (float)
tpPercent (float)
atrMultSL (float)
atrMultTP (float)
stackedCount (int)
stackedTotalPercent (float)
usePartial (bool)
partialPct (float)
atrLength (simple int)
superLength (simple int)
superFactor (float) 腳本庫

腳本庫

Trade Strategy Calculator [WillyAlgoTrader]📊 Trade Strategy Calculator is the first comprehensive mathematical strategy calculator built entirely inside TradingView — a 4-panel dashboard that computes position sizing, risk analysis, deposit growth projection, and Kelly Criterion optimization in real time, directly on your chart. No spreadsheets, no external tools, no switching tabs. Every number you need before entering a trade — position size, stop loss level, take-profit targets, commission impact, expected value, probability of ruin, compound growth forecast, and optimal bet sizing — calculated from your strategy parameters and displayed in a single organized view.
This tool is useful for every trader regardless of market, instrument, or timeframe — stocks, forex, crypto, futures, indices, commodities. Whether you trade scalping on 1-minute charts or swing on daily, whether you use 1x spot or 125x futures leverage — the mathematics of position sizing, risk management, and bankroll growth are universal. This calculator puts those mathematics at your fingertips.
🧩 WHY ALL FOUR PANELS WORK TOGETHER
Most traders calculate position size in isolation — they know how much to risk but don't connect it to their long-term growth trajectory. They know their win rate but don't know if it's mathematically profitable after commissions. They have a "feel" for their risk level but haven't computed what happens after 7 consecutive losses.
This calculator connects four mathematical dimensions into one coherent picture:
🎯 TRADE panel answers: "How large should this specific trade be, and what are the exact entry/SL/TP prices?"
⚠️ RISK panel answers: "What happens when things go wrong — how many losses until I hit my daily limit, my max drawdown, and what's my expected value per trade?"
📈 GROWTH panel answers: "If I trade consistently with these parameters, where will my deposit be in 30/90/365 days — and how long to reach my target?"
📐 KELLY panel answers: "Am I betting the mathematically optimal amount — or am I over-betting (risking ruin) or under-betting (leaving growth on the table)?"
A trader who only uses the TRADE panel knows their position size but not whether their strategy has positive expected value. A trader who only uses KELLY knows the optimal bet size but not the specific position for their current trade. A trader who only uses GROWTH knows the projection but not whether the underlying math is sound. All four together give you the complete picture: "Is my strategy profitable? Am I sizing correctly? What's the worst case? And where does this lead?"
🔍 WHAT MAKES IT ORIGINAL
There is no other indicator on TradingView that combines all four of these mathematical models — position sizing, risk stress testing, compound growth simulation, and Kelly Criterion — into a single, real-time, interactive dashboard. Each panel alone would be a useful tool. Together, they create something that doesn't exist elsewhere on the platform.
🎯 PANEL 1 — TRADE (Position Sizing + Targets)
This panel calculates the exact position size for your trade based on your deposit, risk percentage, stop loss distance, leverage, and commissions.
Core formula:
positionSize = riskAmount / (slDistance% + commissionBothSides)
Where:
— riskAmount = deposit × riskPerTrade%
— slDistance% = slPercent × (1 + slippage%) — slippage is added to the stop distance for realistic sizing
— commissionBothSides = commission% × 2 (open + close)
This formula ensures that if your stop loss is hit, you lose exactly riskAmount — not more, not less — after accounting for both slippage and round-trip commission.
What you see:
— Direction (Long / Short)
— Entry Price (manual or auto from chart)
— Stop Loss price (calculated from entry ± SL%)
— 💰 Position Size in USD — the headline number
— Margin Required (if leverage > 1)
— Quantity (units/coins/shares)
— 🔴 Risk (loss) in USD and % of deposit
— 🟢 Profit at TP — in USD, % of deposit, and net R:R after commission
— TP Price level
— Commission cost in USD
— Liquidation price (for leveraged positions)
— ⚠️ Insufficient margin warning (if position exceeds deposit)
Multi Take-Profit mode:
When enabled, the position is split across 2 or 3 TP levels with configurable volume allocation:
— TP1 at R:R 1.0 with 50% of position → locks partial profit early
— TP2 at R:R 2.0 with 30% → captures the main move
— TP3 at R:R 3.0 with 20% (if 3 TPs) → runner for extended moves
Each TP shows: profit in USD, target price. The panel also computes:
— Total blended profit across all TPs
— Net R:R (blended, after commissions)
— Breakeven price after TP1 — the price where your remaining position becomes zero-loss after banking TP1 profit. This is critical: after TP1, you move your stop to this price — the trade can no longer lose money.
Example:
Deposit: $10,000. Risk: 1% ($100). SL: 2%. Commission: 0.04%.
Position = $100 / (0.02 + 0.0008) = $4,808.
If BTC at $100,000 → SL at $98,000, TP1 at $102,000.
If stopped out → you lose exactly $100 (1% of deposit).
If TP1 hit → you gain ~$96 (after commission).
⚠️ PANEL 2 — RISK (Stress Testing + Expected Value)
This panel answers: "What happens when I have a losing streak, and is my strategy mathematically profitable?"
Daily risk limit:
maxLosingDaily = floor(dailyRiskLimit% / riskPerTrade%)
Example: 3% daily limit, 1% per trade → you stop after 3 losses in a day.
Max drawdown limit:
maxLosingTotal = floor(maxDrawdown% / riskPerTrade%)
Example: 20% max DD, 1% per trade → 20 consecutive losses to hit max DD.
Stress test — losing streaks:
The panel computes what happens after 5, 7, and 10 consecutive losses:
— depositAfterN = deposit × (1 − riskPerTrade%)^N
— drawdownAfterN = (1 − (1 − riskPerTrade%)^N) × 100%
— probabilityOfN = (1 − winrate%)^N × 100%
Example: $10,000 deposit, 1% risk, 55% winrate:
— 5 losses: −4.9% DD ($9,510), probability 1.85%
— 7 losses: −6.8% DD ($9,321), probability 0.37%
— 10 losses: −9.6% DD ($9,044), probability 0.03%
This tells you: a 5-loss streak WILL happen (1.85% probability over hundreds of trades). A 10-loss streak is extremely rare (0.03%). Your risk% must be sized so that even the realistic worst case doesn't blow your account.
Expected Value (EV):
EV per trade = winrate × riskAmount × avgR:R − (1 − winrate) × riskAmount − commission
This is the single most important number in trading. If EV > 0, your strategy makes money over time. If EV < 0, no amount of position sizing saves you.
The panel shows:
— 📈 EV per trade in USD (highlighted — this is the headline metric)
— EV per 100 trades
— Break-even winrate WITH commission — the minimum winrate needed to be profitable at your R:R, accounting for commission drag
— Your actual WR and R:R for comparison
Break-even winrate formula (with commission):
beWinrate = (1 + commissionCost / riskAmount) / (avgR:R + 1)
This is more accurate than the standard 1/(R:R+1) because it accounts for commission reducing your net edge.
📈 PANEL 3 — GROWTH (Deposit Projection + Scenarios)
This is the unique deposit growth simulator — it projects where your deposit will be after N days of consistent trading, using either compound (reinvest profits) or simple (fixed risk from initial deposit) growth.
Compound growth formula:
EV per trade as % = winrate × (risk% × R:R) − (1 − winrate) × risk%
totalTrades = tradesPerDay × projectionDays
finalDeposit = deposit × (1 + evPerTrade%)^totalTrades
Simple growth formula:
finalDeposit = deposit + deposit × evPerTrade% × totalTrades
The difference is massive. Compound growth reinvests profits — each winning trade increases the base for the next trade. Simple growth always risks a fixed amount from the initial deposit.
Example — compound vs simple:
$1,000 deposit, 55% WR, 1:2 R:R, 1% risk, 3 trades/day, 30 days:
— Simple: $1,000 + $1,000 × 0.65% × 90 = $1,585
— Compound: $1,000 × (1.0065)^90 = $1,795
Over 90 days: $1,585 vs $1,795. Over 365 days the gap becomes enormous. This is why compound growth (reinvesting profits) is the key to deposit acceleration.
Three scenarios:
— 🟢 Optimistic: your winrate + 10% (what happens if you're having a great month)
— 🟡 Realistic: your actual parameters
— 🔴 Pessimistic: your winrate − 10% (what happens during a drawdown period)
This gives you a range, not a single number. If even the pessimistic scenario is positive, your strategy is robust.
Goal milestones:
— Days to 2× deposit (double your money)
— Days to 3× deposit
— Days to custom target ($5,000, $10,000, etc.)
Formula: daysToTarget = log(target / deposit) / (log(1 + evPerTrade%) × tradesPerDay)
Risk metrics:
— Max estimated drawdown: based on expected worst losing streak × risk%
— Ruin probability: the probability of losing your entire bankroll at your current risk level
Ruin probability formula:
edge = winrate × R:R − (1 − winrate)
bankrollUnits = floor(100 / risk%)
ruinProb = ((1 − winrate) / (winrate × R:R))^bankrollUnits
If edge ≤ 0, ruin probability is effectively 100%. If edge > 0, ruin probability decreases exponentially with more bankroll units (lower risk%).
Presets for quick scenarios:
— Beginner: 45% WR, 1:2 R:R, 1% risk — conservative starting point
— Moderate: 55% WR, 1:2 R:R, 2% risk — typical intermediate trader
— Aggressive: 50% WR, 1:3 R:R, 3% risk — higher risk, needs discipline
— Custom: uses your exact My Strategy values
📐 PANEL 4 — KELLY CRITERION (Optimal Bet Sizing)
The Kelly Criterion is the mathematically optimal percentage of your bankroll to risk on each bet, given your edge. It maximizes the long-term growth rate of your account.
Kelly formula:
edge = winrate × avgR:R − (1 − winrate)
kellyPercent = edge / avgR:R
If edge ≤ 0 → Kelly = 0% (no edge, don't trade). If edge > 0 → Kelly tells you the maximum you should risk.
What the panel shows:
— Your winrate and avg R:R
— Break-even winrate (with commission)
— 📐 Edge per $1 risked — your mathematical advantage. If +$0.15, every $1 risked returns $1.15 on average.
— Full Kelly % — the theoretical maximum. Most traders should NOT use this — it's too aggressive.
— Half Kelly ✦ — the recommended practical value. Reduces variance by ~75% while giving up only ~25% of growth.
— Quarter Kelly — ultra-conservative, minimal variance.
— Your current risk % — so you can compare
— Status: 🟢 Optimal (between half and full Kelly), 🟡 Conservative (below half), 🔴 Over-bet (above full Kelly), 🚨 >2× Kelly (danger zone)
Growth rate comparison:
— Growth rate at Kelly %: the compound growth rate per trade at the optimal bet size
— Growth rate at your %: your actual compound growth rate per trade
Formula: growthRate = winrate × log(1 + risk% × R:R) + (1 − winrate) × log(1 − risk%)
If your rate is close to the Kelly rate, you're near-optimal. If it's much lower, you're leaving growth on the table. If it's negative (possible when over-betting!), you're actually losing money despite having a positive edge — the over-betting destroys the compounding.
Why this matters:
A trader with a 55% WR and 1:2 R:R has an edge. Kelly says risk ~4.6%. But if that trader risks 10% per trade (2× Kelly), their actual growth rate can become negative — they go broke despite having a winning strategy. This is the most counterintuitive result in trading mathematics: over-betting a winning system turns it into a losing system . The Kelly panel prevents this.
📖 HOW TO USE — STEP BY STEP
Step 1 — Enter your strategy parameters (My Strategy section):
— Deposit: your actual account balance in USD
— Risk per Trade: how much you risk per trade (start with 1% if unsure)
— Winrate: your historical win rate (be honest — check your journal)
— Average R:R: your average reward-to-risk on winning trades
— Trades per Day: how many trades you typically take
— Leverage: 1 for spot, or your futures leverage
— Commission: your exchange fee per side (Binance Futures taker: 0.04%)
Step 2 — Set up your current trade (Trade Setup section):
— Direction: Long or Short
— Stop Loss %: how far your SL is from entry
— Risk:Reward: your target R:R for this trade
— Entry Price: manual or auto from chart
Step 3 — Read the TRADE panel:
— The 💰 Position Size number is your order size in USD
— If using leverage, check Margin Required doesn't exceed your deposit
— Note the SL and TP prices — set these in your exchange
Step 4 — Check the RISK panel:
— Is your EV per trade positive? If not, your strategy loses money long-term
— Is your winrate above the break-even? If not, improve your R:R
— Check the stress test: can your deposit survive 7 losses in a row?
— If the risk badge shows 🚨 DANGER, reduce your risk% or leverage
Step 5 — Review the GROWTH panel:
— The projected deposit shows where you'll be in 30 days
— Check the pessimistic scenario — is it still above your starting deposit?
— Note the days to 2× — this is your compound growth timeline
— If ruin probability > 5%, your risk is too high
Step 6 — Optimize with KELLY panel:
— Compare your risk% to Half Kelly — this is the recommended level
— If Status shows 🔴 Over-bet, reduce your risk%
— If Status shows 🟡 Conservative, you could increase (but don't have to)
— Check Growth Rate at Your % — is it positive? Is it close to Kelly's rate?
🎯 PRACTICAL EXAMPLES
Example 1 — Conservative Spot Trader:
Deposit $5,000, Risk 1%, WR 55%, R:R 1:2, 2 trades/day, No leverage, Commission 0.1%
— Position: ~$2,500 per trade. Risk: $50.
— EV: +$5.60 per trade. Positive — strategy is profitable.
— 30-day projection (compound): $5,000 → $5,705 (+14.1%)
— Days to double: ~98 days
— Kelly: 4.6%. Your 1% = conservative. Status: 🟡
Example 2 — Crypto Futures Scalper:
Deposit $1,000, Risk 2%, WR 50%, R:R 1:3, 5 trades/day, Leverage 10x, Commission 0.04%
— Position: ~$10,000 per trade. Margin: $1,000. Risk: $20.
— EV: +$10.40 per trade. Strong positive edge.
— 30-day projection (compound): $1,000 → $4,680 (+368%)
— Days to double: ~14 days
— Kelly: 8.3%. Your 2% = well below Kelly. Room to grow.
— ⚠️ But 7-loss streak probability: 0.78%. DD: −13.2%. Manageable.
Example 3 — Why Over-Betting Kills:
Same as Example 2, but Risk 15% (almost 2× Kelly):
— EV per trade still positive (+$78)
— BUT growth rate per trade: NEGATIVE (−0.3%)
— 30-day projection: $1,000 → $620 (−38%)
— Kelly Status: 🚨 >2× Kelly
— Despite winning 50% with 1:3 R:R, you LOSE money because over-betting destroys compounding.
⚙️ KEY SETTINGS REFERENCE
⚙️ My Strategy:
— Deposit : account balance in USD
— Risk per Trade (default 1%): % of deposit risked per trade
— Winrate (default 55%): historical win rate
— Average R:R (default 2.0): average reward-to-risk on wins
— Trades per Day (default 3): daily trade count
— Leverage (default 1): 1 = spot, >1 = futures
— Commission (default 0.04%): exchange fee per side
🎯 Trade Setup:
— Direction : Long / Short
— Stop Loss % (default 1%): SL distance from entry
— Risk:Reward (default 2.0): target R:R
— Slippage (default 0.05%): expected execution slippage
— Entry Price : Manual or Auto (chart price)
🎯 Multi Take-Profit:
— Enable Multi TP (default Off): split into 2–3 targets
— R:R for TP1/TP2/TP3 (default 1.0/2.0/3.0)
— Volume allocation (default 50%/30%/20%)
📈 Growth Projection:
— Preset : Beginner / Moderate / Aggressive / Custom
— Projection Period (default 30 days)
— Compound (default On): reinvest profits
— Target Deposit (default 0 = off): goal amount
— Max Daily Risk (default 3%): daily loss limit
— Max Drawdown (default 20%): total DD limit
🎨 Visual:
— Font Size: Tiny / Small / Normal / Large
— Auto / Dark / Light theme
⚠️ IMPORTANT NOTES
— 📊 This is a calculator, not a signal generator. It does not produce buy/sell signals. It computes the mathematical framework for your trading decisions — position sizing, risk limits, growth projections, and optimal bet sizing. The math is universal and applies to any strategy.
— 📐 All calculations are deterministic — they depend only on your input parameters, not on price data. The dashboard updates in real-time when you change any input.
— ⚖️ The growth projection assumes consistent strategy parameters over the projection period. Real trading involves varying win rates, R:R ratios, and market conditions. The three scenarios (optimistic/realistic/pessimistic) partially address this by showing a range.
— 📏 The Kelly Criterion assumes known, fixed probabilities . In practice, your winrate and R:R fluctuate. This is why Half Kelly (not Full Kelly) is recommended — it accounts for parameter uncertainty.
— 💰 Commission is calculated as round-trip (both sides) and deducted from both profit calculations and expected value. This provides realistic net returns.
— 📊 The break-even winrate calculation includes commission drag — it's higher than the simplified 1/(R:R+1) formula because commission erodes your edge.
— 🔄 The compound growth formula uses logarithmic overflow protection — if the projected growth exceeds exp(23) ≈ 10 billion ×, it displays "∞" instead of crashing.
— 🛠️ Works on any chart, any instrument, any timeframe . The calculator is price-independent — it uses your manual inputs. "Auto" entry price mode uses the current chart close for convenience.
— 🌐 Useful for all markets : stocks (set leverage = 1, commission = 0.1%), forex (adjust for pip-based SL), crypto spot (leverage = 1), crypto futures (set your leverage), indices, commodities. 指標

FO_UtilLibrary "FO_Util"
f_inSession(startHour, startMinute, endHour, endMinute)
Parameters:
startHour (int)
startMinute (int)
endHour (int)
endMinute (int)
f_isExecutionBlocked(marketType)
Parameters:
marketType (string)
f_allowEntry(useSessionFilter, startHour, startMinute, endHour, endMinute, marketType)
Parameters:
useSessionFilter (bool)
startHour (int)
startMinute (int)
endHour (int)
endMinute (int)
marketType (string)
f_volFilter(_volume, volMA, volMultiplier)
Parameters:
_volume (float)
volMA (float)
volMultiplier (float)
f_wickCondition(_open, _close, _high, _low, _ratio, _wickSide)
Parameters:
_open (float)
_close (float)
_high (float)
_low (float)
_ratio (float)
_wickSide (int)
f_atrRangeFilter(_high, _low, _atr, _mult)
Parameters:
_high (float)
_low (float)
_atr (float)
_mult (float)
f_updatePositionExtremes(inLong, inShort, prevHigh, prevLow, highestPrev, lowestPrev)
Parameters:
inLong (bool)
inShort (bool)
prevHigh (float)
prevLow (float)
highestPrev (float)
lowestPrev (float)
f_calcATRExitLevels(avgPrice, atr, atrStopMult, atrLimitMult)
Parameters:
avgPrice (float)
atr (float)
atrStopMult (float)
atrLimitMult (float)
f_calcATRTrailStop(avgPrice, highestPrev, lowestPrev, atrPrev, trailAtrMult, atrLimitMult, atrStopMult, inLong, inShort)
Parameters:
avgPrice (float)
highestPrev (float)
lowestPrev (float)
atrPrev (float)
trailAtrMult (float)
atrLimitMult (float)
atrStopMult (float)
inLong (bool)
inShort (bool)
f_calcATRExit(avgPrice, atr, highestPrev, lowestPrev, prevHigh, prevLow, trailAtrMult, atrStopMult, atrLimitMult, inLong, inShort)
Parameters:
avgPrice (float)
atr (float)
highestPrev (float)
lowestPrev (float)
prevHigh (float)
prevLow (float)
trailAtrMult (float)
atrStopMult (float)
atrLimitMult (float)
inLong (bool)
inShort (bool)
f_executeEntry(longSignal, shortSignal)
Parameters:
longSignal (bool)
shortSignal (bool)
f_isPreClose(closeHour, closeMinute)
Parameters:
closeHour (int)
closeMinute (int)
f_executeSessionClose(useSessionClose, closeHour, closeMinute)
Parameters:
useSessionClose (bool)
closeHour (int)
closeMinute (int) 腳本庫

腳本庫
