Library

Trading_UI_ComponentsLibrary "Trading_UI_Components"
drawEntryLabel(isLong, barIdx, priceY, txt, bgCol, txtCol, sz)
Parameters:
isLong (bool) : Is Long
barIdx (int) : Bar index
priceY (float) : Y axis price
txt (string) : Label text
bgCol (color) : Background color
txtCol (color) : Text color
sz (string) : Size string ('tiny', 'small', 'normal')
Returns: Created label
drawTPLabel(isLong, barIdx, price, tpNum, pnlStr, isDCA, col)
Parameters:
isLong (bool) : Is Long
barIdx (int) : Bar index
price (float) : TP price
tpNum (int) : TP number (1, 2, 3)
pnlStr (string) : PnL formatted string
isDCA (bool) : Is DCA TP
col (color) : TP color
Returns: Created label
drawSLLabel(isLong, barIdx, price, pnlStr, isTrailing, col)
Parameters:
isLong (bool)
barIdx (int)
price (float)
pnlStr (string)
isTrailing (bool)
col (color)
drawForceExitLabel(isLong, barIdx, price, pnlStr, col)
Parameters:
isLong (bool)
barIdx (int)
price (float)
pnlStr (string)
col (color)
drawSwingLabel(fromLong, barIdx, price, pnlStr, col)
Parameters:
fromLong (bool)
barIdx (int)
price (float)
pnlStr (string)
col (color)
drawLiqLabel(isLong, barIdx, liqPrice, col)
Parameters:
isLong (bool)
barIdx (int)
liqPrice (float)
col (color)
drawMPLabel(isLong, barIdx, priceY, totalProfit)
Parameters:
isLong (bool) : Direction
barIdx (int) : Bar index for label
priceY (float) : Y-axis price (high for Long, low for Short)
totalProfit (float) : Accumulated trade PnL
Returns: Created label
persistLabel(lbl, latch, cleanup, barIdx, price, txt, isUp, col, txtCol, sz, yloc_mode)
Parameters:
lbl (label) : Current label reference (var label)
latch (bool) : Is the trigger active
cleanup (bool) : Delete label when latch goes off (Webhook=true, swpspace=false)
barIdx (int) : Bar index
price (float) : Y axis price
txt (string) : Label text
isUp (bool) : Label style up (true) or down (false)
col (color) : Background color
txtCol (color) : Text color
sz (string) : Size string ('small', 'normal', 'tiny')
yloc_mode (string) : Yloc mode: 'price', 'abovebar', 'belowbar', 'default'
Returns: Updated label reference
persistFELabel(lbl, latch, cleanup, blocked, showBlockedLbl, barIdx, price, txt, isUp, col)
Parameters:
lbl (label) : Current label reference
latch (bool) : Is trigger active
cleanup (bool) : Delete on latch off
blocked (bool) : Is the exit blocked
showBlockedLbl (bool) : Show full label when blocked
barIdx (int) : Bar index
price (float) : Y price
txt (string) : Label text
isUp (bool) : true=style_label_up, false=style_label_down
col (color) : Background color
Returns: Updated label reference
updateHLine(ln, barIdx, price, col, style, width)
Parameters:
ln (line) : Current line (if na, creates new)
barIdx (int) : Start bar index
price (float) : Price level
col (color) : Line color
style (string) : Line style
width (int) : Line width
Returns: Updated/Created line
drawHLine(ln, price, col, w, sty)
Parameters:
ln (line) : Current line reference (will be deleted if not na)
price (float) : Price level
col (color) : Line color
w (int) : Line width (default 1)
sty (string) : Style string: 'solid', 'dashed', 'dotted'
Returns: New line
deleteLines9(l1, l2, l3, l4, l5, l6, l7, l8, l9)
Parameters:
l1 (line) : Line 1 to delete
l2 (line) : Line 2 to delete
l3 (line) : Line 3 to delete
l4 (line) : Line 4 to delete
l5 (line) : Line 5 to delete
l6 (line) : Line 6 to delete
l7 (line) : Line 7 to delete
l8 (line) : Line 8 to delete
l9 (line) : Line 9 to delete
deleteLine(ln)
Parameters:
ln (line) : Line to delete
deleteAllLines(grp)
Parameters:
grp (LineGroup) : Line group
updateTPLines(grp, barIdx, tp1, tp2, tp3, colTP)
Parameters:
grp (LineGroup) : Current line group
barIdx (int) : Start bar index
tp1 (float) : TP1 price
tp2 (float) : TP2 price (na if not drawn)
tp3 (float) : TP3 price (na if not drawn)
colTP (color) : TP color
Returns: Updated line group
updateSLLine(grp, barIdx, slPrice, colSL)
Parameters:
grp (LineGroup)
barIdx (int)
slPrice (float)
colSL (color)
updateAvgLine(grp, barIdx, avgPrice, colAvg)
Parameters:
grp (LineGroup)
barIdx (int)
avgPrice (float)
colAvg (color)
panelCell(tbl, row, txt, txtCol, bgCol, tipTxt)
Parameters:
tbl (table) : Table reference
row (int) : Row number
txt (string) : Content
txtCol (color) : Text color
bgCol (color) : Background color (optional)
tipTxt (string) : Tooltip (optional)
panelCellSimple(tbl, row, txt, txtCol, bgCol)
Parameters:
tbl (table)
row (int)
txt (string)
txtCol (color)
bgCol (color)
pnlColor(pnl, posColor, negColor)
Parameters:
pnl (float) : PnL value
posColor (color) : Positive color
negColor (color) : Negative color
Returns: Appropriate color
sessionStatus(dateError, activeSession, sessionStarted)
Parameters:
dateError (bool) : Is there a date error
activeSession (bool) : Is session active
sessionStarted (bool) : Has session started
Returns:
drawPivotLines(pp, r1, r2, r3, s1, s2, s3, showPivots, colPP, colR, colS)
Parameters:
pp (float) : Pivot Point
r1 (float) : Resistance 1
r2 (float) : Resistance 2
r3 (float) : Resistance 3
s1 (float) : Support 1
s2 (float) : Support 2
s3 (float) : Support 3
showPivots (bool) : Show/Hide
colPP (color) : Pivot color
colR (color) : Resistance color
colS (color) : Support color
Returns: void (lines updated)
tpColor(tpNum, col1, col2, col3)
Parameters:
tpNum (int) : TP number (1, 2, 3)
col1 (color) : TP1 color
col2 (color) : TP2 color
col3 (color) : TP3 color
Returns: Selected color
fade(col, transp)
Parameters:
col (color) : Color
transp (int) : Transparency (0-100)
Returns: Faded color
stackY(stackCount, baseOffset)
Parameters:
stackCount (int) : Current stack count
baseOffset (float) : Base offset value (h-l or mintick*50)
Returns: Y axis offset
safeOffset()
VisualMarker
Fields:
txt (series string)
bgColor (series color)
txtColor (series color)
sz (series string)
LineGroup
Fields:
entryLine (series line)
avgLine (series line)
tp1Line (series line)
tp2Line (series line)
tp3Line (series line)
slLine (series line)
liqLine (series line)
tsLine (series line)
PanelTheme
Fields:
bgColor (series color)
borderColor (series color)
textPrimary (series color)
textGreen (series color)
textRed (series color)
textYellow (series color)
textBlue (series color)
textOrange (series color)
textCyan (series color) Library

Signal_Routing_EngineLibrary "Signal_Routing_Engine"
checkPivotCross_Anlik(sysEn, lvlEn, active, inPos, pVal)
Parameters:
sysEn (bool) : Pivot system active
lvlEn (bool) : This level active
active (bool) : This pivot active (reactivated)
inPos (bool) : Already entered from this pivot
pVal (float) : Pivot price value
Returns: Pivot triggered
checkPivotCross_MumKapanisi(sysEn, lvlEn, active, inPos, pVal, isLong)
Parameters:
sysEn (bool)
lvlEn (bool)
active (bool)
inPos (bool)
pVal (float)
isLong (bool)
checkPivotReactivate(sysEn, pVal, isLong)
Parameters:
sysEn (bool)
pVal (float)
isLong (bool)
checkPivotCross(mode, sysEn, lvlEn, active, inPos, pVal, isLong)
Parameters:
mode (string) : 'Instant' (Instant) or 'Bar Close' (Bar Close)
sysEn (bool)
lvlEn (bool)
active (bool)
inPos (bool)
pVal (float)
isLong (bool)
Returns: Pivot triggered
f_calcMACD(cfg, flagsL, flagsS)
Parameters:
cfg (MACDConfig) : MACD configuration
flagsL (MACDTrigFlags) : Long trigger flags
flagsS (MACDTrigFlags) : Short trigger flags
Returns:
allowSignal(enabled, src, lvl, rule)
Parameters:
enabled (bool) : Filter active
src (float) : Source value
lvl (float) : Comparison level
rule (string) : 'Altında Engelle' (Block Below) or 'Üstünde Engelle' (Block Above)
Returns: true = signal allowed
allowPriceSignal(enabled, line, rule)
Parameters:
enabled (bool)
line (float)
rule (string)
allowZoneSignal(enabled, zoneSrc)
Parameters:
enabled (bool)
zoneSrc (float) : >= 0.5 means zone is active (entry allowed)
Returns: true = signal allowed
allowLineRangeDual(enabled, lineLevel, pctAbove, pctBelow, modeAbove, modeBelow)
Parameters:
enabled (bool) : Filter active
lineLevel (float) : Line price level
pctAbove (float) : Above % threshold
pctBelow (float) : Below % threshold
modeAbove (string) : 'Eşik İçi' (Inside) or 'Eşik Dışı' (Outside)
modeBelow (string) : 'Eşik İçi' (Inside) or 'Eşik Dışı' (Outside)
Returns: true = signal allowed
blockPass(mode, e1, p1, e2, p2, e3, p3, eZ, pZ)
Parameters:
mode (string) : 'AND' or 'OR'
e1 (bool) : Blocker 1 enabled
p1 (bool) : Blocker 1 passed
e2 (bool) : Blocker 2 enabled
p2 (bool) : Blocker 2 passed
e3 (bool) : Blocker 3 enabled
p3 (bool) : Blocker 3 passed
eZ (bool) : Zone enabled
pZ (bool) : Zone passed
Returns: true = signal allowed
checkSignalInstant(use, src)
Parameters:
use (bool) : Source active
src (float) : Source value (0 = no signal)
Returns: true = signal exists
detectTick(use, currentVal, lastVal, prevBarVal)
Parameters:
use (bool) : Source active
currentVal (float) : Current source value
lastVal (float) : Last recorded value (held with varip)
prevBarVal (float) : Previous bar value (src )
Returns: true = new signal tick detected
zoneOrCombine(enableArray, passArray)
Parameters:
enableArray (array) : bool array: Active states
passArray (array) : bool array: Pass results
Returns: true = all filters passed (or none active)
ppZoneBlock(blockEnable, blockMode, inZone, checkSide)
Parameters:
blockEnable (bool) : Block active
blockMode (string) : 'Long', 'Short', 'Both' (Both)
inZone (bool) : Is in zone (src >= 0.5)
checkSide (string) : 'Long' or 'Short' - checked direction
Returns: true = signal BLOCKED
anySignalActive(signals)
Parameters:
signals (array) : array: 7 signal slots + pivot + MACD latch results
Returns: true = at least one signal active
finalTrigger(rawTrigger, blockPassResult, zoneCombined, pivotDistPass, ppZoneBlocked)
Parameters:
rawTrigger (bool) : Raw signal (before filters)
blockPassResult (bool) : BlockPass result
zoneCombined (bool) : Zone OR combination
pivotDistPass (bool) : Pivot distance filter
ppZoneBlocked (bool) : PP zone blocked
Returns: true = signal valid (all filters passed)
MACDConfig
Fields:
oscType (series string)
fast (series int)
slow (series int)
sig (series int)
sigType (series string)
l1 (series float)
l2 (series float)
l3 (series float)
l4 (series float)
l5 (series float)
MACDTrigFlags
Fields:
crossUP (series bool)
crossDN (series bool)
ml1U (series bool)
ml1D (series bool)
ml2U (series bool)
ml2D (series bool)
ml3U (series bool)
ml3D (series bool)
ml4U (series bool)
ml4D (series bool)
ml5U (series bool)
ml5D (series bool)
sl1U (series bool)
sl1D (series bool)
sl2U (series bool)
sl2D (series bool)
sl3U (series bool)
sl3D (series bool)
sl4U (series bool)
sl4D (series bool)
sl5U (series bool)
sl5D (series bool)
SignalSlot
Fields:
use (series bool)
src (series float)
srcPrice (series float)
BlockerConfig
Fields:
enable (series bool)
src (series float)
level (series float)
rule (series string)
LineBlockerConfig
Fields:
enable (series bool)
src (series float)
pctAbove (series float)
pctBelow (series float)
modeAbove (series string)
modeBelow (series string)
ZoneBlocker
Fields:
enable (series bool)
src (series float) Library

Strategy_Core_CalculationsLibrary "Strategy_Core_Calculations"
f_pctToPrice(pct, basePrice)
Parameters:
pct (float) : Percentage value (e.g., 2.0 = 2%)
basePrice (float) : Reference price
Returns: Price difference
f_pipsToPrice(pips, pipVal)
Parameters:
pips (float) : Number of pips (e.g., 100 pips)
pipVal (float) : Price value of 1 pip (XAUUSD: 0.01)
Returns: Price difference
f_toPrice(value, basePrice, isForex, pipVal)
Parameters:
value (float) : Distance value (% or pip)
basePrice (float) : Reference price (for percentage mode)
isForex (bool) : Is Forex mode
pipVal (float) : Pip value (for Forex mode)
Returns: Price difference
f_lotToNotional(lots, price, contractSize)
Parameters:
lots (float) : Lot amount (e.g., 0.01)
price (float) : Instrument price
contractSize (float) : Contract size (XAUUSD: 100)
Returns: Position value in Dollars
f_lotToMargin(lots, price, contractSize, leverage)
Parameters:
lots (float) : Lot amount
price (float) : Price
contractSize (float) : Contract size
leverage (int) : Leverage
Returns: Required margin (USD)
f_calcFee(notional, useFee, feePercent)
Parameters:
notional (float) : Trade volume
useFee (bool) : Is fee active
feePercent (float) : Fee percentage
Returns: Calculated fee
f_calcAvgPrice(oldAvg, oldNotional, newPrice, newNotional)
Parameters:
oldAvg (float) : Current average price
oldNotional (float) : Current position volume
newPrice (float) : New entry price
newNotional (float) : New entry volume
Returns: New weighted average price
f_multiplier(lvl, dcaMode)
Parameters:
lvl (int) : Current DCA level
dcaMode (string) : DCA mode ('Step', '2x', 'Off', 'Selection Step')
Returns: Multiplier value
f_unrealizedPnL(isLong, avgPrice, totalNotional, currentPrice)
Parameters:
isLong (bool) : Long or Short
avgPrice (float) : Average entry price
totalNotional (float) : Total volume
currentPrice (float) : Current price
Returns: Unrealized PnL
f_totalUnrealizedPnL(avgLongPrice, totalLongNotional, avgShortPrice, totalShortNotional, currentPrice)
Parameters:
avgLongPrice (float)
totalLongNotional (float)
avgShortPrice (float)
totalShortNotional (float)
currentPrice (float)
f_liqPrice_Long(avgPrice, totalNotional, availableEquity)
Parameters:
avgPrice (float) : Long average price
totalNotional (float) : Long total volume
availableEquity (float) : Available equity (balance + realized PNL - fee - short margin)
Returns: Estimated liquidation price
f_liqPrice_Short(avgPrice, totalNotional, availableEquity)
Parameters:
avgPrice (float) : Short average price
totalNotional (float) : Short total volume
availableEquity (float) : Available equity
Returns: Estimated liquidation price
f_calcTPLevels_Long(avgPrice, tp1_pct, tp2_pct, tp3_pct)
Parameters:
avgPrice (float) : Average entry price
tp1_pct (float) : TP1 percentage
tp2_pct (float) : TP2 percentage
tp3_pct (float) : TP3 percentage
Returns: TPVisuals structure
f_calcTPLevels_Short(avgPrice, tp1_pct, tp2_pct, tp3_pct)
Parameters:
avgPrice (float) : Average entry price
tp1_pct (float) : TP1 percentage
tp2_pct (float) : TP2 percentage
tp3_pct (float) : TP3 percentage
Returns: TPVisuals structure
f_calcTPLevels_Long_Unified(avgPrice, tp1_val, tp2_val, tp3_val, isForex, pipVal)
Parameters:
avgPrice (float) : Average entry price
tp1_val (float) : TP1 distance (% or pip)
tp2_val (float) : TP2 distance
tp3_val (float) : TP3 distance
isForex (bool) : Is Forex (pip) mode
pipVal (float) : Pip value (for Forex)
Returns: TPVisuals structure
f_calcTPLevels_Short_Unified(avgPrice, tp1_val, tp2_val, tp3_val, isForex, pipVal)
Parameters:
avgPrice (float)
tp1_val (float)
tp2_val (float)
tp3_val (float)
isForex (bool)
pipVal (float)
f_calcSL_Long(avgPrice, level, cfg, trailHigh)
Parameters:
avgPrice (float)
level (int)
cfg (SLConfig)
trailHigh (float)
f_calcSL_Short(avgPrice, level, cfg, trailLow)
Parameters:
avgPrice (float)
level (int)
cfg (SLConfig)
trailLow (float)
f_calcSL_Long_Unified(avgPrice, level, cfg, trailHigh, isForex, pipVal)
Parameters:
avgPrice (float)
level (int)
cfg (SLConfig)
trailHigh (float)
isForex (bool) : if true pip based, else % based
pipVal (float) : Forex pip value (for Forex mode)
Returns: tuple
f_calcSL_Short_Unified(avgPrice, level, cfg, trailLow, isForex, pipVal)
Parameters:
avgPrice (float)
level (int)
cfg (SLConfig)
trailLow (float)
isForex (bool)
pipVal (float)
f_effectiveSL(isLong, slFixed, slTrail)
Parameters:
isLong (bool) : True if Long
slFixed (float) : Fixed SL
slTrail (float) : Trailing SL (can be na)
Returns: Effective SL price
f_calcEquity(walletBalance, totalRealizedPnL, latchedPnL_L, latchedPnL_S, unrealizedTotal)
Parameters:
walletBalance (float)
totalRealizedPnL (float)
latchedPnL_L (float)
latchedPnL_S (float)
unrealizedTotal (float)
f_calcFreeMargin(equity, totalLongNotional, totalShortNotional, leverage)
Parameters:
equity (float)
totalLongNotional (float)
totalShortNotional (float)
leverage (int)
f_availableEquityForLiq(walletBalance, totalRealizedPnL, latchedPnL_L, latchedPnL_S, totalFees, useFee, otherSideNotional, leverage)
Parameters:
walletBalance (float)
totalRealizedPnL (float)
latchedPnL_L (float)
latchedPnL_S (float)
totalFees (float)
useFee (bool)
otherSideNotional (float)
leverage (int)
Returns: Available equity
f_shouldForceFullExit(posNotional, exitAmount, leverage, minThreshold)
Parameters:
posNotional (float) : Current position volume
exitAmount (float) : Amount to exit
leverage (int) : Leverage
minThreshold (float) : Minimum position size (USDT)
Returns: true if full close required
f_calcExitPnL(isLong, avgPrice, exitPrice, exitAmount)
Parameters:
isLong (bool) : Is Long
avgPrice (float) : Average price
exitPrice (float) : Exit price
exitAmount (float) : Exit amount
Returns: PnL value
f_isApproachingSL(isLong, priceExtreme, slPrice, avgPrice, approachPct)
Parameters:
isLong (bool) : Is Long
priceExtreme (float) : Low (Long) or High (Short)
slPrice (float) : SL price
avgPrice (float) : Average price
approachPct (float) : Approach threshold percentage
Returns: true if approaching
f_isApproachingLiq(isLong, priceExtreme, liqPrice, avgPrice, approachPct)
Parameters:
isLong (bool)
priceExtreme (float)
liqPrice (float)
avgPrice (float)
approachPct (float)
f_isApproachingSL_Unified(isLong, priceExtreme, slPrice, avgPrice, approachVal, isForex, pipVal)
Parameters:
isLong (bool)
priceExtreme (float)
slPrice (float)
avgPrice (float)
approachVal (float)
isForex (bool)
pipVal (float)
f_isApproachingLiq_Unified(isLong, priceExtreme, liqPrice, avgPrice, approachVal, isForex, pipVal)
Parameters:
isLong (bool)
priceExtreme (float)
liqPrice (float)
avgPrice (float)
approachVal (float)
isForex (bool)
pipVal (float)
f_forexUsedMargin(lots, price, contractSize, leverage)
Parameters:
lots (float) : Lot amount
price (float) : Price
contractSize (float) : Contract size
leverage (int) : Leverage
Returns: Used margin (USD)
f_forexFreeMargin(equity, usedMarginL, usedMarginS)
Parameters:
equity (float)
usedMarginL (float)
usedMarginS (float)
f_forexPnL(isLong, entryPrice, exitPrice, lots, contractSize, pipVal)
Parameters:
isLong (bool) : Is Long
entryPrice (float) : Entry price
exitPrice (float) : Exit price
lots (float) : Lot amount
contractSize (float) : Contract size
pipVal (float) : Pip value
Returns: PnL (USD)
f_calcPivots(method, h, l, c)
Parameters:
method (string) : Pivot method ('Traditional', 'Fibonacci', 'Woodie', 'Camarilla')
h (float) : Previous High
l (float) : Previous Low
c (float) : Previous Close
Returns:
f_getPrice(inlinePrice, currentClose)
Parameters:
inlinePrice (float)
currentClose (float)
f_stackOffset(h, l)
Parameters:
h (float)
l (float)
TPConfig
Fields:
tp1_pct (series float)
tp1_port (series float)
tp1_reverse (series bool)
tp2_active (series bool)
tp2_pct (series float)
tp2_port (series float)
tp3_active (series bool)
tp3_pct (series float)
tp3_port (series float)
DCATPConfig
Fields:
tp1_pct (series float)
tp1_port (series float)
tp2_pct (series float)
tp2_port (series float)
tp3_pct (series float)
tp3_port (series float)
SLConfig
Fields:
l1_pct (series float)
dca_pct (series float)
useBE (series bool)
be_act_pct (series float)
be_offset_pct (series float)
useTS (series bool)
ts_act_pct (series float)
ts_dev_pct (series float)
PositionConfig
Fields:
baseAmount (series float)
leverage (series int)
maxLevel (series int)
dcaMode (series string)
selectionStep (series int)
useFee (series bool)
feePercent (series float)
PositionState
Fields:
level (series int)
signalCounter (series int)
avgPrice (series float)
lastEntryPrice (series float)
totalNotional (series float)
peakNotional (series float)
pctLeft (series float)
tpStage (series int)
tpStageDCA (series int)
accumulatedPnL (series float)
TradeStats
Fields:
slCountWin (series int)
slCountLoss (series int)
liqCount (series int)
maxDcaHit (series int)
maxVol (series float)
maxLoss (series float)
grossLoss (series float)
totalFees (series float)
totalVolume (series float)
tradeCount (series int)
peakEquity (series float)
maxDrawdown (series float)
maxDrawdownPct (series float)
currentDrawdownPct (series float)
approachSL (series int)
approachLiq (series int)
TPVisuals
Fields:
tp1 (series float)
tp2 (series float)
tp3 (series float)
SLState
Fields:
slFixed (series float)
slTrail (series float)
trailExtreme (series float)
ForexConfig
Fields:
pipValue (series float)
contractSize (series float)
baseLot (series float)
isForex (series bool) Library

Lib_AlertswLibrary "Webhook_Payload_Builder"
buildCode(action, cfg)
Parameters:
action (string) : Action code (e.g., 'ENTER-LONG', 'EXIT-SHORT', etc.)
cfg (BotConfig) : Bot configuration
Returns: Formatted code string
buildMPTPSL(tpsl)
Parameters:
tpsl (AlertTPSL) : TP/SL configuration
Returns: JSON string (,"takeProfits": ,"stopLoss":{...})
enterLong(cfg, amount, tpsl)
Parameters:
cfg (BotConfig) : Bot configuration
amount (float) : Trade amount (USDT)
tpsl (AlertTPSL) : TP/SL configuration (for MP mode, if na not added)
Returns: JSON string
enterShort(cfg, amount, tpsl)
Parameters:
cfg (BotConfig) : Bot configuration
amount (float) : Trade amount (USDT)
tpsl (AlertTPSL) : TP/SL configuration (for MP mode)
Returns: JSON string
exitLong(cfg)
Parameters:
cfg (BotConfig) : Bot configuration
Returns: JSON string
exitShort(cfg)
Parameters:
cfg (BotConfig) : Bot configuration
Returns: JSON string
exitLongPartial(cfg, totalNotional, pctClose)
Parameters:
cfg (BotConfig) : Bot configuration
totalNotional (float) : Current total position volume
pctClose (float) : Percentage to close (100 = full)
Returns: JSON string
exitShortPartial(cfg, totalNotional, pctClose)
Parameters:
cfg (BotConfig) : Bot configuration
totalNotional (float) : Current total position volume
pctClose (float) : Percentage to close
Returns: JSON string
buildTPSL_Normal(tp1_pct, tp1_port, tp2_pct, tp2_port, tp3_pct, tp3_port, sl_pct)
Parameters:
tp1_pct (float)
tp1_port (float)
tp2_pct (float)
tp2_port (float)
tp3_pct (float)
tp3_port (float)
sl_pct (float)
buildTPSL_DCA(dca_tp1_pct, dca_tp1_port, dca_tp2_pct, dca_tp2_port, dca_tp3_pct, dca_tp3_port, dca_sl_pct)
Parameters:
dca_tp1_pct (float)
dca_tp1_port (float)
dca_tp2_pct (float)
dca_tp2_port (float)
dca_tp3_pct (float)
dca_tp3_port (float)
dca_sl_pct (float)
selectTPSL(level, normalTPSL, dcaTPSL)
Parameters:
level (int) : Current DCA level
normalTPSL (AlertTPSL) : Normal entry TP/SL
dcaTPSL (AlertTPSL) : DCA entry TP/SL
Returns: Appropriate AlertTPSL
formatPnL(pnl)
Parameters:
pnl (float) : PnL value
Returns: Formatted string
formatPct(pct)
Parameters:
pct (float) : Percentage value
Returns: Formatted string
formatPrice(price)
Parameters:
price (float) : Price value
Returns: Formatted string
buildEntryLabel(isLong, level, price, amount, leverage)
Parameters:
isLong (bool) : Is Long
level (int) : DCA level
price (float) : Entry price
amount (float) : Trade amount
leverage (int) : Leverage
Returns: (emoji) Level - price - amount
buildTPLabel(isLong, tpNum, price, pnl, isDCA)
Parameters:
isLong (bool) : Is Long
tpNum (int) : TP number (1, 2, 3)
price (float) : Exit price
pnl (float) : PnL value
isDCA (bool) : Is DCA TP
Returns: Formatted label string
buildSLLabel(isLong, price, pnl, isTrailing)
Parameters:
isLong (bool)
price (float)
pnl (float)
isTrailing (bool)
buildForceExitLabel(isLong, price, pnl)
Parameters:
isLong (bool)
price (float)
pnl (float)
buildSwingLabel(isLong, price, pnl)
Parameters:
isLong (bool)
price (float)
pnl (float)
swb_secretPart(cfg)
Parameters:
cfg (SWBotConfig)
swb_base(cfg, action)
Parameters:
cfg (SWBotConfig) : SWBot configuration
action (string) : Action type ('BUY', 'SELL', 'CLOSE_LONG', etc.)
Returns: JSON start
swb_buy(cfg, lotSize, slPrice)
Parameters:
cfg (SWBotConfig) : SWBot configuration
lotSize (float) : Lot amount
slPrice (float) : SL price (if na, SL not added)
Returns: JSON string
swb_sell(cfg, lotSize, slPrice)
Parameters:
cfg (SWBotConfig) : SWBot configuration
lotSize (float) : Lot amount
slPrice (float) : SL price (if na, SL not added)
Returns: JSON string
swb_buy_tpsl(cfg, lotSize, slPips, tpPips)
Parameters:
cfg (SWBotConfig)
lotSize (float)
slPips (float) : SL distance (pips)
tpPips (float) : TP distance (pips)
Returns: JSON string
swb_sell_tpsl(cfg, lotSize, slPips, tpPips)
Parameters:
cfg (SWBotConfig)
lotSize (float)
slPips (float)
tpPips (float)
swb_closeLong(cfg)
Parameters:
cfg (SWBotConfig)
swb_closeShort(cfg)
Parameters:
cfg (SWBotConfig)
swb_closeLongPartial(cfg, lotToClose)
Parameters:
cfg (SWBotConfig)
lotToClose (float) : Lot amount to close
swb_closeShortPartial(cfg, lotToClose)
Parameters:
cfg (SWBotConfig)
lotToClose (float)
swb_amendLong(cfg, slPrice, tpPrice)
Parameters:
cfg (SWBotConfig)
slPrice (float) : New SL price
tpPrice (float) : New TP price
swb_amendShort(cfg, slPrice, tpPrice)
Parameters:
cfg (SWBotConfig)
slPrice (float)
tpPrice (float)
swb_amendSLLong(cfg, slPrice)
Parameters:
cfg (SWBotConfig)
slPrice (float)
swb_amendSLShort(cfg, slPrice)
Parameters:
cfg (SWBotConfig)
slPrice (float)
swb_amendTrailingLong(cfg, slPrice)
Parameters:
cfg (SWBotConfig)
slPrice (float) : SL price (broker trailing start point)
swb_amendTrailingShort(cfg, slPrice)
Parameters:
cfg (SWBotConfig)
slPrice (float)
exchA_openLong(cfg, qtyInCoin)
Parameters:
cfg (ExchangeConfigA) : configuration
qtyInCoin (float) : Trade amount in Coin
exchA_openShort(cfg, qtyInCoin)
Parameters:
cfg (ExchangeConfigA)
qtyInCoin (float)
exchA_closeLong(cfg)
Parameters:
cfg (ExchangeConfigA)
exchA_closeShort(cfg)
Parameters:
cfg (ExchangeConfigA)
exchA_closeLongPartial(cfg, pct)
Parameters:
cfg (ExchangeConfigA)
pct (float)
exchA_closeShortPartial(cfg, pct)
Parameters:
cfg (ExchangeConfigA)
pct (float)
exchB_base(cfg)
Parameters:
cfg (ExchangeConfigB)
exchB_openLong(cfg, qtyInCoin)
Parameters:
cfg (ExchangeConfigB)
qtyInCoin (float)
exchB_openShort(cfg, qtyInCoin)
Parameters:
cfg (ExchangeConfigB)
qtyInCoin (float)
exchB_closeLong(cfg, qtyInCoin)
Parameters:
cfg (ExchangeConfigB)
qtyInCoin (float)
exchB_closeShort(cfg, qtyInCoin)
Parameters:
cfg (ExchangeConfigB)
qtyInCoin (float)
exchB_closeLongPartial(cfg, partialQty)
Parameters:
cfg (ExchangeConfigB)
partialQty (float)
exchB_closeShortPartial(cfg, partialQty)
Parameters:
cfg (ExchangeConfigB)
partialQty (float)
BotConfig
Fields:
exchangeName (series string)
symbolInput (series string)
botName (series string)
tfStr (series string)
botID (series string)
useMultiPair (series bool)
leverage (series int)
AlertTPSL
Fields:
tp1_pct (series float)
tp1_port (series float)
tp2_pct (series float)
tp2_port (series float)
tp3_pct (series float)
tp3_port (series float)
sl_pct (series float)
SWBotConfig
Fields:
licenseKey (series string)
secretKey (series string)
symbol (series string)
pipValue (series float)
contractSize (series float)
useBrokerTPSL (series bool)
useMultiPos (series bool)
ExchangeConfigA
Fields:
symbol (series string)
strategyId (series string)
maxLag (series int)
ExchangeConfigB
Fields:
symbol (series string)
signalId (series string)
uid (series string)
positionSide (series string) Library

TO_JSONTO_JSON
A lightweight Pine Script v6 library for converting PulseWire series data into JSON-formatted alert payloads.
`TO_JSON` is designed for users who want to export chart data to external systems through PulseWire alerts.
It helps transform rolling series such as OHLCV, indicator values, or text states into JSON-compatible arrays and wraps them into a structured message for webhooks, bots, dashboards, or automated workflows.
What this library does
This library provides helper functions to:
- convert float series into JSON arrays
- convert integer series into JSON arrays using a sentinel value as `null`
- convert string series into JSON arrays with fallback filling and JSON-safe escaping
- wrap custom payloads into a top-level JSON alert message with symbol, timeframe, timestamp, and token
It is especially useful when you want to send the latest `N` bars of market data or indicator values to an external service.
Features
- Rolling array export for `float`, `int`, and `string` series
- Chronological output from oldest to newest
- `null` support for missing values
- JSON-safe string escaping
- Simple wrapper for alert message generation
- Works well for webhook-based automation and downstream parsing
Exported functions
### `series_to_array_float_null(series float src, int N)`
Converts the latest `N` values of a float series into a JSON array string.
Missing values are exported as `null`.
`series_to_array_int_sentinel(series int src, int N, int sentinel)`
Converts the latest `N` values of an integer series into a JSON array string.
The specified sentinel value is exported as `null`.
`series_to_array_str_fill(series string src, int N, string fill="")`
Converts the latest `N` values of a string series into a JSON array string.
Missing values are replaced with `fill`, and strings are escaped for JSON compatibility.
`json(simple string token="1234567890", string info="", simple string symbol="AUTO")`
Wraps a custom JSON payload into a top-level alert message including:
- symbol
- timeframe
- current timestamp
- human-readable time
- info payload
- token
Typical use case
A common use case is exporting the last bars of:
- time
- open
- high
- low
- close
- volume
- moving averages
- custom signals
into one flat JSON object, then embedding it into the alert message.
Example
```pine
//@version=6
import veegee82/TO_JSON/1 as json
indicator("TO_JSON Example", overlay=false)
stO = open
stH = high
stL = low
stC = close
stV = volume
ema_50 = ta.ema(close, 50)
ema_100 = ta.ema(close, 100)
ema_200 = ta.ema(close, 200)
ema_500 = ta.ema(close, 500)
ema_1000 = ta.ema(close, 1000)
json_flat(int n=50) =>
s_name = '"name":"' + 'vision_' + timeframe.period + '"'
s_tf = ',"timeframe":"' + timeframe.period + '"'
s_ts = ',"ts":' + json.series_to_array_float_null(time, n)
s_o = ',"open":' + json.series_to_array_float_null(stO, n)
s_h = ',"high":' + json.series_to_array_float_null(stH, n)
s_l = ',"low":' + json.series_to_array_float_null(stL, n)
s_c = ',"close":' + json.series_to_array_float_null(stC, n)
s_v = ',"volume":' + json.series_to_array_float_null(stV, n)
s_ema_50 = ',"ema_50":' + json.series_to_array_float_null(ema_50, n)
s_ema_100 = ',"ema_100":' + json.series_to_array_float_null(ema_100, n)
s_ema_200 = ',"ema_200":' + json.series_to_array_float_null(ema_200, n)
s_ema_500 = ',"ema_500":' + json.series_to_array_float_null(ema_500, n)
s_ema_1000 = ',"ema_1000":' + json.series_to_array_float_null(ema_1000, n)
"{" + s_name + s_tf + s_ts + s_o + s_h + s_l + s_c + s_v + s_ema_50 + s_ema_100 + s_ema_200 + s_ema_500 + s_ema_1000 + "}"
info = json_flat(100)
alert(
message = json.json(token = "1234567890", info = info, symbol = "AUTO"),
freq = alert.freq_once_per_bar_close
) Library

Chew Library Library "AssetCorrelationUtils"
detectIndicesFutures(ticker)
Detects Index Futures (NQ/ES/YM/RTY + micro variants)
Parameters:
ticker (string) : The ticker string to check (typically syminfo.ticker)
Returns: AssetPairing with secondary and tertiary assets configured
detectMetalsFutures(ticker)
Detects Metal Futures (GC/SI + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectForexFutures(ticker)
Detects Forex Futures (6E/6B + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectEnergyFutures(ticker)
Detects Energy Futures (CL/RB/HO + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectTreasuryFutures(ticker)
Detects Treasury Futures (ZB/ZF/ZN)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectCryptoFutures(ticker)
Detects CME Crypto Futures (BTC/ETH + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectCADFutures(ticker)
Detects CAD Forex Futures (6C + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectForexCFD(ticker, tickerId)
Detects Forex CFD pairs (EUR/GBP/DXY, USD/JPY/CHF triads)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID (syminfo.tickerid) for primary asset
Returns: AssetPairing with secondary and tertiary assets configured
detectCrypto(ticker, tickerId)
Detects major Crypto assets (BTC, ETH, SOL, XRP, alts)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with secondary and tertiary assets configured
detectMetalsCFD(ticker, tickerId)
Detects Metals CFD (XAU/XAG/Copper)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with secondary and tertiary assets configured
detectIndicesCFD(ticker, tickerId)
Detects Indices CFD (NAS100/SP500/DJ30)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with secondary and tertiary assets configured
detectEUStocks(ticker, tickerId)
Detects EU Stock Indices (GER40/EU50) - Dyad only
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with secondary asset configured (tertiary empty for dyad)
getDefaultFallback(tickerId)
Returns default fallback assets (chart ticker only, no correlation)
Parameters:
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with chart ticker as primary, empty secondary/tertiary (no correlation)
applySessionModifierWithBackadjust(tickerStr, sessionType)
Applies futures session modifier to ticker WITH back adjustment
Parameters:
tickerStr (string) : The ticker to modify
sessionType (string) : The session type (syminfo.session)
Returns: Modified ticker string with session and backadjustment.on applied
applySessionModifierNoBackadjust(tickerStr, sessionType)
Applies futures session modifier to ticker WITHOUT back adjustment
Parameters:
tickerStr (string) : The ticker to modify
sessionType (string) : The session type (syminfo.session)
Returns: Modified ticker string with session and backadjustment.off applied
isTriadMode(pairing)
Checks if a pairing represents a valid triad (3 assets)
Parameters:
pairing (AssetPairing) : The AssetPairing to check
Returns: True if tertiary is non-empty (triad mode), false for dyad
getAssetTicker(tickerId)
Extracts clean ticker string from full ticker ID
Parameters:
tickerId (string) : The full ticker ID (e.g., "BITGET:BTCUSDT.P")
Returns: Clean ticker string (e.g., "BTCUSDT.P")
resolveTriad(chartTickerId, pairing)
Resolves triad asset assignments with proper inversion flags
Parameters:
chartTickerId (string) : The current chart's ticker ID (syminfo.tickerid)
pairing (AssetPairing) : The detected AssetPairing
Returns: Tuple
resolveDyad(chartTickerId, pairing)
Resolves dyad asset assignment with proper inversion flag
Parameters:
chartTickerId (string) : The current chart's ticker ID
pairing (AssetPairing) : The detected AssetPairing (dyad: tertiary is empty)
Returns: Tuple
resolveAssets(ticker, tickerId, assetType, sessionType, useBackadjust)
Main auto-detection entry point. Detects asset category and returns fully resolved config.
Parameters:
ticker (string) : The ticker string to check (typically syminfo.ticker)
tickerId (string) : The full ticker ID (typically syminfo.tickerid)
assetType (string) : The asset type (typically syminfo.type)
sessionType (string) : The session type for futures (typically syminfo.session)
useBackadjust (bool) : Whether to apply back adjustment for futures session alignment
Returns: AssetConfig with fully resolved assets, inversion flags, and detection status
resolveCurrentChart()
Simplified auto-detection using current chart's syminfo values
Returns: AssetConfig with fully resolved assets, inversion flags, and detection status
AssetPairing
Core asset pairing structure for triad/dyad configurations
Fields:
primary (series string) : The primary (chart) asset ticker ID
secondary (series string) : The secondary correlated asset ticker ID
tertiary (series string) : The tertiary correlated asset ticker ID (empty for dyad)
invertSecondary (series bool) : Whether secondary asset should be inverted for divergence calc
invertTertiary (series bool) : Whether tertiary asset should be inverted for divergence calc
AssetConfig
Full asset resolution result with mode detection and computed values
Fields:
detected (series bool) : Whether auto-detection succeeded
isTriadMode (series bool) : True if triad (3 assets), false if dyad (2 assets)
primary (series string) : The resolved primary asset ticker ID
secondary (series string) : The resolved secondary asset ticker ID
tertiary (series string) : The resolved tertiary asset ticker ID (empty for dyad)
invertSecondary (series bool) : Computed inversion flag for secondary asset
invertTertiary (series bool) : Computed inversion flag for tertiary asset
assetCategory (series string) : String describing the detected asset category Library

Library

Library

fsl_helpersLibrary "fsl_helpers"
A library with function helpers for FSL script family, including functions for plotting, formatting, etc.
@version=6
plot_width_get()
Returns the internal panel width used by the helper library.
Returns: int Width of the custom plot panel.
plot_x_axis(x, inc, theme)
Draws a vertical tick and label on the custom X-axis of the panel.
Parameters:
x (int) : X-axis coordinate in panel space.
inc (float) : Label value displayed below the tick.
theme (Theme type from QuantNomad/fsl_theme/3) : Theme used for the chart
plot_y_axis(yy, min, max, theme, plot_mult)
Draws a horizontal Y-axis guide line and corresponding price label.
Converts the normalized panel coordinate to the actual price level.
Parameters:
yy (float) : Normalized Y coordinate in panel space.
min (float) : Minimum value of the plotted price range.
max (float) : Maximum value of the plotted price range.
theme (Theme type from QuantNomad/fsl_theme/3) : Theme used for the chart
plot_mult (int) : Horizontal spacing multiplier used by the panel.
Returns: void
plot_scale(y, min, max)
Converts a price value into the normalized panel scale used
by the forward-curve plotting area.
Parameters:
y (float) : Price value to scale.
min (float) : Minimum value of the plotted price range.
max (float) : Maximum value of the plotted price range.
Returns: float Normalized Y coordinate for plotting.
plot_scatter(x, y, max, min, col, s, tiptool, theme, plot_mult)
Draws a scatter-point marker in the forward-curve panel.
Optionally attaches a tooltip containing symbol, time, and price.
Parameters:
x (int) : X index position within the curve.
y (float) : Price value of the point.
max (float) : Maximum value of the plotted price range.
min (float) : Minimum value of the plotted price range.
col (color) : Marker color.
s (string) : Marker size.
tiptool (string) : Text shown in the tooltip.
theme (Theme type from QuantNomad/fsl_theme/3) : Theme used for the chart
plot_mult (int) : Horizontal spacing multiplier used by the panel.
Returns: void
plot_line(x, y, max, min, x1, y1, col, w, sty, plot_mult)
Draws a line segment between two curve points in the panel.
Used to connect consecutive futures contracts in the forward curve.
Parameters:
x (int) : X position of the ending point.
y (float) : Price value of the ending point.
max (float) : Maximum value of the plotted price range.
min (float) : Minimum value of the plotted price range.
x1 (int) : X position of the starting point.
y1 (float) : Price value of the starting point.
col (color) : Line color.
w (int) : Line width.
sty (string) : Line style.
plot_mult (int) : Horizontal spacing multiplier used by the panel.
Returns: void
plot_legend(y, col, sty, txt, theme, plot_mult)
Draws a legend entry composed of a marker, line sample, and label.
Parameters:
y (float) : Y position of the legend row.
col (color) : Legend color.
sty (string) : Line style used for the sample segment.
txt (string) : Legend label text.
theme (Theme type from QuantNomad/fsl_theme/3) : Theme used for the chart
plot_mult (int) : Horizontal spacing multiplier used by the panel.
Returns: void
plot_remove_all_boxes()
Deletes all boxes currently drawn by the script.
Useful before redrawing the custom panel.
Returns: void
plot_remove_all_labels()
Deletes all labels currently drawn by the script.
Useful before redrawing the custom panel.
Returns: void
plot_remove_all_lines()
Deletes all lines currently drawn by the script.
Useful before redrawing the custom panel.
Returns: void
plot_main_boxes(main_title, theme, plot_mult)
Draws the main panel boxes for the forward-curve display, including
frame, title area, legend area, and timeframe header.
Parameters:
main_title (string) : Main title for the plot
theme (Theme type from QuantNomad/fsl_theme/3) : Theme used for the chart
plot_mult (int) : Horizontal spacing multiplier used by the panel.
Returns: void Library

Library

Library

HighClassCalculationsLibrary "HighClassCalculations"
Advanced Pine Script v6 calculation library for statistical, normalization, trend, and risk metrics.
safeDiv(numerator, denominator, fallback)
Safe division helper that prevents division-by-zero errors.
Parameters:
numerator (float) : Value on the top of the fraction.
denominator (float) : Value on the bottom of the fraction.
fallback (float) : Value returned when denominator is zero.
Returns: Result of the division or fallback.
clamp(value, minValue, maxValue)
Clamps a value into a fixed range.
Parameters:
value (float) : Source value.
minValue (float) : Minimum allowed value.
maxValue (float) : Maximum allowed value.
Returns: Clamped value.
rescale(value, oldMin, oldMax, newMin, newMax)
Rescales a value from one range into another range.
Parameters:
value (float) : Source value.
oldMin (float) : Source range minimum.
oldMax (float) : Source range maximum.
newMin (float) : Target range minimum.
newMax (float) : Target range maximum.
Returns: Rescaled value.
normalize(src, len)
Returns the min-max normalized position of a series within a rolling window.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Value between 0 and 1 when the range is valid.
rangePercent(src, len)
Returns the source position inside its rolling range as a percentage.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Value between 0 and 100 when the range is valid.
zScore(src, len)
Calculates the z-score of a series.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Standardized z-score.
robustZScore(src, len)
Calculates a robust z-score using median absolute deviation.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Robust z-score less sensitive to outliers.
percentileRank(src, len)
Calculates percentile rank for the latest value inside a rolling window.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Percentile rank from 0 to 100.
percentileValue(src, len, percentile)
Calculates the value at a requested percentile inside a rolling window.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
percentile (float) : Requested percentile from 0 to 100.
Returns: Percentile value.
simpleReturn(src)
Calculates simple arithmetic return versus the previous bar.
Parameters:
src (float) : Price or equity series.
Returns: One-bar simple return.
logReturn(src)
Calculates log return versus the previous bar.
Parameters:
src (float) : Price or equity series.
Returns: One-bar log return.
compoundedReturn(src, len)
Calculates cumulative return over a fixed lookback.
Parameters:
src (float) : Price or equity series.
len (int) : Lookback window.
Returns: Return from src to current src.
realizedVolatility(src, len, annualization)
Calculates realized volatility from log returns and annualizes it.
Parameters:
src (float) : Price or equity series.
len (int) : Rolling lookback window.
annualization (float) : Number of bars used for annualization.
Returns: Annualized volatility.
downsideDeviation(returnSeries, len, mar, annualization)
Calculates downside deviation from a return series.
Parameters:
returnSeries (float) : Series of returns, not raw price.
len (int) : Rolling lookback window.
mar (float) : Minimum acceptable return.
annualization (float) : Number of bars used for annualization.
Returns: Annualized downside deviation.
rollingSharpe(returnSeries, len, riskFreeRate, annualization)
Calculates a rolling Sharpe ratio from a return series.
Parameters:
returnSeries (float) : Series of returns, not raw price.
len (int) : Rolling lookback window.
riskFreeRate (float) : Per-bar risk free rate.
annualization (float) : Number of bars used for annualization.
Returns: Annualized Sharpe ratio.
rollingSortino(returnSeries, len, mar, annualization)
Calculates a rolling Sortino ratio from a return series.
Parameters:
returnSeries (float) : Series of returns, not raw price.
len (int) : Rolling lookback window.
mar (float) : Minimum acceptable return.
annualization (float) : Number of bars used for annualization.
Returns: Annualized Sortino ratio.
efficiencyRatio(src, len)
Calculates Kaufman's efficiency ratio.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Efficiency ratio from 0 to 1.
regressionSlope(src, len)
Calculates rolling linear regression slope.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Slope per bar.
regressionAngle(src, len)
Converts rolling regression slope into an angle.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Slope angle in degrees.
beta(asset, benchmark, len)
Calculates rolling beta versus a benchmark series.
Parameters:
asset (float) : Asset series.
benchmark (float) : Benchmark series.
len (int) : Rolling lookback window.
Returns: Beta coefficient.
alpha(asset, benchmark, len, riskFreeRate)
Calculates Jensen-style alpha versus a benchmark series.
Parameters:
asset (float) : Asset return series.
benchmark (float) : Benchmark return series.
len (int) : Rolling lookback window.
riskFreeRate (float) : Per-bar risk free rate.
Returns: Alpha over the rolling window.
ulcerIndex(src, len)
Calculates the Ulcer Index for a series.
Parameters:
src (float) : Price or equity series.
len (int) : Rolling lookback window.
Returns: Ulcer Index value.
maxDrawdown(src, len)
Calculates the maximum drawdown over a rolling window.
Parameters:
src (float) : Price or equity series.
len (int) : Rolling lookback window.
Returns: Maximum drawdown as a negative decimal.
atrPercent(len, src)
Calculates ATR as a percentage of price.
Parameters:
len (simple int) : ATR lookback window.
src (float) : Reference price used for the percentage denominator.
Returns: ATR percent.
relativeVolume(len)
Calculates relative volume versus its rolling average.
Parameters:
len (simple int) : Rolling lookback window.
Returns: Volume divided by average volume.
getAllFunctions()
Returns a comma-separated list of all exported calculation helpers.
Returns: Function catalog for quick reference. Library

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

Library

Library

Library

Library

Library

ONS_ForexSessionLibLibrary "ONS_ForexSessionLib"
Library for DST-adjusted Forex session detection. Returns session state and timing for a given bar.
Thanks to the author of "Sessions Full Markets Forex Stocks Index 7 Time by TFlab"
DST_Detector(Start_Month, Start_Day, Start_CountDay, End_Month, End_Day, End_CountDay, TimeZone)
Detects whether DST is Active or Inactive for a given timezone.
Parameters:
Start_Month (int) : Month DST begins (int)
Start_Day (int) : Day-of-week DST begins (int, use dayofweek.* constants)
Start_CountDay (int) : Nth occurrence of Start_Day in Start_Month (int)
End_Month (int) : Month DST ends (int)
End_Day (int) : Day-of-week DST ends (int)
End_CountDay (int) : Nth occurrence of End_Day in End_Month (int)
TimeZone (string) : IANA timezone string, use "Australia/Sydney" to invert logic (string)
Returns: "Active" or "Inactive" (string)
getDSTStates()
Returns DST state for Sydney, London and New York at the current bar.
Returns: — each "Active" or "Inactive" (tuple of strings)
getForexSessionStrings(Sydney_DST, London_DST, NewYork_DST)
Returns UTC session strings for all Forex sessions, DST-adjusted.
Parameters:
Sydney_DST (string) : DST state string for Sydney ("Active"/"Inactive")
London_DST (string) : DST state string for London ("Active"/"Inactive")
NewYork_DST (string) : DST state string for New York ("Active"/"Inactive")
Returns: session strings (tuple of strings)
isInSession(sessionStr, tz)
Returns 1 if the bar at the current series position is inside a session, 0 otherwise.
Parameters:
sessionStr (string) : Session string in "HHMM-HHMM" format (string)
tz (string) : IANA or UTC offset timezone string for the session (string)
Returns: 1 if inside session, 0 if outside (int)
isBarInSession(targetIndex, sessionStr, tz)
Returns 1 if a specific bar_index is inside a session (for point-in-time lookup).
Parameters:
targetIndex (int) : bar_index to test (int)
sessionStr (string) : Session string "HHMM-HHMM" (string)
tz (string) : IANA or UTC offset timezone string (string)
Returns: 1 if the target bar is/was inside session, 0 otherwise (int)
getAllForexSessions()
One-shot helper: given the current bar, returns open/closed state for all
DST-adjusted Forex sessions simultaneously.
Returns:
Each value is 1 (open) or 0 (closed). (tuple of ints) Library

Vantage_LO1_Sizing**Overview**
Position-sizing library for the LO1 breakout box day-trading strategy. Provides a unified recoup (opposite-add) sizing pipeline and dollar-risk/profit helpers. Extracting these functions into a library avoids Pine Script's function inlining, reducing compiled token count in the main strategy.
**Exported Type: RecoupSizingResult**
Holds the output of the 8-step sizing pipeline:
• Micro-level quantities (raw, DLL-capped, final)
• YM-level quantities (pre/post min-1-YM policy, proxy-capped)
• Risk gate values (projected loss, worst-case drawdown, pass/fail)
• Recoup scenario P&L (net outcome if T1 stops and recoup wins)
**Exported Functions**
`f_calcTradeRiskDollars(entry, stop, qty)` → float
Projected risk in dollars. Converts price distance to ticks via syminfo.mintick, then to dollars via syminfo.pointvalue.
`f_calcTradeProfitDollars(entry, tp, qty)` → float
Projected profit in dollars. Same tick-to-dollar conversion applied to the take-profit distance.
`f_computeRecoupSizing(...)` → RecoupSizingResult
8-step recoup sizing pipeline:
1. Raw micro qty from risk multiplier (CEILING)
2. Daily loss limit cap at micro level
3. Micro-to-YM conversion (FLOOR)
4. Minimum-1-YM policy
5. Proxy capacity cap
6. Micro-equivalent for risk gating
7. Worst-case projection (base stop + opposing flatten + recoup stop)
8. Risk gate pass/fail
Plus scenario P&L: net recoup outcome and T1-win profit.
**Usage**
import Vantage-Stack/Vantage_LO1_Sizing/1 as sz
float risk = sz.f_calcTradeRiskDollars(entry, stop, qty)
sz.RecoupSizingResult r = sz.f_computeRecoupSizing(baseQty, baseEntry, baseStop, recoupEntry, recoupStop,
recoupTP, multiplier, proxyMul, minOneYM, curLoss, maxLoss, maxProxy, t1TP, oppTP, oppFrac, oppRemoval)
======================
Library "Vantage_LO1_Sizing"
Position sizing library for LO1 breakout box strategy.
Extracts pure-computation functions to reduce compiled token count in the main script.
f_calcTradeRiskDollars(_entry, _stop, _qty)
Calculates projected risk in dollars for a position (qty × |entry−stop| in ticks × pointvalue).
Parameters:
_entry (float) : Entry price
_stop (float) : Stop-loss price
_qty (float) : Position quantity (contracts)
Returns: Risk in dollars
f_calcTradeProfitDollars(_entry, _tp, _qty)
Calculates projected profit in dollars for a position (qty × |tp−entry| in ticks × pointvalue).
Parameters:
_entry (float) : Entry price
_tp (float) : Take-profit price
_qty (float) : Position quantity (contracts)
Returns: Profit in dollars
f_computeRecoupSizing(baseQtyMicro, baseEntry, baseStop, recoupEntry, recoupStop, recoupTP, oppositeMultiplier, proxyQtyMul, minOneYMEnabled, currentLossDollars, maxDailyLossLimit, maxProxyCap, t1TPPrice, oppTPPrice, oppAddStopFrac, opposingRemovalEnabled)
Computes recoup (opposite-add) position sizing through an 8-step pipeline: raw micro qty, DLL cap, micro-to-YM conversion, min-1-YM policy, proxy cap, risk gating, worst-case projection, and recoup scenario P&L.
Parameters:
baseQtyMicro (int) : T1 micro-contract quantity
baseEntry (float) : T1 entry price
baseStop (float) : T1 stop-loss price
recoupEntry (float) : Recoup entry price
recoupStop (float) : Recoup stop-loss price
recoupTP (float) : Recoup take-profit price
oppositeMultiplier (float) : Target risk multiplier for recoup vs T1 (e.g., 4.0)
proxyQtyMul (float) : Micro-to-YM conversion factor (0 = no proxy)
minOneYMEnabled (bool) : Force minimum 1 YM contract when proxy is active
currentLossDollars (float) : Running session loss in dollars (0 for estimate mode)
maxDailyLossLimit (float) : Daily loss limit in dollars (-1 = disabled)
maxProxyCap (int) : Maximum proxy contracts cap (0 = unlimited)
t1TPPrice (float) : T1 take-profit price (for scenario P&L calculation)
oppTPPrice (float) : Opposing MYM TP price when T1 stops (for scenario profit calc)
oppAddStopFrac (float) : Fraction of base risk for opposite MYM emergency flatten
opposingRemovalEnabled (bool) : Whether opposing removal entry mode is active
Returns: RecoupSizingResult with quantities, risk values, and scenario P&L
RecoupSizingResult
Holds the complete output of the 8-step recoup sizing pipeline: micro/YM quantities, risk gate results, worst-case projections, and recoup-scenario P&L.
Fields:
microQtyRaw (series int)
microCapByDLL (series int)
microQtyCapped (series int)
ymQtyPre (series int)
ymQtyFinal (series int)
microEqForGate (series int)
projectedLossRecoup (series float)
dllRemaining (series float)
totalWorstCase (series float)
riskOK (series bool)
oppMYMLoss (series float)
didMinOneOverride (series bool)
dllForcedZero (series bool)
recoupScenarioNet (series float)
t1WinProfit (series float) Library

SMC_CoreEN:
Trying to fix something that keeps breaking is exhausting; you’re done reopening the same file hoping for a different ending—because why do we keep reopening the same folder of memories when we already know it’s corrupted? 💾 It’s like loving someone who treated your heart like a draft they never planned to publish. Being ghosted is strange and unfinished 👻—it leaves you as a glitch in their timeline while you keep checking for updates on a story that isn’t yours anymore. You don’t need closure from someone who wasn’t brave enough to give it; their silence was the loudest answer 🔕. Stop waiting for notifications from someone who only appears when they need a backup plan. Some people aren’t meant to stay—and moving on isn’t dramatic. Sometimes it’s simply choosing clarity, stability, and a version of yourself that no longer settles for less ✨
ID:
Berusaha memperbaiki sesuatu yang terus rusak itu melelahkan; kamu berhenti membuka file yang sama dengan harapan ending-nya berubah—padahal kamu tahu folder itu sudah rusak 💾 Mencintai orang yang memperlakukan hatimu seperti draft yang tak pernah ingin dipublikasikan memang melelahkan. Di-ghosting itu aneh dan gantung 👻—kamu jadi seperti glitch di timeline mereka sementara terus mengecek update dari cerita yang bukan milikmu lagi. Kamu tidak butuh penjelasan dari orang yang bahkan tak cukup berani memberi perpisahan; diamnya mereka sudah jadi jawaban paling keras 🔕 Berhenti menunggu notifikasi dari orang yang muncul hanya saat butuh cadangan. Tidak semua orang ditakdirkan untuk tinggal—dan move on bukan selalu dramatis. Kadang itu hanya soal memilih kejelasan, kestabilan, dan versi diri yang tidak lagi mau menerima kurang dari yang pantas ✨
====
SMC Core Utilities Library
A comprehensive utility library designed for Smart Money Concepts (SMC) and ICT-based trading strategies. This library provides standardized objects and methods to detect price imbalances and manage trading sessions effectively.
Key Features:
- Gap Detection: Advanced logic to identify Fair Value Gaps (FVG), Volume Imbalances (VI), and Liquidity Voids (LV).
- Session Management: Automated parsing and validation of trading sessions with midnight-cross support.
- Visual Helpers: Standardized enums for line styles, font sizes, and labeling.
- Optimized: Uses custom Types and Methods for modular and efficient code execution.
Library utilitas lengkap yang dirancang untuk strategi berbasis Smart Money Concepts (SMC) dan ICT. Library ini menyediakan objek dan metode standar untuk mendeteksi ketidakseimbangan harga dan mengelola sesi trading.
Fitur Utama:
- Deteksi Gap: Logika untuk identifikasi Fair Value Gap (FVG), Volume Imbalance (VI), dan Liquidity Void (LV).
- Manajemen Sesi: Validasi sesi trading otomatis (London, NY, Asia) dengan dukungan perpindahan hari.
- Visual Helper: Standarisasi gaya garis, ukuran font, dan penamaan label.
- Optimal: Menggunakan Custom Types dan Methods agar kode lebih bersih dan ringan.
Library

Library
