MRScoringLibraryLibrary "MRScoringLibrary"
Mean-reversion graduated scoring: z-score any indicator into -3 to +3 integer scale.
mrScore(src, lookback, alreadyZ, invert)
Converts any continuous indicator value into a graduated
mean-reversion score from -3 (deep overbought) to +3 (deep oversold).
Parameters:
src (float) : Raw indicator value (or z-score if alreadyZ=true)
lookback (int) : Rolling lookback for z-score calc (ignored if alreadyZ=true)
alreadyZ (bool) : True if src is already a z-score — skips internal z-scoring
invert (bool) : True if HIGH indicator value = oversold (flips mapping)
Returns: Integer score: +3 to -3
zScore(src, lookback)
Returns the raw z-score without mapping to graduated scale.
Useful for plotting or custom threshold logic.
Parameters:
src (float) : Raw indicator value
lookback (int) : Rolling lookback period
Returns: Float z-score
mrScoreCustom(src, lookback, alreadyZ, invert, sd1, sd2, sd3)
Same as mrScore but with configurable SD band edges.
For indicators where standard 1/2/3 SD bands don't fit well
(e.g., an indicator only becomes useful at 1.5 SD).
Parameters:
src (float) : Raw indicator value (or z-score if alreadyZ=true)
lookback (int) : Rolling lookback for z-score calc
alreadyZ (bool) : True if src is already a z-score
invert (bool) : True if HIGH value = oversold
sd1 (float) : Inner band threshold (default would be 1.0)
sd2 (float) : Middle band threshold (default would be 2.0)
sd3 (float) : Outer band threshold (default would be 3.0)
Returns: Integer score: +3 to -3 Library

MRTestingLibraryLibrary "MRTestingLibrary"
Mean-reversion graduated scoring: z-score any indicator into -3 to +3 integer scale.
mrScore(src, lookback, alreadyZ, invert)
Converts any continuous indicator value into a graduated
mean-reversion score from -3 (deep overbought) to +3 (deep oversold).
Parameters:
src (float) : Raw indicator value (or z-score if alreadyZ=true)
lookback (int) : Rolling lookback for z-score calc (ignored if alreadyZ=true)
alreadyZ (bool) : True if src is already a z-score — skips internal z-scoring
invert (bool) : True if HIGH indicator value = oversold (flips mapping)
Returns: Integer score: +3 to -3
zScore(src, lookback)
Returns the raw z-score without mapping to graduated scale.
Useful for plotting or custom threshold logic.
Parameters:
src (float) : Raw indicator value
lookback (int) : Rolling lookback period
Returns: Float z-score
mrScoreCustom(src, lookback, alreadyZ, invert, sd1, sd2, sd3)
Same as mrScore but with configurable SD band edges.
For indicators where standard 1/2/3 SD bands don't fit well
(e.g., an indicator only becomes useful at 1.5 SD).
Parameters:
src (float) : Raw indicator value (or z-score if alreadyZ=true)
lookback (int) : Rolling lookback for z-score calc
alreadyZ (bool) : True if src is already a z-score
invert (bool) : True if HIGH value = oversold
sd1 (float) : Inner band threshold (default would be 1.0)
sd2 (float) : Middle band threshold (default would be 2.0)
sd3 (float) : Outer band threshold (default would be 3.0)
Returns: Integer score: +3 to -3 Library

Library

MyLibraryPubLibrary "MyLibraryPub"
TODO: add library description here
futu_ema(src, len)
与futu的MA系统,保持一致
Parameters:
src (float)
len (int)
MaxEMA(c)
多头ema最大值
Parameters:
c (float)
MaxEMA10(c)
多头ema最大值,10
Parameters:
c (float)
isEmpty(inStr)
空字符判定
Parameters:
inStr (string)
Bull_Max(tk, tf)
进入多头价格
Parameters:
tk (string)
tf (string)
Bull_Day(tk, tf)
多头天数
Parameters:
tk (string)
tf (string)
Bull(tk, tf)
是否多头
Parameters:
tk (string)
tf (string)
Bull10(tk, tf)
是否多头10
Parameters:
tk (string)
tf (string)
Bull_BuyMax(tk, tf)
可以买的最大值
Parameters:
tk (string)
tf (string)
Bull_BuyStatus(tk, tf)
当前状态
Parameters:
tk (string)
tf (string)
pct_D20(tk, tf)
涨幅
Parameters:
tk (string)
tf (string)
pct_D10(tk, tf)
涨幅
Parameters:
tk (string)
tf (string)
pct_D5(tk, tf)
涨幅
Parameters:
tk (string)
tf (string) Library

Library

FMatrixSCLibraryLibrary "FMatrixSCLibrary"
defaultTheme()
calcEnv(adx, rsi, atr_pr, er, mean_ext, btcRet, date, dir)
Parameters:
adx (float)
rsi (float)
atr_pr (float)
er (float)
mean_ext (float)
btcRet (float)
date (string)
dir (string)
pushEnv(arr, snap, maxSize)
Parameters:
arr (array)
snap (EnvSnap)
maxSize (int)
calcSys(history, tradeNum, date, dir, r, wl, earlyExit, equity, peakEq, dd, dow, quarter, cycleYear)
Parameters:
history (array)
tradeNum (int)
date (string)
dir (string)
r (float)
wl (int)
earlyExit (bool)
equity (float)
peakEq (float)
dd (float)
dow (string)
quarter (string)
cycleYear (int)
pushSys(arr, snap, maxSize)
Parameters:
arr (array)
snap (SysSnap)
maxSize (int)
renderEnvTable(t, snaps, maxRows, sysCode, theme)
Parameters:
t (table)
snaps (array)
maxRows (int)
sysCode (string)
theme (SCTheme)
renderSysTable(t, snaps, maxRows, sysCode, theme)
Parameters:
t (table)
snaps (array)
maxRows (int)
sysCode (string)
theme (SCTheme)
SCTheme
Fields:
bg (series color)
hdr (series color)
row (series color)
row2 (series color)
txt (series color)
dim (series color)
cyan (series color)
bull (series color)
bear (series color)
gold (series color)
grid (series color)
EnvSnap
Fields:
date (series string)
dir (series string)
adx (series float)
rsi (series float)
atr_pr (series float)
er (series float)
mean_ext (series float)
btc_ret (series float)
SysSnap
Fields:
num (series int)
date (series string)
dir (series string)
r (series float)
wl (series int)
early_exit (series bool)
equity (series float)
peak_eq (series float)
dd (series float)
state (series string)
streak (series int)
wr20 (series float)
dow (series string)
quarter (series string)
cycle_year (series int) Library

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

Library

MarketStructureLibMarket Structure Library (MSL)
A Multi-Timeframe Structural Analysis Toolkit for Pine Script
A Developer's Library for Building Advanced Structural Analysis Indicators.
🎓 THEORETICAL FOUNDATION
The Market Structure Library (MSL) is a collection of functions and data types designed for Pine Script developers to build custom structural analysis indicators. It provides a framework for analyzing market geometry, liquidity, and order flow across multiple timeframes. The library's functions handle complex calculations related to multi-timeframe data aggregation and analysis.
The system is organized around four functional pillars that work together to provide a unified structural context.
Pillar 1: Unified Liquidity Context
The library's primary function is to create a unified view of market activity. It includes logic to automatically detect if real footprint data is available.
With Footprint Data: It utilizes bid-ask volume, delta, and Value Area metrics for analysis.
Without Footprint Data: It employs a mathematical OHLCV proxy to model bar dynamics and approximate buy/sell pressure, absorption, and aggressor intent.
This dual-mode capability allows indicators built with the library to function consistently regardless of the user's data source.
Pillar 2: Multi-Timeframe Structure Aggregation
Market structure is fractal, with higher timeframe levels influencing lower timeframe price action. The MSL is designed to manage this by providing a master container (MultiTFStructure) that holds and organizes structural data—including swing points, value areas, and dynamic levels—for up to four user-defined timeframes. This allows a script to query and act on a complete, multi-layered market picture.
Pillar 3: Dynamic Structure - The Siege Corridor
The MSL introduces ' Siege Corridors ,' which are dynamic trendlines projected from consecutive pivot points. These are data objects that are updated with price interaction statistics, including hit count , energy decay , order flow alignment , and the calculated probability of a break or failure .
Pillar 4: High-Probability Confluence Zones
Significant price action often occurs where structure from multiple timeframes aligns. The library's find_zones function is a discovery utility that scans all tracked levels across all timeframes. It identifies these Confluence Zones where levels cluster, calculating their combined strength, dominant type (supply/demand), and overall bias.
🔧 COMPREHENSIVE API & DATA TYPES
This library provides developers with a set of data structures (types) to utilize in their scripts. A clear understanding of these types is essential for proper implementation.
Core Data Types
MarketContext: A per-bar snapshot of liquidity, blending Footprint and OHLCV models. Includes unified_delta, absorption, spread_proxy, and vol_quality.
LevelLiquidity: A detailed analysis of order flow specifically at a structural level. Provides hold_probability, break_probability, and an action_type classifier ("defending", "absorbing", "attacking").
StructureLevel: Represents a single horizontal level (e.g., POC, VAH, Swing High/Low). Contains its price, level_type, timeframe, strength, age, and its own LevelLiquidity object.
SiegeCorridor: The complete object for a dynamic trendline. Contains anchor points, slope, hit_count, decay, and break_prob/fail_prob.
Container Types
TimeframeStructure: The container for all structural information for a single timeframe. It holds the poc, vah, val_, an array of all StructureLevel objects, and the res_corridor and sup_corridor.
MultiTFStructure: The master object that a script will primarily interact with. It holds up to four TimeframeStructure objects, providing the complete multi-timeframe view.
Analysis & State Types
ConfluenceZone: An object representing a cluster of levels. Contains the zone's average price, width, level_count, and combined_strength.
StructureState: A high-level summary for decision-making logic. Provides nearest_support, nearest_resistance, net_bias, and a boolean for whether price is inside_value.
IntrabarState: Designed for real-time, tick-level analysis. Indicates if price is currently touching a POC, VAH, Siege Corridor, or Confluence Zone.
🎨 VISUALIZING THE STRUCTURE (IMPLEMENTATION EXAMPLES)
The provided images demonstrate visualizations that can be built using the data objects from the MSL. The library supplies the calculated data; the developer controls the visual output.
Drawing Confluence Zones (Boxes)
Use the find_zones() function to get an array of ConfluenceZone objects. For each zone:
The box's vertical position is determined by zone.price.
The box's height is determined by zone.width.
The box's color can be conditional on zone.dominant_type ("supply" or "demand").
The box's styling (e.g., opacity) can be driven by zone.combined_strength.
Drawing Siege Corridors (Channels)
Access the res_corridor and sup_corridor from a TimeframeStructure object.
The central dashed line is drawn from corr.anchor_bar_a/corr.anchor_price_a to the current bar, extended by corr.slope.
Outer boundary lines can be drawn parallel to the central line, offset by an ATR-based value.
Drawing Value Area & Swing Levels (Horizontal Lines)
Iterate through the levels array within each TimeframeStructure.
Use level.price to draw the line.
Use get_level_color(level) to apply a consistent color scheme based on the level.level_type.
Creating Informative Labels
Labels can be generated by combining data from library objects. A label for a resistance level could display:
Level Type & Timeframe: level.level_type + level.timeframe
Hold/Break Probabilities: Access level.liquidity.hold_probability when price interacts with the level.
Siege Stats: For a siege corridor, display corr.hit_count and corr.fail_prob.
📚 DEVELOPER INTEGRATION GUIDE
This guide outlines the process for integrating the MSL into a Pine Script indicator.
Step 1: Import & Initialization
Import the library and initialize the master MultiTFStructure container in the script's global scope.
import DskyzInvestments/MarketStructureLib/1 as msl
var msl.MultiTFStructure structure = msl.create_structure()
Step 2: Define Timeframes & Collect Data
Define the timeframes for analysis. Use request.security to retrieve the required OHLCV and pivot data for each timeframe.
// --- INPUTS ---
tf1 = input.timeframe("15", "Timeframe 1")
pivot_len = input.int(15, "Pivot Lookback")
// --- DATA COLLECTION ---
// Request TF1 data using request.security()
// Collect historical arrays of highs, lows, pivots, etc. for TF1
Step 3: Get Unified Market Context
Once per bar, generate the fused liquidity context. This object is passed to other functions for liquidity calculations.
// --- MAIN LOGIC ---
float atr_val = ta.atr(14)
footprint fp = request.footprint(100, 70) // Optional: use 'na' if not using footprint
msl.MarketContext ctx = msl.get_market_context(open, high, low, close, volume, fp, ta.sma(volume, 20), nz(structure.tf1.poc ), atr_val)
Step 4: Update the Structure Container
On each bar, update the respective TimeframeStructure object within the master container.
// Calculate TF1's Value Area from historical arrays
= msl.calc_unified_poc_va(h_arr1, l_arr1, c_arr1, v_arr1, 24, fp)
// Update the structure object for TF1
structure.tf1 := msl.update_structure(structure.tf1, poc1, vah1, val1, sh_p1, sh_b1, sl_p1, sl_b1, tf1, atr_val, ctx)
// Repeat for structure.tf2, etc.
Step 5: Analyze and Use the Data
With the structure updated, perform high-level analysis using the state and zone functions.
// Find Confluence Zones with a 0.3% price tolerance
array zones = msl.find_zones(structure, 0.3)
// Get the high-level summary state
msl.StructureState state = msl.get_structure_state(structure, close, false)
// Use state.net_bias, state.nearest_support, etc. for indicator logic
// Get Real-Time Intra-Bar State for precise alerts
float alert_tolerance = atr_val * 0.1
msl.IntrabarState ib_state = msl.scan_intrabar_levels(structure, zones, close, alert_tolerance)
if ib_state.at_confluence
alert("Price is at " + ib_state.active_level_name, alert.freq_once_per_bar)
Step 6: Visualization
Use the data from the structure, zones, and state objects to implement the script's visual elements (lines, boxes, tables, labels).
🔮 CONCLUSION
The Market Structure Library (MSL) library provides a structured set of tools for developers working with multi-timeframe market structure. By encapsulating complex calculations for data aggregation, liquidity modeling, and geometric analysis, it allows developers to focus on the specific logic and visualization of their custom indicators. The library is designed to serve as a foundational component for building detailed and context-aware analysis tools in Pine Script. Library

Objective Market Structure FrameworkThis library provides a systematic, rule-based approach to categorize market movements into four objective phases: Compression, Expansion, Distribution, and Consolidation.
Instead of subjective chart patterns, this tool uses volatility-relative thresholds (ATR) and momentum filters to identify significant trading ranges and structural breaks.
Main Use Cases:
Clear & Compact MTF Visualization: Map higher-timeframe (HTF) market structures directly onto your lower-timeframe (LTF) charts. Provides a clean, non-cluttered overview for an intuitive display of key levels without overcomplicating the chart.
Automated Setup Classification: Assign specific trading setups to distinct market regimes (Uptrends, Corrections, Sideways Ranges). Enables rapid, objective analysis every trading day, eliminating the need for manual re-evaluation or "hunting" for the current trend state.
Core Features:
Volatility-Adaptive: Range calculations scale automatically with the market's current ATR, making the analysis relevant across all asset classes.
MTF-Optimized Performance: Engineered for professional Multi-Timeframe workflows. Fetch 19 structural variables with a single request.security() call to minimize script load and prevent memory errors.
Momentum Validation: Distinguishes between high-conviction structural breaks and low-momentum "noise" using body-to-ATR ratios.
Reliability & Stability: Built-in Guard-Clauses protect against "Bar 0" and "NA" runtime errors, even when requesting lower timeframe data from a higher timeframe chart.
Key Parameters (Customizable Defaults):
Distribution Threshold (e.g. 1.2): Identifies price movement beyond the established range to confirm trend strength.
Compression (e.g. 1.5x ATR): Detects low-volatility buildup phases.
Expansion (e.g. 4.0x ATR): Flags explosive "Huge Range" impulses.
How to use (Educational Example included):
The source code contains a fully functional MTF Dashboard example (commented out at the bottom). It demonstrates how to map the library’s output variables into a visual trading interface, showing HTF trend alignment and real-time market phases.
Quick Start (Implementation):
import arnipoer/PriceActionStructure/1 as pa
// Single request for all 19 structural variables
=
request.security(syminfo.tickerid, "D",
pa.get_structure(true, 1.0, close, 14, 1.2, 1.5, 4.0))
// Example: Visualization
plot(strHigh, color=color.aqua, title="HTF Structure High")
bgcolor(hugeRange ? color.new(color.purple, 80) : na, title="Expansion Alert")
Disclaimer: No financial advice. Trading involves significant risk. This is an analytical tool for professional traders to build their own systematic strategies. Library

Library

equity_curveLibrary "equity_curve"
f_remove_exchange_name(name)
Remove exchange prefix from ticker string (e.g., "BINANCE:BTCUSD" → "BTCUSD")
Parameters:
name (simple string) : Ticker string potentially containing exchange prefix
Returns: Ticker without exchange prefix
f_roc()
Calculate bar-over-bar return as decimal (close-to-close, for buy-and-hold)
Returns: Return as decimal (e.g., 0.02 for +2%)
f_roc_entry()
Calculate open-to-close return (realistic strategy entry assumption at bar open)
Returns: Intrabar return as decimal
f_equity(ticker1, ticker2, ticker3, ticker4, ticker5, ticker6, best_asset, r1, r2, r3, r4, r5, r6, backtest, prev_equity, prev_peak, prev_dd)
Calculate strategy equity for a rotation system (stateless — caller must maintain var state).
Uses best_asset so signal is visible 1 bar before equity acts on it.
Parameters:
ticker1 (simple string) : Asset 1 ticker string
ticker2 (simple string) : Asset 2 ticker string
ticker3 (simple string) : Asset 3 ticker string
ticker4 (simple string) : Asset 4 ticker string
ticker5 (simple string) : Asset 5 ticker string
ticker6 (simple string) : Asset 6 ticker string
best_asset (string) : The currently selected best-performing asset ticker
r1 (float) : Per-bar return for asset 1 (open-to-close)
r2 (float) : Per-bar return for asset 2
r3 (float) : Per-bar return for asset 3
r4 (float) : Per-bar return for asset 4
r5 (float) : Per-bar return for asset 5
r6 (float) : Per-bar return for asset 6
backtest (bool) : Whether backtesting is active this bar
prev_equity (float) : Previous bar's equity value (caller initializes var as na)
prev_peak (float) : Previous bar's peak equity value (caller initializes var as na)
prev_dd (float) : Previous bar's max drawdown value (caller initializes var as 0.0)
Returns:
f_buy_and_hold(r, backtest, prev_equity, prev_peak, prev_dd)
Calculate buy-and-hold equity for a single asset (stateless — caller must maintain var state)
Parameters:
r (float) : Per-bar return (close-to-close)
backtest (bool) : Whether backtesting is active this bar
prev_equity (float) : Previous bar's equity value (caller initializes var as na)
prev_peak (float) : Previous bar's peak equity value (caller initializes var as na)
prev_dd (float) : Previous bar's max drawdown value (caller initializes var as 0.0)
Returns:
f_since(active, prev_count)
Calculate lookback period as bar count since condition became true (stateless — caller must maintain var state)
Parameters:
active (bool) : Whether the counting condition is active this bar
prev_count (int) : Previous bar's raw count (caller initializes var as 0)
Returns: — output is the adjusted lookback for metrics; count is the raw counter to feed back next bar
f_best_asset_col(ticker1, ticker2, ticker3, ticker4, ticker5, ticker6, best_asset, backtest, colors)
Return color for equity curve based on currently held asset.
Uses best_asset so signal is visible 1 bar before equity execution.
Parameters:
ticker1 (simple string) : Asset 1 ticker string
ticker2 (simple string) : Asset 2 ticker string
ticker3 (simple string) : Asset 3 ticker string
ticker4 (simple string) : Asset 4 ticker string
ticker5 (simple string) : Asset 5 ticker string
ticker6 (simple string) : Asset 6 ticker string
best_asset (string) : The confirmed best-performing asset ticker
backtest (bool) : Whether backtesting is active
colors (array) : Array of 8 colors:
Returns: Color corresponding to the currently held asset
f_PerformanceMetrics(base, Lookback, backtest, max_drawdown)
Calculate performance metrics from an equity curve
Parameters:
base (float) : The equity curve series
Lookback (int) : Number of bars to analyze (capped at 4998)
backtest (bool) : Whether backtesting is active
max_drawdown (float) : Maximum drawdown value (pre-calculated, as decimal e.g. 0.25 = 25%)
Returns: Array of 10 floats:
f_PerfMetricTable(p, ticker1, ticker2, ticker3, ticker4, ticker5, ticker6, strategy, a1, a2, a3, a4, a5, a6, colors)
Populate a performance metrics comparison table. Caller must create the table with `var` and pass it in.
Should only be called on barstate.islast.
Parameters:
p (table) : Pre-created table (caller uses: var table p = table.new(position.top_left, 8, 15, ...))
ticker1 (simple string) : Asset 1 ticker string
ticker2 (simple string) : Asset 2 ticker string
ticker3 (simple string) : Asset 3 ticker string
ticker4 (simple string) : Asset 4 ticker string
ticker5 (simple string) : Asset 5 ticker string
ticker6 (simple string) : Asset 6 ticker string
strategy (array) : Strategy metrics array (from f_PerformanceMetrics)
a1 (array) : Buy-and-hold metrics for asset 1
a2 (array) : Buy-and-hold metrics for asset 2
a3 (array) : Buy-and-hold metrics for asset 3
a4 (array) : Buy-and-hold metrics for asset 4
a5 (array) : Buy-and-hold metrics for asset 5
a6 (array) : Buy-and-hold metrics for asset 6
colors (array) : Array of 8 colors
Returns: The table object Library

Lib_SW_VisualLibrary "Lib_SW_Visual"
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

Lib_Sw_SignalsLibrary "Lib_Sw_Signals"
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) : 'Anlık' (Instant) or 'Mum Kapanışı' (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', 'Her İkisi' (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

Lib_SW_CoreLibrary "Lib_SW_Core"
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 ('Adım'/'Step', '2x', 'Kapalı'/'Off', 'Seçim Adımlı'/'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 ('Geleneksel', '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_SW_AlertsLibrary "Lib_SW_Alerts"
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

GLLV_HelpersLibrary "GLLV_Helpers"
buildAlertMsg(pineLic, ticker, risk, sl, tp, strategyCode)
Parameters:
pineLic (string)
ticker (string)
risk (float)
sl (float)
tp (float)
strategyCode (string)
isRising(src, points, step)
Parameters:
src (float)
points (int)
step (int)
regimeOf(pip2, posLimit, negLimit)
Parameters:
pip2 (float)
posLimit (float)
negLimit (float)
calcMata(fast, mid, slow)
Parameters:
fast (float)
mid (float)
slow (float)
crossUpByColor(src, ema, pvsraColor, expectedColor)
Parameters:
src (float)
ema (float)
pvsraColor (color)
expectedColor (color)
crossDownByColor(src, ema, pvsraColor, expectedColor)
Parameters:
src (float)
ema (float)
pvsraColor (color)
expectedColor (color)
calcSlope(src, length, mult, method)
Parameters:
src (float)
length (simple int)
mult (float)
method (string)
createDebugTable()
updateDebugTable(tbl, row, label, value)
Parameters:
tbl (table)
row (int)
label (string)
value (string) Library

Library

VisualStructureToolsLibrary "VisualStructureTools"
MTF-safe drawing library (Unix-Time). Designed for high visual discrimination and efficient debugging of complex logic without cluttering the main script.
Optimized for Pine Script® v6 to prevent runtime errors in multi-timeframe environments.
setLine(price, startTime, labelText, labelPos, is_extend, l_width, l_col, l_style)
Draws a horizontal level or a segment with an optional label.
Parameters:
price (float) : Price level for the line.
startTime (int) : UNIX timestamp (ms) for the starting point.
labelText (string) : Text to display on the label. Use "none" to hide.
labelPos (string) : Position of the label relative to the price ('above' or 'below', 'none').
is_extend (bool) : If true, the line extends infinitely (extend.both).
l_width (int) : Width of the line in pixels.
l_col (color) : Color for the line and label text.
l_style (string) : Style of the line ('solid', 'dashed', 'dotted').
setBox(top, bottom, startTime, endTime, boxText, b_col, b_width, b_style, b_transp)
Draws a filled box with an optional synchronized text label.
Parameters:
top (float) : Price of the upper boundary.
bottom (float) : Price of the lower boundary.
startTime (int) : UNIX timestamp (ms) for the left side of the box.
endTime (int) : UNIX timestamp (ms) for the right side (defaults to current 'time').
boxText (string) : Optional text label for the box. Use "" to hide.
b_col (color) : Border and fill color.
b_width (int) : Border width.
b_style (string) : Border style ('solid', 'dashed', 'dotted').
b_transp (int) : Transparency for the background fill (0-100). Library

smaemarvwapClaireLibrary "smaemarvwapClaire"
repeat_character(count)
Parameters:
count (int)
f_1_k_line_width()
is_price_in_merge_range(p1, p2, label_merge_range)
Parameters:
p1 (float)
p2 (float)
label_merge_range (float)
get_pre_label_string(kc, t, is_every)
Parameters:
kc (VWAP_key_levels_draw_settings)
t (int)
is_every (bool)
f_is_new_period_from_str(str)
Parameters:
str (string)
total_for_time_when(source, days, ma_set)
Parameters:
source (float)
days (int)
ma_set (ma_setting)
f_calculate_sma_ema_rolling_vwap(src, length, ma_settings)
Parameters:
src (float)
length (simple int)
ma_settings (ma_setting)
f_calculate_sma_ema_rvwap(ma_settings)
Parameters:
ma_settings (ma_setting)
f_get_ma_pre_label(ma_settings, sma, ema, rolling_vwap)
Parameters:
ma_settings (ma_setting)
sma (float)
ema (float)
rolling_vwap (float)
f_smart_ma_calculation(ma_settings2)
Parameters:
ma_settings2 (ma_setting)
f_calculate_endpoint(start_time, kc, is_every, endp, extend1, extend2, line_label_extend_length)
Parameters:
start_time (int)
kc (VWAP_key_levels_draw_settings)
is_every (bool)
endp (int)
extend1 (bool)
extend2 (bool)
line_label_extend_length (int)
f_single_line_label_fatory(left_point, right_point, line_col, line_width, lines_style_select, labeltext_col, label_text_size, label_array, line_array, label_col, label_text, l1, label1)
根据两个点创建线段和/或标签,并将其添加到对应的数组中
Parameters:
left_point (chart.point) : 左侧起点坐标
right_point (chart.point) : 右侧终点坐标
line_col (color) : 线段颜色
line_width (int) : 线段宽度
lines_style_select (string) : 线段样式(实线、虚线等)
labeltext_col (color) : 标签文字颜色
label_text_size (string) : 标签文字大小
label_array (array) : 存储标签对象的数组
line_array (array) : 存储线段对象的数组
label_col (color) : 标签背景颜色(默认:半透明色)
label_text (string) : 标签文字内容(默认:空字符串)
l1 (bool) : 是否创建线段(默认:false)
label1 (bool) : 是否创建标签(默认:false)
Returns: void
f_line_and_label_merge_func(t, data, l_text, kc, is_every, endp, merge_str_map, label_array, line_array, extend1, extend2, line_label_extend_length, label_merge_control, line_width, lines_style_select, label_text_size)
Parameters:
t (int)
data (float)
l_text (string)
kc (VWAP_key_levels_draw_settings)
is_every (bool)
endp (int)
merge_str_map (map)
label_array (array)
line_array (array)
extend1 (bool)
extend2 (bool)
line_label_extend_length (int)
label_merge_control (bool)
line_width (int)
lines_style_select (string)
label_text_size (string)
plot_ohlc(kc, ohlc_data, extend1, extend2, merge_str_map, label_array, line_array, is_every, line_label_extend_length, label_merge_control, line_width, lines_style_select, label_text_size)
Parameters:
kc (VWAP_key_levels_draw_settings)
ohlc_data (bardata)
extend1 (bool)
extend2 (bool)
merge_str_map (map)
label_array (array)
line_array (array)
is_every (bool)
line_label_extend_length (int)
label_merge_control (bool)
line_width (int)
lines_style_select (string)
label_text_size (string)
plot_vwap_keylevels(kc, vwap_data, extend1, extend2, merge_str_map, label_array, line_array, is_every, line_label_extend_length, label_merge_control, line_width, lines_style_select, label_text_size)
Parameters:
kc (VWAP_key_levels_draw_settings)
vwap_data (vwap_snapshot)
extend1 (bool)
extend2 (bool)
merge_str_map (map)
label_array (array)
line_array (array)
is_every (bool)
line_label_extend_length (int)
label_merge_control (bool)
line_width (int)
lines_style_select (string)
label_text_size (string)
plot_vwap_bardata(kc, ohlc_data, vwap_data, extend1, extend2, merge_str_map, label_array, line_array, is_every, line_label_extend_length, label_merge_control, line_width, lines_style_select, label_text_size)
Parameters:
kc (VWAP_key_levels_draw_settings)
ohlc_data (bardata)
vwap_data (vwap_snapshot)
extend1 (bool)
extend2 (bool)
merge_str_map (map)
label_array (array)
line_array (array)
is_every (bool)
line_label_extend_length (int)
label_merge_control (bool)
line_width (int)
lines_style_select (string)
label_text_size (string)
f_start_end_total_min(session)
Parameters:
session (string)
f_get_vwap_array(anchor1, data_manager, is_historical)
Parameters:
anchor1 (string)
data_manager (data_manager)
is_historical (bool)
f_get_bardata_array(anchorh, data_manager, is_historical)
Parameters:
anchorh (string)
data_manager (data_manager)
is_historical (bool)
vwap_snapshot
Fields:
t (series int)
vwap (series float)
upper1 (series float)
lower1 (series float)
upper2 (series float)
lower2 (series float)
upper3 (series float)
lower3 (series float)
VWAP_key_levels_draw_settings
Fields:
enable (series bool)
index (series int)
anchor (series string)
session (series string)
vwap_col (series color)
bands_col (series color)
bg_color (series color)
text_color (series color)
val (series bool)
poc (series bool)
vah (series bool)
enable2x (series bool)
enable3x (series bool)
o_control (series bool)
h_control (series bool)
l_control (series bool)
c_control (series bool)
extend_control (series bool)
only_show_the_lastone_control (series bool)
bg_control (series bool)
line_col_labeltext_col (series color)
bardata
Fields:
o (series float)
h (series float)
l (series float)
c (series float)
v (series float)
start_time (series int)
end_time (series int)
ma_setting
Fields:
day_control (series bool)
kline_numbers (series int)
ma_color (series color)
ema_color (series color)
rvwap_color (series color)
ma_control (series bool)
ema_control (series bool)
rvwap_control (series bool)
session (series string)
merge_label_template
Fields:
left_point (chart.point)
right_point (chart.point)
label_text (series string)
p (series float)
label_color (series color)
merge_init_false (series bool)
anchor_snapshots
Fields:
vwap_current (array)
vwap_historical (array)
bardata_current (array)
bardata_historical (array)
data_manager
Fields:
snapshots_map (map)
draw_settings_map (map) Library

Synapse_VSync_LibV-Sync (Volume Synchronization) is a multi-dimensional macro-confluence engine. It aggregates four objective market truths into a single synchronized bias (0.0 to 1.0) to filter signals and define market regime.
The Four Pillars of V-Sync
1. Base Volume (Temporal Flux)
Engine: Exponentially weighted volume flow.
Logic: up_volume / total_volume with a math.exp(-i/lookback) decay.
Utility: Capturing sustained momentum in raw participation. It filters out low-volume "fakeout" moves that lack broad participation.
2. Footprint (Order Flow Delta)
Engine: Micro-delta tracking (Institutional Tape).
Logic: Normalized ratio of aggressive buy orders vs sell orders, sourced from LTF footprint or synthetic body-to-wick estimation.
Utility: Identifying where "Smart Money" is actively committing capital in real-time.
3. TICK Data (Market Internals)
Engine: Exchange-wide breadth internals.
Index Mapping:
SPX/ES: NYSE:TICK
NQ/NDX: NASDAQ:TICKQ
Fidelity: Processes intrabar HT/LT extremes to capture high-speed institutional sweeps.
Commitment Levels: Benchmarked at 800 (MOO alignment), 1000 (Extreme), and 1200 (Climax).
4. Thermal Map (Structural Binning)
Engine: Range-based volume distribution (Heatmap).
Logic: 30-bin price-range analysis. Identifies if the current price is supported by "Buy Liquidity" below or capped by "Sell Liquidity" above.
Utility: Visualizing structural depth and identifying high-probability zones where price is likely to stick or bounce.
Interaction & Intelligence Modules
5. Interaction Tooltips
Engine: Dynamic string generator.
Logic: Aggregates pillars (V-Sync, TICK, Heatmap) and local interaction (Delta, OB Bias) into a human-readable forensic report.
Utility: Provides instant clarity on why a level is reacting (e.g., "Institutional Defense" vs "Passive Absorption").
6. Delta Aggregation (Defense vs Aggression)
Engine: Decaying session delta sum.
Logic: Tracks footprint delta at discrete price levels. Categorizes bias as:
Aggressive (A): Delta moves in the direction of the break (Push).
Defensive (D): Delta moves against the local price interaction (Absorption/Soaking).
Utility: Standardizing the interpretation of footprint across all Synapse indicators.
7. Universal Plot Auditing
Engine: Kinetic flux interaction logic.
Logic: Allows auditing of any technical plot line (Moving Averages, VWAP, Anchored Levels) for touches, cross-overs, and structural fidelity.
Utility: Enables the entire Synapse forensic suite to be applied to any existing indicator's data lines.
Library Architecture: Synapse_VSync_Lib
Key Functions
f_get_tick_source(): Auto-detects SPX vs NQ for correct internal sourcing.
f_calc_tick_extreme(): High-fidelity internal pressure tracking.
f_vsync_stack(): Blends all pillars into a weighted consensus.
HUD Representation
Indicators utilizing the full stack display V-STACK (instead of V-SYNC), signifying that Market Internals and Structural structural depth are being calculated alongside volume flow.
License: Open Source (MIT License) Library

FMatrixLibraryLibrary "FMatrixLibrary"
f_family(code)
Parameters:
code (string)
f_execMode(fam)
Parameters:
fam (int)
f_structure(fam)
Parameters:
fam (int)
f_tfStyle(tf)
Parameters:
tf (string)
f_regimeCompat(stype, swingReg, dayReg, scalpReg, tfStyle)
Parameters:
stype (string)
swingReg (string)
dayReg (string)
scalpReg (string)
tfStyle (string)
f_riskMin(style)
Parameters:
style (string)
f_riskMax(style)
Parameters:
style (string)
f_minRR(style)
Parameters:
style (string)
f_ddState(ddR)
Parameters:
ddR (float)
f_aTier(enabled, ddOk, regimeOk, sessOk, dayOk, quarterOk, yearOk, equityOk, biasOk)
Parameters:
enabled (bool)
ddOk (bool)
regimeOk (bool)
sessOk (bool)
dayOk (bool)
quarterOk (bool)
yearOk (bool)
equityOk (bool)
biasOk (bool)
f_bTier(aTier, enabled, ddOk, regimeOk, equityOk)
Parameters:
aTier (bool)
enabled (bool)
ddOk (bool)
regimeOk (bool)
equityOk (bool)
f_regColor(reg)
Parameters:
reg (string)
f_tierColor(tier)
Parameters:
tier (string)
f_ddColor(state)
Parameters:
state (string) Library

MatrixMetricsLibrary "MatrixMetrics"
c_val(v, bad, mid, good, invert)
Parameters:
v (float)
bad (float)
mid (float)
good (float)
invert (bool)
c_pct(v)
Parameters:
v (float)
curve(equity)
Parameters:
equity (float)
metricsTable(mode, pos, equity, tradeClosed, tradePnl, tradeSize, tradeBars)
Parameters:
mode (simple string)
pos (simple string)
equity (float)
tradeClosed (bool)
tradePnl (float)
tradeSize (float)
tradeBars (int) Library
