Liquidation Map [Alpha Extract]A sophisticated liquidity distribution visualization system that identifies potential liquidation zones through pivot-based detection and renders them as an interactive histogram with cumulative distance-to-liquidation curves. Utilizing multi-exchange volume aggregation and ATR-scaled pocket detection, this indicator delivers institutional-grade liquidity mapping with real-time histogram display showing relative concentration of long and short liquidation levels across configurable price ranges. The system's box-based rendering architecture combined with cumulative distribution overlays provides comprehensive visual assessment of asymmetric liquidity positioning for strategic trade planning.
🔶 Advanced Multi-Exchange Aggregation Framework
Implements intelligent ticker detection and multi-source volume aggregation across major exchanges including Binance, Bybit, KuCoin, OKX, and MEXC for accurate liquidity weight calculations. The system automatically identifies base currency (BTC, ETH, SOL) from chart ticker, retrieves volume data from matching perpetual contracts across multiple venues, and aggregates into composite volume metric for enhanced pocket weighting accuracy.
🔶 Pivot-Based Liquidation Pocket Detection
Features sophisticated swing point identification using configurable pivot width with ATR-scaled vertical zone construction for volatility-adaptive pocket sizing. The system detects pivot highs for short liquidation zones (placed above swing) and pivot lows for long liquidation zones (placed below swing), applying 200-period ATR with percentage multipliers to determine pocket heights that adjust to market volatility conditions.
🔶 Interactive Histogram Visualization Engine
Provides real-time box-based histogram rendering in indicator pane with configurable bin counts (up to 400 columns) and adjustable height, displaying liquidity concentration across fixed percentage range above and below current price. The system calculates bin sizes from view range, accumulates pocket weights into price bins, and renders vertical bars with gradient color intensity reflecting relative liquidity concentration at each price level.
🔶 Cumulative Distance Overlay System
Implements innovative cumulative distribution curves showing aggregate liquidity distance from current price for both long (left) and short (right) positions. The system calculates running totals of pocket weights from current price outward in both directions, normalizes against maximum span, and overlays line segments showing how much total liquidity exists at various distances, enabling instant assessment of liquidation cascade potential.
🔶 Dynamic Price Range Adaptation
Features fixed percentage-based view window that maintains consistent price range visualization across all timeframes and instruments, automatically centering histogram on current price with configurable +/- percentage bounds. The system recalculates histogram bins and pocket distributions on each bar close, ensuring visualization adapts to price movement while maintaining interpretable scale regardless of volatility regime.
🔶 Touch Detection and Weight Adjustment
Provides intelligent pocket state tracking that identifies when price trades through liquidation zones and applies configurable weight multipliers to touched pockets for historical context. The system monitors price interaction with pocket midpoints, marks pockets as "hit" when violated, and optionally increases their visual weight (default 5x) to emphasize historical liquidation levels while distinguishing from untouched future zones.
🔶 Gradient Intensity Color System
Implements sophisticated color gradient engine that modulates bar opacity from transparent to opaque based on relative liquidity concentration within each bin. The system normalizes bin values against maximum liquidity, applies color interpolation from faded to vivid hues, and distinguishes long liquidation zones (cyan) from short liquidation zones (yellow/gold) with current price column highlighted in red for instant orientation.
🔶 Performance-Optimized Rendering Architecture
Utilizes efficient box and line object management with dynamic allocation based on histogram configuration, implementing intelligent cleanup and reuse to maintain smooth performance. The system includes adaptive line budget calculations that adjust segment density for cumulative curves based on available object limits, ensuring consistent operation even with maximum histogram resolution settings.
🔶 Asymmetric Distribution Analysis
Calculates separate cumulative distributions for long and short liquidation zones split at current price, enabling identification of imbalanced liquidity positioning. The system normalizes distributions against respective maximums and overlays both curves on single histogram, allowing traders to instantly assess whether more liquidation risk exists above (shorts vulnerable) or below (longs vulnerable) current price levels.
🔶 Configurable Label and Scale System
Provides price axis labeling with adjustable frequency to reduce clutter while maintaining reference points, displaying price values at regular column intervals with configurable offset positioning. The system includes current price label showing exact value and percentile position within view range, offering both absolute price reference and relative positioning context for distribution interpretation.
🔶 Historical Pocket Persistence Framework
Maintains rolling window of liquidation pockets up to 3000 bars with automatic expiration management and optional preservation of touched zones for historical analysis. The system tracks pocket creation time, monitors age against lookback limits, and manages array cleanup to prevent memory overflow while retaining relevant historical liquidation levels for pattern recognition and support/resistance validation.
This indicator delivers sophisticated liquidity distribution analysis through histogram visualization and cumulative distance curves that reveal asymmetric positioning of potential liquidation levels. Unlike simple liquidation heatmaps that show absolute levels, the Liquidation Map's cumulative distribution overlays instantly communicate how much total liquidity exists at various distances from current price, enabling assessment of cascade potential. The system's multi-exchange volume aggregation, touch-weighted historical zones, and fixed-range visualization make it essential for traders seeking strategic positioning around institutional liquidity clusters in cryptocurrency futures markets. The histogram format enables instant identification of price levels where concentrated liquidations may trigger significant volatility or reversal events, while the asymmetric distribution curves reveal whether market structure favors upside or downside cascades.
Statistics
Breakeven LECAPs BONCAPsEN
Breakeven LECAPs & BONCAPs (ARS → USD) + Futures Curve
This indicator plots the breakeven USD/ARS exchange rate for Argentine fixed-rate Treasury instruments LECAPs (S tickers) and BONCAPs (T tickers), showing the USD/ARS level at each maturity where holding the peso instrument would match the performance of holding dollars.
What you get
• Breakeven labels at (Maturity Date, Breakeven Dollar)
• Automatic FX benchmarks:
• Dólar MEP: BCBA:AL30 / BCBA:AL30D
• Dólar Cable (CCL): BCBA:AL30 / BCBA:AL30C
• Optional Custom Dollar input (1000–10000 ARS)
• Optional MatbaRofex USD futures labels at their expiry dates
• Optional polynomial regression curves for LECAPs, BONCAPs, and Futures (degree 1–4), with independent toggles, colors, and smoothness points
Core calculations
• Direct Return = (Maturity Price / Last Price) - 1
• TNA (Annualized Rate) = Direct Return × 365 / Days to Maturity
• Breakeven Dollar = Current Dollar × (1 + Direct Return)
Tooltip (hover labels)
Ticker/type, maturity date, days to maturity, current price, maturity price (px_finish), direct return, TNA, and breakeven value.
⸻
ES
Breakeven LECAPs & BONCAPs (ARS → USD) + Curva de Futuros
Este indicador grafica el tipo de cambio USD/ARS de equilibrio (breakeven) para instrumentos de tasa fija del Tesoro argentino LECAPs (tickers S) y BONCAPs (tickers T). Te muestra a qué nivel de dólar, en cada vencimiento, una inversión en pesos igualaría el rendimiento de quedarse en dólares.
Qué muestra
• Etiquetas de breakeven en (Fecha de vencimiento, Dólar breakeven)
• Referencias automáticas de tipo de cambio:
• Dólar MEP: BCBA:AL30 / BCBA:AL30D
• Dólar Cable (CCL): BCBA:AL30 / BCBA:AL30C
• Opción de Dólar Custom (1000–10000 ARS)
• Opción de mostrar futuros de USD MatbaRofex en sus vencimientos
• Curvas de regresión polinómica opcionales para LECAPs, BONCAPs y Futuros (grado 1–4), con toggle, color y suavizado configurables por separado
Cálculos principales
• Retorno Directo = (Precio de vencimiento / Último precio) - 1
• TNA = Retorno Directo × 365 / Días al vencimiento
• Dólar Breakeven = Dólar actual × (1 + Retorno Directo)
Tooltip (pasar el mouse por las etiquetas)
Ticker/tipo, fecha de vencimiento, días restantes, precio actual, precio de vencimiento (px_finish), retorno directo, TNA y valor de breakeven.
==================== DISCLAIMER / AVISO LEGAL ====================
This indicator is for informational and educational purposes only.
Eco Valores S.A. does NOT provide investment advice or recommendations.
Consult a qualified financial advisor before making investment decisions.
Este indicador es solo para fines informativos y educativos.
Eco Valores S.A. NO brinda asesoramiento ni recomendaciones de inversion.
Consulte con un asesor financiero calificado antes de invertir.
===================================================================
CFD Position Sizing Tool (ATR-Based)A visual dashboard is included. This is an ATR Designed robust position sizing calculator for the on the fly traders.
Momentum Concepts | Baseline Strategy 📊 Momentum Concepts | Baseline Strategy
Momentum Concepts | Baseline Strategy is a rule-based momentum framework designed to identify directional bias during active market hours and participate in sustained intraday price movement.
The strategy focuses on momentum behavior relative to a neutral reference level, allowing it to adapt dynamically to changing market conditions while avoiding unnecessary trades during indecisive phases.
🔹 Core Philosophy
This strategy is built around the concept that momentum alignment is more important than raw price movement.
Trades are taken only when momentum shows clear directional intent and remains aligned with the prevailing market bias.
Rather than reacting to short-term fluctuations, the strategy emphasizes continuation and structural momentum flow.
🔹 Market Behavior Classification
At any given time, the market is internally classified into one of the following states:
Positive Momentum Phase – Favoring long exposure
Negative Momentum Phase – Favoring short exposure
Neutral Phase – No new exposure
Only one directional bias is active at a time.
Internal momentum calculations, smoothing logic, and reference mechanics are intentionally abstracted.
🔹 Trade Execution Logic (High-Level)
Positions may initiate at the start of the trading session if momentum bias is already established
During the session, trades continue only when directional alignment remains valid
Opposing signals result in directional transition rather than over-trading
No discretionary or manual intervention required
🔹 Built-In Controls
Date-based trade activation filter
Session-based execution window
Optional bar-close confirmation to avoid intrabar noise
Fully rule-driven and non-repainting behavior
🔹 Ideal Use Case
Designed primarily for intraday index and derivative markets
Performs best during directional or momentum-driven sessions
May remain flat or switch bias during low-momentum conditions
🔹 Risk & Usage Notes
Position sizing and capital allocation depend on user configuration
Backtesting on the intended instrument and timeframe is strongly recommended
Performance may vary across volatility regimes and market environments
⚠️ Disclaimer
This strategy is provided for educational and analytical purposes only.
It does not constitute financial or investment advice.
Trading involves risk, and past performance does not guarantee future results.
SOFR - EFFR SpreadThis indicator calculates and visualizes the spread between SOFR (Secured Overnight Financing Rate) and EFFR (Effective Federal Funds Rate) on TradingView. It fetches data from FRED to compute the difference. 'Red' indicates a liquidity crunch (tightness) in the market, while 'green' indicates ample liquidity.
Weekend Trading Range - [EntryLab]ENTRYLAB WEEKEND RANGE
Trading the weekends often results in lower volume, consolidation, and flat price action. This indicator is built for the community to clearly mark the weekend range, allowing traders to gauge how price formed during the weekend before markets reopen on Monday.
Custom built by EntryLab for the trading community.
LECAPS_BONCAP_LibraryLibrary "LECAPS_BONCAP_Library"
getInstrumentCount()
getTicker(index)
Parameters:
index (int)
getTickerShort(index)
Parameters:
index (int)
getMaturityPrice(index)
Parameters:
index (int)
getMaturityTimestamp(index)
Parameters:
index (int)
getMaturityYear(index)
Parameters:
index (int)
getMaturityMonth(index)
Parameters:
index (int)
getMaturityDay(index)
Parameters:
index (int)
isBoncap(index)
Parameters:
index (int)
isLecap(index)
Parameters:
index (int)
getInstrumentType(index)
Parameters:
index (int)
getDolarFuturesCount()
getDolarFuturesTicker(index)
Parameters:
index (int)
getDolarFuturesShort(index)
Parameters:
index (int)
getDolarFuturesExpiry(index)
Parameters:
index (int)
getDaysToMaturity(index)
Parameters:
index (int)
getDataSummary(index)
Parameters:
index (int)
YTD % / Visible Range % TableAUTHOR: Brandon Gum
DATE: 2026-01-03
// PURPOSE:
// Calculates price-range metrics based on the *currently visible*
// portion of the chart. Intended for table-based UI display where
// values must be stable and evaluated only on the last bar.
//
// Originally based on Jeff Sun's ADR price data table.
//
// METRICS RETURNED:
// - Visible High
// - Visible Low
// - Visible % Range = (Visible High - Visible Low) / Visible Low
// - Visible ATRs = (Visible High - Visible Low) / ATR
//
// IMPLEMENTATION NOTES:
// - Logic executes ONLY on barstate.islast to avoid state corruption.
// - Visible range is recomputed atomically using a backward loop
// bounded by chart.left_visible_bar_time.
// - Avoids var-based accumulation and bar-by-bar resets, which are
// unreliable when visible window changes.
// - ATR is evaluated at the current bar (not averaged over range).
//
// ASSUMPTIONS / LIMITATIONS:
// - Uses chart-visible time boundaries supplied by TradingView.
// - Loop upper bound must be sufficiently large to cover max
// expected visible bars.
// - Intended for display purposes, not signal generation.
//
// SIDE EFFECTS:
// - None. No plots, no drawings, no state persistence.
FX Rate Bias US vs EU 2YFX Rate Bias – US vs EU (2Y)
This indicator implements a rate-differential based macro bias model using the 2-year government bond yield spread between the United States and Germany.
The methodology focuses on the short end of the yield curve, which primarily reflects central bank expectations rather than long-term inflation or risk premiums.
By applying light smoothing and a zero-line regime framework, the script classifies market conditions into USD rate advantage or EUR rate advantage states.
Calculation logic:
Retrieves daily 2Y sovereign yields for the US and Germany
Computes the yield differential (US − DE)
Applies optional smoothing to reduce noise
Uses the zero line as a regime boundary to define relative monetary bias
Practical use:
This tool is designed to provide directional macro context for FX analysis, particularly for EURUSD.
It helps traders align technical setups with prevailing interest rate expectations, and is not intended as a standalone signal or timing indicator.
Asia & London Session High/Low Description:
This indicator plots the highest and lowest points of the Asian and London trading sessions based on Eastern Time (ET).
Features:
Draws horizontal rays for session highs and lows
Automatically resets for each session
Perfect for I CT-style liquidity analysis , range breaks , and session-based trading setups
Clean chart : no labels or clutter, just the key session levels
Use it to identify liquidity zones , plan entries , and anticipate potential session raids in your trading strategy.
Ranking de activosThis script is a real-time performance monitor designed for TradingView, which automatically organizes a list of assets according to their percentage performance during the current trading day.
Key Features:
Dynamic Ranking: The script calculates the percentage change of up to 17 assets simultaneously. It constantly reorders them (with each price movement), placing the fastest-rising assets at the top and the slowest-rising assets at the bottom.
Flexible Asset Management: * Allows you to choose any symbol from the TradingView database (Crypto, Indices, Gold, Forex).
Includes toggles (checkboxes) to enable or disable individual assets, allowing the table to automatically resize.
Minimalist Interface: Automatically removes the exchange name (e.g., from "BINANCE:BTCUSDT" it leaves only "BTC") to avoid visual clutter.
Color Coding: Percentages are automatically highlighted in green if the performance is positive and in red if it is negative.
Apex ICT: Proximity & Delivery FlowThis indicator is a specialized ICT execution tool that automates the identification of Order Blocks, Fair Value Gaps, and Changes in State of Delivery (CISD). Unlike standard indicators that clutter the screen, this script uses a Proximity Logic Engine to ensure you only see tradeable levels. It automatically purges old data (50-candle CISD limit) and deletes mitigated zones the moment they are breached, leaving you with a clean, institutional-grade chart.
ICT CISD+FVG+OBThis script is a high-performance ICT suite designed for traders who want a professional, "noise-free" chart. It identifies core institutional patterns—Order Blocks, Fair Value Gaps, and Changes in State of Delivery (CISD)—across multiple timeframes.
The script features a proprietary Proximity Cleanup Engine that automatically deletes old or broken levels, keeping your workspace focused only on price action that is currently tradeable. It strictly follows directional delivery rules for CISD and includes a 50-candle "freshness" limit to ensure you never have to manually clear old data from your past bars.
Core Features
Intelligent CISD: Only triggers Bullish CISD on green candles and Bearish CISD on red candles.
Proximity Filter: Automatically wipes away any levels that are "miles away" from the current price.
Clean Workspace: Removes broken session highs/lows and mitigated zones instantly.
Full Customization: Toggle visibility and colors for every component via the settings menu.
[ElThibZ] - Futures Lot Size CalculatorI’m sharing a simple script to calculate position size for futures.
You only need to enter:
the risk in USD you’re willing to take
the stop-loss distance in ticks
The script will automatically calculate the correct position size (number of contracts) and display it in the table.
This tool is designed to avoid sizing mistakes, especially on futures where contract multipliers and tick values can easily lead to incorrect risk calculations.
I hope it will be as useful to you as it has been for me.
777 mean reversion engineA guy asked his librarian if they had any books on "paranoia." She leaned in and whispered, "They're right behind you." He hasn't been back to the library since.
Adaptive Trend Envelope [BackQuant]Adaptive Trend Envelope
Overview
Adaptive Trend Envelope is a volatility-aware trend-following overlay designed to stay responsive in fast markets while remaining stable during slower conditions. It builds a dynamic trend spine from two exponential moving averages and surrounds it with an adaptive envelope whose width expands and contracts based on realized return volatility. The result is a clean, self-adjusting trend structure that reacts to market conditions instead of relying on fixed parameters.
This indicator is built to answer three core questions directly on the chart:
Is the market trending or neutral?
If trending, in which direction is the dominant pressure?
Where is the dynamic trend boundary that price should respect?
Core trend spine
At the heart of the indicator is a blended trend spine:
A fast EMA captures short-term responsiveness.
A slow EMA captures structural direction.
A volatility-based blend weight dynamically shifts influence between the two.
When short-term volatility is low relative to long-term volatility, the fast EMA has more influence, keeping the trend responsive. When volatility rises, the blend shifts toward the slow EMA, reducing noise and preventing overreaction. This blended output is then smoothed again to form the final trend spine, which acts as the structural backbone of the system.
Volatility-adaptive envelope
The envelope surrounding the trend spine is not based on ATR or fixed percentages. Instead, it is derived from:
Log returns of price.
An exponentially weighted variance estimate.
A configurable multiplier that scales envelope width.
This creates bands that automatically widen during volatile expansions and tighten during compression. The envelope therefore reflects the true statistical behavior of price rather than an arbitrary distance.
Inner hysteresis band
Inside the main envelope, an inner band is constructed using a hysteresis fraction. This inner zone is used to stabilize regime transitions:
It prevents rapid flipping between bullish and bearish states.
It allows trends to persist unless price meaningfully invalidates them.
It reduces whipsaws in sideways conditions.
Trend regime logic
The indicator operates with three regime states:
Bullish
Bearish
Neutral
Regime changes are confirmed using a configurable number of bars outside the adaptive envelope:
A bullish regime is confirmed when price closes above the upper envelope for the required number of bars.
A bearish regime is confirmed when price closes below the lower envelope for the required number of bars.
A trend exits back to neutral when price reverts through the trend spine.
This structure ensures that trends are confirmed by sustained pressure rather than single-bar spikes.
Active trend line
Once a regime is active, the indicator plots a single dominant trend line:
In a bullish regime, the lower envelope becomes the active trend support.
In a bearish regime, the upper envelope becomes the active trend resistance.
In neutral conditions, price itself is used as a placeholder.
This creates a simple, actionable visual reference for trend-following decisions.
Directional energy visualization
The indicator uses layered fills to visualize directional pressure:
Bullish energy fills appear when price holds above the active trend line.
Bearish energy fills appear when price holds below the active trend line.
Opacity gradients communicate strength and persistence rather than binary states.
A subtle “rim” effect is added using ATR-based offsets to give depth and reinforce the active side of the trend without cluttering the chart.
Signals and trend starts
Discrete signals are generated only when a new trend regime begins:
Buy signals appear at the first confirmed transition into a bullish regime.
Sell signals appear at the first confirmed transition into a bearish regime.
Signals are intentionally sparse. They are designed to mark regime shifts, not every pullback or continuation, making them suitable for higher-quality trend entries rather than frequent trading.
Candle coloring
Optional candle coloring reinforces regime context:
Bullish regimes tint candles toward the bullish color.
Bearish regimes tint candles toward the bearish color.
Neutral states remain visually muted.
This allows the chart to communicate trend state even when the envelope itself is partially hidden or de-emphasized.
Alerts
Built-in alerts are provided for key trend events:
Bull trend start.
Bear trend start.
Transition from trend to neutral.
Price crossing the trend spine.
These alerts support hands-off trend monitoring across multiple instruments and timeframes.
How to use it for trend following
Trend identification
Only trade in the direction of the active regime.
Ignore counter-trend signals during confirmed trends.
Entry alignment
Use the first regime signal as a structural entry.
Use pullbacks toward the active trend line as continuation opportunities.
Trend management
As long as price respects the active envelope boundary, the trend remains valid.
A move back through the spine signals loss of trend structure.
Market filtering
Periods where the indicator remains neutral highlight non-trending environments.
This helps avoid forcing trades during chop or compression.
Adaptive Trend Envelope is designed to behave like a living trend structure. Instead of forcing price into static rules, it adapts to volatility, confirms direction through sustained pressure, and presents trend information in a clean, readable form that supports disciplined trend-following workflows.
Q# ML Logistic Regression Indicator [Lite]
Q TechLabs MLLR Lite — Machine Learning Logistic Regression Trading Indicator
© Q# Tech Labs 2025 Developed by Team Q TechLabs
Overview
Q# MLLR Lite is an open-source, lightweight TradingView indicator implementing a logistic regression model to generate buy/sell signals based on engineered price features. This “lite” version is designed for broad community access and serves as a foundation for the upcoming Pro version with advanced features and integration.
Features
Logistic Regression-based buy/sell signal generation
Customizable price source input (Open, High, Low, Close, HL2, HLC3, OHLC4)
Adjustable signal threshold and smoothing parameters
Signal confidence plotted in a separate pane
Alert conditions for buy and sell signals
Fully documented, clean Pine Script (v6) code for easy customization
Installation
Open TradingView and navigate to the Pine Script editor
Create a new script and paste the full content of the Q# MLLR Lite Pine Script
Save and add to chart
Configure inputs as needed for your trading style
Licensing
Q# MLLR Lite is provided under the MIT License, promoting open use, modification, and community collaboration with attributi
Q# MLLR Lite — Machine Learning Logistic Regression Trading Indicator
© Q# Tech Labs 2025 — Developed by Team Q#
Overview
Q# MLLR Lite is an open-source, lightweight TradingView indicator implementing a logistic regression model to generate buy/sell signals based on engineered price features. This “lite” version is designed for broad community access and serves as a foundation for the upcoming Pro version with advanced features and integration.
Features
Logistic Regression-based buy/sell signal generation
Customizable price source input (Open, High, Low, Close, HL2, HLC3, OHLC4)
Adjustable signal threshold and smoothing parameters
Signal confidence plotted in a separate pane
Alert conditions for buy and sell signals
Fully documented, clean Pine Script (v6) code for easy customization
Installation
Open TradingView and navigate to the Pine Script editor
Create a new script and paste the full content of the Q# MLLR Lite Pine Script
Save and add to chart
Configure inputs as needed for your trading style
Licensing
Q# MLLR Lite is provided under the MIT License, promoting open use, modification, and community collaboration with attribution.
Copyright (c) 2025 Q# Tech Labs
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
PM/PW/PD/OVN/CD/CM/CW/ORB Highs & Lows + EMAs + ATH/ATL/52WTogglable:
Previous Month High / Low
Previous Week High / Low
Previous Day High / Low
Current Month High / Low
Current Week High / Low
Current Day High / Low
ORB High / Low
Overnight High / Low
Asia Session High / Low
London Session High / Low
All Time High / Low
52week High / Low
3 EMAs (default 21/34/55)
Dashboards + lines on chart
DeeptestDeeptest: Quantitative Backtesting Library for Pine Script
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ OVERVIEW
Deeptest is a Pine Script library that provides quantitative analysis tools for strategy backtesting. It calculates over 100 statistical metrics including risk-adjusted return ratios (Sharpe, Sortino, Calmar), drawdown analysis, Value at Risk (VaR), Conditional VaR, and performs Monte Carlo simulation and Walk-Forward Analysis.
█ WHY THIS LIBRARY MATTERS
Pine Script is a simple yet effective coding language for algorithmic and quantitative trading. Its accessibility enables traders to quickly prototype and test ideas directly within TradingView. However, the built-in strategy tester provides only basic metrics (net profit, win rate, drawdown), which is often insufficient for serious strategy evaluation.
Due to this limitation, many traders migrate to alternative backtesting platforms that offer comprehensive analytics. These platforms require other language programming knowledge, environment setup, and significant time investment—often just to test a simple trading idea.
Deeptest bridges this gap by bringing institutional-level quantitative analytics directly to Pine Script. Traders can now perform sophisticated analysis without leaving TradingView or learning complex external platforms. All calculations are derived from strategy.closedtrades.* , ensuring compatibility with any existing Pine Script strategy.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ ORIGINALITY AND USEFULNESS
This library is original work that adds value to the TradingView community in the following ways:
1. Comprehensive Metric Suite: Implements 112+ statistical calculations in a single library, including advanced metrics not available in TradingView's built-in tester (p-value, Z-score, Skewness, Kurtosis, Risk of Ruin).
2. Monte Carlo Simulation: Implements trade-sequence randomization to stress-test strategy robustness by simulating 1000+ alternative equity curves.
3. Walk-Forward Analysis: Divides historical data into rolling in-sample and out-of-sample windows to detect overfitting by comparing training vs. testing performance.
4. Rolling Window Statistics: Calculates time-varying Sharpe, Sortino, and Expectancy to analyze metric consistency throughout the backtest period.
5. Interactive Table Display: Renders professional-grade tables with color-coded thresholds, tooltips explaining each metric, and period analysis cards for drawdowns/trades.
6. Benchmark Comparison: Automatically fetches S&P 500 data to calculate Alpha, Beta, and R-squared, enabling objective assessment of strategy skill vs. passive investing.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ KEY FEATURES
Performance Metrics
Net Profit, CAGR, Monthly Return, Expectancy
Profit Factor, Payoff Ratio, Sample Size
Compounding Effect Analysis
Risk Metrics
Sharpe Ratio, Sortino Ratio, Calmar Ratio (MAR)
Martin Ratio, Ulcer Index
Max Drawdown, Average Drawdown, Drawdown Duration
Risk of Ruin, R-squared (equity curve linearity)
Statistical Distribution
Value at Risk (VaR 95%), Conditional VaR
Skewness (return asymmetry)
Kurtosis (tail fatness)
Z-Score, p-value (statistical significance testing)
Trade Analysis
Win Rate, Breakeven Rate, Loss Rate
Average Trade Duration, Time in Market
Consecutive Win/Loss Streaks with Expected values
Top/Worst Trades with R-multiple tracking
Advanced Analytics
Monte Carlo Simulation (1000+ iterations)
Walk-Forward Analysis (rolling windows)
Rolling Statistics (time-varying metrics)
Out-of-Sample Testing
Benchmark Comparison
Alpha (excess return vs. benchmark)
Beta (systematic risk correlation)
Buy & Hold comparison
R-squared vs. benchmark
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ QUICK START
Basic Usage
//@version=6
strategy("My Strategy", overlay=true)
// Import the library
import Fractalyst/Deeptest/1 as *
// Your strategy logic
fastMA = ta.sma(close, 10)
slowMA = ta.sma(close, 30)
if ta.crossover(fastMA, slowMA)
strategy.entry("Long", strategy.long)
if ta.crossunder(fastMA, slowMA)
strategy.close("Long")
// Run the analysis
DT.runDeeptest()
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ METRIC EXPLANATIONS
The Deeptest table displays 23 metrics across the main row, with 23 additional metrics in the complementary row. Each metric includes detailed tooltips accessible by hovering over the value.
Main Row — Performance Metrics (Columns 0-6)
Net Profit — (Final Equity - Initial Capital) / Initial Capital × 100
— >20%: Excellent, >0%: Profitable, <0%: Loss
— Total return percentage over entire backtest period
Payoff Ratio — Average Win / Average Loss
— >1.5: Excellent, >1.0: Good, <1.0: Losses exceed wins
— Average winning trade size relative to average losing trade. Breakeven win rate = 100% / (1 + Payoff)
Sample Size — Count of closed trades
— >=30: Statistically valid, <30: Insufficient data
— Number of completed trades. Includes 95% confidence interval for win rate in tooltip
Profit Factor — Gross Profit / Gross Loss
— >=1.5: Excellent, >1.0: Profitable, <1.0: Losing
— Ratio of total winnings to total losses. Uses absolute values unlike payoff ratio
CAGR — (Final / Initial)^(365.25 / Days) - 1
— >=10%: Excellent, >0%: Positive growth
— Compound Annual Growth Rate - annualized return accounting for compounding
Expectancy — Sum of all returns / Trade count
— >0.20%: Excellent, >0%: Positive edge
— Average return per trade as percentage. Positive expectancy indicates profitable edge
Monthly Return — Net Profit / (Months in test)
— >0%: Profitable month average
— Average monthly return. Geometric monthly also shown in tooltip
Main Row — Trade Statistics (Columns 7-14)
Avg Duration — Average time in position per trade
— Mean holding period from entry to exit. Influenced by timeframe and trading style
Max CW — Longest consecutive winning streak
— Maximum consecutive wins. Expected value = ln(trades) / ln(1/winRate)
Max CL — Longest consecutive losing streak
— Maximum consecutive losses. Important for psychological risk tolerance
Win Rate — Wins / Total Trades
— Higher is better
— Percentage of profitable trades. Breakeven win rate shown in tooltip
BE Rate — Breakeven Trades / Total Trades
— Lower is better
— Percentage of trades that broke even (neither profit nor loss)
Loss Rate — Losses / Total Trades
— Lower is better
— Percentage of unprofitable trades. Together with win rate and BE rate, sums to 100%
Frequency — Trades per month
— Trading activity level. Displays intelligently (e.g., "12/mo", "1.5/wk", "3/day")
Exposure — Time in market / Total time × 100
— Lower = less risk
— Percentage of time the strategy had open positions
Main Row — Risk Metrics (Columns 15-22)
Sharpe Ratio — (Return - Rf) / StdDev × sqrt(Periods)
— >=3: Excellent, >=2: Good, >=1: Fair, <1: Poor
— Measures risk-adjusted return using total volatility. Annualized using sqrt(252) for daily
Sortino Ratio — (Return - Rf) / DownsideDev × sqrt(Periods)
— >=2: Excellent, >=1: Good, <1: Needs improvement
— Similar to Sharpe but only penalizes downside volatility. Can be higher than Sharpe
Max DD — (Peak - Trough) / Peak × 100
— <5%: Excellent, 5-15%: Moderate, 15-30%: High, >30%: Severe
— Largest peak-to-trough decline in equity. Critical for risk tolerance and position sizing
RoR — Risk of Ruin probability
— <1%: Excellent, 1-5%: Acceptable, 5-10%: Elevated, >10%: Dangerous
— Probability of losing entire trading account based on win rate and payoff ratio
R² — R-squared of equity curve vs. time
— >=0.95: Excellent, 0.90-0.95: Good, 0.80-0.90: Moderate, <0.80: Erratic
— Coefficient of determination measuring linearity of equity growth
MAR — CAGR / |Max Drawdown|
— Higher is better, negative = bad
— Calmar Ratio. Reward relative to worst-case loss. Negative if max DD exceeds CAGR
CVaR — Average of returns below VaR threshold
— Lower absolute is better
— Conditional Value at Risk (Expected Shortfall). Average loss in worst 5% of outcomes
p-value — Binomial test probability
— <0.05: Significant, 0.05-0.10: Marginal, >0.10: Likely random
— Probability that observed results are due to chance. Low p-value means statistically significant edge
Complementary Row — Extended Metrics
Compounding — (Compounded Return / Total Return) × 100
— Percentage of total profit attributable to compounding (position sizing)
Avg Win — Sum of wins / Win count
— Average profitable trade return in percentage
Avg Trade — Sum of all returns / Total trades
— Same as Expectancy (Column 5). Displayed here for convenience
Avg Loss — Sum of losses / Loss count
— Average unprofitable trade return in percentage (negative value)
Martin Ratio — CAGR / Ulcer Index
— Similar to Calmar but uses Ulcer Index instead of Max DD
Rolling Expectancy — Mean of rolling window expectancies
— Average expectancy calculated across rolling windows. Shows consistency of edge
Avg W Dur — Avg duration of winning trades
— Average time from entry to exit for winning trades only
Max Eq — Highest equity value reached
— Peak equity achieved during backtest
Min Eq — Lowest equity value reached
— Trough equity point. Important for understanding worst-case absolute loss
Buy & Hold — (Close_last / Close_first - 1) × 100
— >0%: Passive profit
— Return of simply buying and holding the asset from backtest start to end
Alpha — Strategy CAGR - Benchmark CAGR
— >0: Has skill (beats benchmark)
— Excess return above passive benchmark. Positive alpha indicates genuine value-added skill
Beta — Covariance(Strategy, Benchmark) / Variance(Benchmark)
— <1: Less volatile than market, >1: More volatile
— Systematic risk correlation with benchmark
Avg L Dur — Avg duration of losing trades
— Average time from entry to exit for losing trades only
Rolling Sharpe/Sortino — Dynamic based on win rate
— >2: Good consistency
— Rolling metric across sliding windows. Shows Sharpe if win rate >50%, Sortino if <=50%
Curr DD — Current drawdown from peak
— Lower is better
— Present drawdown percentage. Zero means at new equity high
DAR — CAGR adjusted for target DD
— Higher is better
— Drawdown-Adjusted Return. DAR^5 = CAGR if max DD = 5%
Kurtosis — Fourth moment / StdDev^4 - 3
— ~0: Normal, >0: Fat tails, <0: Thin tails
— Measures "tailedness" of return distribution (excess kurtosis)
Skewness — Third moment / StdDev^3
— >0: Positive skew (big wins), <0: Negative skew (big losses)
— Return distribution asymmetry
VaR — 5th percentile of returns
— Lower absolute is better
— Value at Risk at 95% confidence. Maximum expected loss in worst 5% of outcomes
Ulcer — sqrt(mean(drawdown^2))
— Lower is better
— Ulcer Index - root mean square of drawdowns. Penalizes both depth AND duration
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ MONTE CARLO SIMULATION
Purpose
Monte Carlo simulation tests strategy robustness by randomizing the order of trades while keeping trade returns unchanged. This simulates alternative equity curves to assess outcome variability.
Method
Extract all historical trade returns
Randomly shuffle the sequence (1000+ iterations)
Calculate cumulative equity for each shuffle
Build distribution of final outcomes
Output
The stress test table shows:
Median Outcome: 50th percentile result
5th Percentile: Worst 5% of outcomes
95th Percentile: Best 95% of outcomes
Success Rate: Percentage of simulations that were profitable
Interpretation
If 95% of simulations are profitable: Strategy is robust
If median is far from actual result: High variance/unreliability
If 5th percentile shows large loss: High tail risk
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ WALK-FORWARD ANALYSIS
Purpose
Walk-Forward Analysis (WFA) is the gold standard for detecting strategy overfitting. It simulates real-world trading by dividing historical data into rolling "training" (in-sample) and "validation" (out-of-sample) periods. A strategy that performs well on unseen data is more likely to succeed in live trading.
Method
The implementation uses a non-overlapping window approach following AmiBroker's gold standard methodology:
Segment Calculation: Total trades divided into N windows (default: 12), IS = ~75%, OOS = ~25%, Step = OOS length
Window Structure: Each window has IS (training) followed by OOS (validation). Each OOS becomes the next window's IS (rolling forward)
Metrics Calculated: CAGR, Sharpe, Sortino, MaxDD, Win Rate, Expectancy, Profit Factor, Payoff
Aggregation: IS metrics averaged across all IS periods, OOS metrics averaged across all OOS periods
Output
IS CAGR: In-sample annualized return
OOS CAGR: Out-of-sample annualized return ( THE key metric )
IS/OOS Sharpe: In/out-of-sample risk-adjusted return
Success Rate: % of OOS windows that were profitable
Interpretation
Robust: IS/OOS CAGR gap <20%, OOS Success Rate >80%
Some Overfitting: CAGR gap 20-50%, Success Rate 50-80%
Severe Overfitting: CAGR gap >50%, Success Rate <50%
Key Principles:
OOS is what matters — Only OOS predicts live performance
Consistency > Magnitude — 10% IS / 9% OOS beats 30% IS / 5% OOS
Window count — More windows = more reliable validation
Non-overlapping OOS — Prevents data leakage
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ TABLE DISPLAY
Main Table — Organized into three sections:
Performance Metrics (Cols 0-6): Net Profit, Payoff, Sample Size, Profit Factor, CAGR, Expectancy, Monthly
Trade Statistics (Cols 7-14): Avg Duration, Max CW, Max CL, Win, BE, Loss, Frequency, Exposure
Risk Metrics (Cols 15-22): Sharpe, Sortino, Max DD, RoR, R², MAR, CVaR, p-value
Color Coding
🟢 Green: Excellent performance
🟠 Orange: Acceptable performance
⚪ Gray: Neutral / Fair
🔴 Red: Poor performance
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ IMPLEMENTATION NOTES
Data Source: All metrics calculated from strategy.closedtrades , ensuring compatibility with any Pine Script strategy
Calculation Timing: All calculations occur on barstate.islastconfirmedhistory to optimize performance
Limitations: Requires at least 1 closed trade for basic metrics, 30+ trades for reliable statistical analysis
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ QUICK NOTES
➙ This library has been developed and refined over two years of real-world strategy testing. Every calculation has been validated against industry-standard quantitative finance references.
➙ The entire codebase is thoroughly documented inline. If you are curious about how a metric is calculated or want to understand the implementation details, dive into the source code -- it is written to be read and learned from.
➙ This description focuses on usage and concepts rather than exhaustively listing every exported type and function. The library source code is thoroughly documented inline -- explore it to understand implementation details and internal logic.
➙ All calculations execute on barstate.islastconfirmedhistory to minimize runtime overhead. The library is designed for efficiency without sacrificing accuracy.
➙ Beyond analysis, this library serves as a learning resource. Study the source code to understand quantitative finance concepts, Pine Script advanced techniques, and proper statistical methodology.
➙ Metrics are their own not binary good/bad indicators. A high Sharpe ratio with low sample size is misleading. A deep drawdown during a market crash may be acceptable. Study each function and metric individually -- evaluate your strategy contextually, not by threshold alone.
➙ All strategies face alpha decay over time. Instead of over-optimizing a single strategy on one timeframe and market, build a diversified portfolio across multiple markets and timeframes. Deeptest helps you validate each component so you can combine robust strategies into a trading portfolio.
➙ Screenshots shown in the documentation are solely for visual representation to demonstrate how the tables and metrics will be displayed. Please do not compare your strategy's performance with the metrics shown in these screenshots -- they are illustrative examples only, not performance targets or benchmarks.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ HOW-TO
Using Deeptest is intentionally straightforward. Just import the library and call DT.runDeeptest() at the end of your strategy code in main scope. .
//@version=6
strategy("My Strategy", overlay=true)
// Import the library
import Fractalyst/Deeptest/1 as DT
// Your strategy logic
fastMA = ta.sma(close, 10)
slowMA = ta.sma(close, 30)
if ta.crossover(fastMA, slowMA)
strategy.entry("Long", strategy.long)
if ta.crossunder(fastMA, slowMA)
strategy.close("Long")
// Run the analysis
DT.runDeeptest()
And yes... it's compatible with any TradingView Strategy! 🪄
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ CREDITS
Author: @Fractalyst
Font Library: by @fikira - @kaigouthro - @Duyck
Community: Inspired by the @PineCoders community initiative, encouraging developers to contribute open-source libraries and continuously enhance the Pine Script ecosystem for all traders.
if you find Deeptest valuable in your trading journey, feel free to use it in your strategies and give a shoutout to @Fractalyst -- Your recognition directly supports ongoing development and open-source contributions to Pine Script.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ DISCLAIMER
This library is provided for educational and research purposes. Past performance does not guarantee future results. Always test thoroughly and use proper risk management. The author is not responsible for any trading losses incurred through the use of this code.
FX Rate Bias US vs EU 2YFX Rate Bias – US vs EU (2Y)
This indicator provides a macro bias framework for FX markets by tracking the 2-year government bond yield differential between the United States and Germany.
Rather than displaying the spread as a raw calculation, the script translates interest-rate expectations into a clear directional bias, helping traders understand which currency currently holds a rate advantage.
The 2Y segment of the yield curve is highly sensitive to:
Central bank expectations
Forward guidance
Shifts in short-term monetary policy outlook
How to use
Positive spread → USD rate advantage
Negative spread → EUR rate advantage
Designed to be used as a contextual macro tool, this indicator helps align technical setups with broader monetary conditions.
It is not intended as a standalone entry or signal generator.
MADZ - Moving Average Deviation Z-ScoreMADZ - Moving Average Deviation Z-Score
MADZ is a powerful valuation oscillator that measures how far the current price has deviated from a user-selected moving average, expressed in statistical terms as a Z-Score. This normalization makes it easier to identify overvalued and undervalued conditions across different assets, timeframes, and market environments.
Overview
The indicator works by:
Calculating the percentage deviation of price from a customizable moving average (SMA, EMA, WMA, VWMA, HMA, or RMA).
Applying a Z-Score transformation to this deviation over a chosen lookback period — showing how many standard deviations the current deviation is from its historical average. Smoothing the result for a clean, responsive oscillator centered around zero.
Positive values indicate price is trading above the moving average (potentially overvalued), while negative values suggest price is below (potentially undervalued). The further from zero, the greater the relative valuation extreme.
Key Features
Customizable base moving average (type and length)
Z-Score normalization for statistically meaningful readings
Final smoothing for reduced noise
Static overbought/oversold levels (default ±1.5) — line changes color when crossed (red above, green below)
Dynamic extreme bands (±3σ) — optional display of bands calculated from the oscillator’s own volatility over a user-defined period
Extreme zone highlighting — background shading activates only during truly rare valuation events
Extreme Zone Highlighting Explained
The highlighted extreme zones (background shading) are not based on the fixed static levels. Instead, they signal statistically significant outliers using dynamic bands:
Overbought extreme zone (red background): Triggered when MADZ rises above the upper dynamic band (+3 standard deviations of the MADZ line itself over the dynamic length period).
Oversold extreme zone (green background): Triggered when MADZ falls below the lower dynamic band (-3 standard deviations).
These ±3σ bands adapt to the recent behavior of the oscillator. Because they represent three standard deviations from the mean of MADZ, crossings are rare and often precede major reversals or trend accelerations — making them valuable for spotting potential turning points in valuation extremes.
How to Use
Use zero-line crosses for trend changes or mean-reversion setups.
Watch static level crossings (±1.5 default) for early overbought/oversold warnings.
Pay special attention to extreme zone shading — these highlight high-conviction valuation dislocations that may offer superior risk/reward opportunities.
Designed on the BTC chart, but can be used on other assets.
Settings
Moving Average Settings: Type, length, source
Z-Score & Smoothing: Lookback period and smoothing length
Threshold Levels: Static overbought/oversold thresholds
Display Options: Toggle dynamic bands and extreme background highlighting
This is an educational tool designed to aid in valuation analysis. The information provided is not financial advice. Always conduct your own research and consider multiple factors before making trading decisions. Trade at your own risk.
Institutional Intermarket Score PRO V3.3 (Presets)This indicator is built on an unusual, non-traditional intermarket concept and is designed to provide market context rather than trading signals.
Institutional Intermarket Score – Indicator Description
Overview
The Institutional Intermarket Score is a contextual market indicator designed to provide a macro and intermarket perspective on the current market environment.
It aggregates information from multiple user-selected correlated and inversely correlated assets to determine whether the broader market context favors risk-on, risk-off, or neutral conditions.
This indicator is not a buy or sell signal.
It does not attempt to predict short-term price movements, entries, or exits.
Its sole purpose is to help the trader understand the broader market context before making any trading decisions.
Core Concept
Markets do not move in isolation.
Institutional participants continuously monitor multiple related markets to assess risk, liquidity, and conviction before deploying capital.
This indicator replicates that process by:
Monitoring several correlated assets (assets that tend to move in the same direction)
Monitoring several inversely correlated assets (assets that typically move in the opposite direction)
Combining their behavior into a single, normalized intermarket score
The result is a context filter, not a trading system.
Asset Groups
The indicator supports up to:
5 correlated assets
5 inversely correlated assets
All assets are fully configurable by the user and can be enabled or disabled individually.
Only active assets are included in all calculations.
Market State Evaluation
Each asset is evaluated using a Price vs VWAP relationship:
Price above VWAP → bullish state
Price below VWAP → bearish state
This binary state is used consistently across all assets to maintain clarity and robustness.
Intermarket Score
----------------------
The Intermarket Score represents the average directional alignment of all active assets and is normalized between -1 and +1.
Positive values indicate a risk-on environment
Negative values indicate a risk-off environment
Values near zero indicate balance, rotation, or uncertainty
The score is smoothed to reduce noise and highlight regime persistence rather than short-term fluctuations.
Confirmation Metric (X / Y)
----------------------------------
In addition to the score, the indicator calculates a confirmation ratio:
Y = total number of active assets
X = number of assets aligned with the current regime
Alignment is evaluated relative to the current regime:
In bullish regimes, assets above VWAP confirm
In bearish regimes, assets below VWAP confirm
This metric reflects the quality and conviction of the intermarket consensus.
High confirmation indicates broad agreement across markets.
Low confirmation indicates divergence, uncertainty, or fragile conditions.
Heatmap
-----------
A compact heatmap visually displays the state of each individual asset:
Green indicates alignment with the regime
Red indicates opposition
Neutral indicates inactive assets
This allows immediate identification of:
Which markets are confirming
Which markets are diverging
Whether consensus is broad or fragmented
Intended Use
----------------
This indicator is designed to be used:
Before evaluating trade setups
As a filter, not a trigger
In combination with price action, structure, and risk management
Typical applications include:
Avoiding trades against the broader market context
Distinguishing strong trends from fragile moves
Identifying periods of institutional alignment or hesitation
What This Indicator Is Not
It is not a buy or sell indicator
It does not provide entry or exit signals
It does not predict price direction on its own
It does not guarantee profitable trades
Any trading decisions remain entirely the responsibility of the user.
Summary
The Institutional Intermarket Score provides a high-level market image based on assets selected by the user.
It reflects context, alignment, and conviction, not timing.
Used correctly, it helps traders avoid low-quality trades, understand when markets are aligned or fragmented, and make decisions with greater awareness of the broader environment.
It is a decision support tool, not a trading system.
This indicator, is still evolving and its structure will continue to develop as new insights are tested...






















