Position and Leverage Size CalculatorThis script is assist you to see approximate position and leverage size while trading in prop firms.
Penunjuk dan strategi
NY Open Candle IndicatorThe NY Open Candle Indicator identifies significant opening range activity at the New York stock market open.
It highlights the 09:30–09:45 EST 15-minute candle when its range (high - low) exceeds a user-defined percentage of the daily ATR (default 25%).
- Bullish wide-range candles are colored green
- Bearish wide-range candles are colored red
A small table displays:
- Current Daily ATR
- The threshold value (user % of ATR in price terms)
An alert condition is included — create an alert for "Wide NY Open Range Detected" to get notified when a qualifying candle closes.
Perfect for traders watching opening range breakouts, volatility expansion, or momentum at the NY open.
Requirements:
- Use on 15-minute timeframe
- Set chart timezone to America/New_York
Enjoy!
RSI con EMA JP MENTOR TRADINGspot DCA BINANCE.. indicador RSI 36 y EMA 200 BASE para trading spot automatizado en binance
AI Liquidity Confirmation Framework [Signals + RR]// LOGIC FLOW:
// 1. Detect liquidity sweep (context, NOT an entry)
// 2. Enter WAIT state (no trading allowed)
// 3. Require price action confirmation (displacement)
// 4. Require AI / SnapTrader directional bias agreement
// 5. Execute trade with automatic Entry, Stop, and Take-Profit
//
// CORE FEATURES:
// - Liquidity-based context (buyside & sellside)
// - Mandatory confirmation before signals
// - Manual AI / SnapTrader bias filter (TradingView legal)
// - Automatic Risk-to-Reward projection
// - Setup expiration to prevent late entries
// - Non-repainting logic
//
// IMPORTANT NOTES:
// - Liquidity alone is NOT a trade signal
// - AI bias must be updated manually by the trader
// - Designed as a decision-support tool, not prediction software
// - Always apply proper risk management
DTS Momentum Dot Plot (MACD / STOCH / RSI)This comes from Treyding Stocks Famous Dot Plot, but for think or swim. When the green and red dots align, then it is a good opportunity for a buy or sell. It is the MACD, MACD Histogram, Fast Stochastic, the slow stochastic and the RSI, t
You can also add alerts when all lines turn green or red!
Enjoy!
SMT divergencesSMT divergences, virtually shows where Divergences in a pair are, choose your pairs and add to chart, only shows divergence when the laggard pair is sweeping downward and the leading pair doesn't sweep.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
For Source the Cutie
Final Project Midpoint Package (4H / D / W) Layer 1This script runs based off of the higher timeframe candlesticks. (4HR and Daily)
This strategy is simple and is based on your logic as well. I personally use all 5 strategies on one chart however those are being tested. As soon as you get it you will see allot on the screen , just open the setting and turn off the extra bands from the 4HR and the Daily. Fix your settings however you seem fit . Once the others are finished testing i will release those also. Will be adding updates as it progresses.
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.
8 AM (UTC-5) 1-Hour Candle High/Low Box This indicator creates a box for the 8 am (UTC-5) 1-hour candle and will delete on the chart once both the high and low is swept. When one side is swept, the box will turn orange.
Silver Macro Projection ModelSILVER MACRO PROJECTION MODEL
Multi-Factor Fair Value Estimation for Silver
OVERVIEW
The Silver Macro Projection Model estimates silver's fair value based on its historical relationships with key macroeconomic drivers. By synthesizing data from gold, M2 money supply, the US Dollar Index, and major equity indices, this indicator projects where silver should theoretically be trading, helping traders identify potential overvaluation and undervaluation conditions.
HOW IT WORKS
This indicator employs three complementary projection methodologies:
Correlation-Weighted Z-Score Composite (50% weight) - Calculates rolling correlations between silver and each input factor. Factors with stronger correlations receive more influence. Each factor is normalized to a z-score, combined into a composite, then converted back to silver's price scale.
Gold/Silver Ratio Mean Reversion (35% weight) - The gold/silver ratio historically exhibits mean-reverting behavior. This component projects silver's implied price based on current gold prices and the historical average ratio.
M2 Money Supply Relationship (15% weight) - Silver tracks monetary expansion over long time horizons. This anchors the projection to the fundamental relationship between silver and the monetary base.
INPUT FACTORS
Gold - Strong Positive - Precious metals move together; silver amplifies gold
M2 Supply - Positive - Inflation hedge; expands with monetary base
DXY - Negative - Dollar strength pressures commodity prices
S&P 500 - Variable - Risk sentiment indicator
Dow Jones - Variable - Industrial/economic health proxy
Nasdaq 100 - Variable - Growth/risk appetite indicator
Russell 2000 - Variable - Small-cap risk sentiment
VISUAL ELEMENTS
Silver Line (Gray) - Actual silver price
Yellow Line - Model's projected fair value
Green Fill - Silver trading BELOW projection (potentially undervalued)
Red Fill - Silver trading ABOVE projection (potentially overvalued)
INFORMATION TABLE
The indicator displays a real-time panel showing:
Current correlation coefficients for each factor
Dynamic weight allocation based on correlation strength
Z-scores for each input factor
Actual vs. projected silver price
Percentage divergence from fair value
Signal classification (Strong Buy to Strong Sell)
SETTINGS
Lookback Settings
Correlation Period (default: 60) - Bars used for rolling correlations
Regression Period (default: 120) - Bars for z-score normalization
Smoothing Period (default: 10) - EMA smoothing on projection
Weight Settings
Use Auto Correlation Weights - Weights adjust dynamically based on correlation strength
Manual Weights - Override with custom factor weights
ALERTS
Silver Extremely Undervalued (Z < -2)
Silver Extremely Overvalued (Z > +2)
Price crossed above projection
Price crossed below projection
BEST PRACTICES
Use on daily timeframe for most reliable signals
Combine with the companion Divergence Oscillator for timing
Extreme divergences (>2 sigma) historically precede mean reversion
Consider macro environment as correlations shift during different regimes
Longer regression periods (150-250) for investing; shorter (60-90) for trading
Disclaimer: This indicator is for educational purposes only. Past correlations do not guarantee future relationships. Always use proper risk management.
MA-MTF-12 Overlay📊 MA-MTF-12 Overlay — Indicator Description
■ Overview
MA-MTF-12 Overlay is a multi-timeframe moving average indicator that allows you to display up to 12 moving averages (SMA / EMA) simultaneously, calculated either from the current timeframe (Local) or from higher timeframes (MTF).
It is designed to help traders visualize short-term price action and higher-timeframe market structure on a single chart, enabling clearer trend context and better decision-making.
■ Key Features
✅ Up to 12 Moving Averages
Display MA1–MA12 independently
Choose SMA or EMA for each MA
Fully customizable length, color, and line width
✅ Per-MA Local / MTF Selection
Each moving average can be set individually to:
Local – calculated on the current chart timeframe
MTF – retrieved from a higher timeframe (e.g. 1H, 4H, Daily, Weekly, Monthly)
This allows you to clearly separate entry signals from higher-timeframe trend context.
✅ Confirmed Bar Mode (Repaint Control)
When using MTF, each MA supports Confirmed Bar Mode:
ON – updates only after the higher-timeframe bar is closed (minimal repaint, backtest-friendly)
OFF – follows the current higher-timeframe bar in real time (discretionary trading)
✅ Gap Handling Option
Gaps OFF – higher-timeframe values are filled smoothly (step-style, easier to read)
Gaps ON – values appear only when a higher-timeframe bar updates (theoretical accuracy)
✅ Lightweight & Efficient Design
Each MA includes separate:
Calculation ON / OFF
Display ON / OFF
Unused MAs can be completely disabled, preventing unnecessary calculations and keeping the indicator fast even with multiple MTF sources.
■ Example Use Case
MA1–MA3: Local timeframe MAs for short-term momentum
MA4–MA6: Higher-timeframe MAs (4H / Daily / Weekly) for trend structure
MA7–MA12: Optional layers, disabled by default
This setup makes it easy to understand where price is trading within the broader market context.
■ Who This Indicator Is For
Traders who rely on multi-timeframe trend analysis
Scalpers, day traders, and swing traders who want one-chart clarity
Users concerned about repainting and indicator performance
Anyone who uses moving averages as structural reference points, not just signals
■ Technical Notes
Pine Script v5
Overlay indicator (drawn on price chart)
Multi-timeframe support via request.security()
No alerts or shapes — pure visual analysis
📊 MA-MTF-12 Overlay – インジケーター解説
■ 概要
MA-MTF-12 Overlay** は、
最大12本の移動平均(SMA / EMA)を、現在足(Local)または上位足(MTF)から自由に組み合わせて表示できる**
マルチタイムフレーム対応の高機能MAインジケーターです。
短期足の値動きから、1時間・4時間・日足・週足・月足といった
上位足のトレンド環境を、1つのチャート上で同時に把握**することを目的に設計されています。
---
■ 主な特徴
✅ 最大12本のMAを同時表示
* MA1〜MA12を個別に設定可能
* SMA / EMA をMAごとに選択
* 期間・色・太さもすべて自由にカスタマイズ
---
✅ Local / MTF をMAごとに切替可能
各MAは以下を個別に選択できます。
Local:現在のチャート時間足で計算
MTF:指定した上位足(例:1H / 4H / D / W / M)から取得
👉
短期MAはLocal、
環境認識用MAはMTF、
という役割分担を1つのインジケーターで実現できます。
---
✅ 確定足モード(リペイント制御)
MTF使用時は、確定足モードをMAごとに設定可能。
ON:上位足が確定してから更新(リペイント最小・検証向き)
OFF:上位足の進行中の値もリアルタイムで反映(裁量トレード向き)
用途に応じて柔軟に使い分けられます。
---
✅ ギャップ表示 ON / OFF
OFF:上位足MAを階段状に補完表示(視認性重視)
ON:上位足更新点のみ表示(理論重視)
---
✅ 計算ON / 表示ON を分離した軽量設計
各MAには
計算ON / OFF
表示ON / OFF**
を個別に用意。
使わないMAは計算そのものを停止できるため、
MTFを多用しても**動作が重くなりにくい設計です。
---
■ 想定される使い方
* MA1〜MA3:Local(短期〜中期の勢い把握)
* MA4〜MA6:MTF(4H・日足・週足のトレンド環境)
* MA7〜MA12:必要に応じて追加(初期はOFF)
👉
「今どの時間軸のトレンドの中にいるのか」を
MAだけで直感的に把握できます。
---
■ こんな方におすすめ
* 上位足MAを使った環境認識を重視するトレーダー
* スキャル・デイトレ・スイングを1チャートで完結させたい方
* MTFインジケーターのリペイントや重さが気になる方
* MAを「本数・役割・時間軸」で整理して使いたい方
---
■ 技術仕様
* Pine Script v5
* overlay=true(価格チャート上に表示)
* MTF対応(request.security 使用)
* アラート・シェイプなし(純粋な分析用)
---
RSI Trendline Breakout BB Exit -by RiazMalikUse this strategy based on RSI and bolinger bands
When RSI trend line breaks take position when RSI touches bolinger bands exit
Momentum Color Classification System### Code Analysis: Momentum Color Classification System (Pine Script v5)
#### Core Function
This is a **non-overlay TradingView Pine Script v5 indicator** designed to quantify and categorize price momentum dynamics with extreme precision. It calculates core momentum from price Rate of Change (ROC) and second-derivative momentum change, then classifies market momentum into 9 distinct states (bullish variations, bearish variations, and neutral oscillation). The indicator visualizes momentum via color-coded histogram bars, and provides real-time status labels, a detailed info dashboard, and actionable trading suggestions — all to help traders accurately identify momentum strength, acceleration/deceleration trends, and guide long/short trading decisions.
#### Key Features (Concise & Clear)
1. **9-tier Precise Momentum Classification**
Divides momentum into **4 bullish states** (accelerating/decelerating/steady/weak up), **4 bearish states** (accelerating/decelerating/steady/weak down) and 1 neutral oscillation state, fully covering all momentum trend phases in the market.
2. **2-dimensional Momentum Calculation**
Combines **1st-order momentum** (price ROC-based core momentum) and **2nd-order momentum change** (momentum acceleration/deceleration), plus absolute momentum strength, to comprehensively judge momentum direction, speed and intensity.
3. **Color-Coded Visualization with Hierarchy**
Uses a gradient color system (vibrant-to-pale green for bullish, vivid-to-light red for bearish, gray for neutral) with transparency differentiation to reflect momentum strength; histogram style ensures intuitive observation, paired with a dotted zero reference line for clear bias judgment.
4. **Practical Trading Auxiliary Tools**
Supports toggleable status labels for extreme momentum (accelerating up/down); embeds a top-right dashboard displaying real-time momentum values, change rate, state, strength level and direct trading suggestions, enabling one-glance market judgment.
5. **High Customizability**
Allows adjustment of core parameters (momentum calculation period, smoothing factor) and toggling of label display, with reasonable parameter ranges to adapt to different trading assets and timeframes.
6. **Trade-Oriented Decision Guidance**
Maps each momentum state to corresponding strength levels and actionable operation advice (long/add position, short/add position, hold, reduce position, wait), directly linking technical analysis to actual trading behavior.
AnchoredVolume ProDescription
AnchoredVolume builds a real-time volume profile that distributes volume across price levels, identifying the Point of Control (POC), Value Area High (VAH), and Value Area Low (VAL). These levels represent where 70% of volume occurred and act as powerful support/resistance zones.
GLI Regime Index (v1.0)GLI Regime Index
Global Liquidity Intelligence for Risk Markets
The GLI Regime Index is a macro-liquidity regime engine that classifies the financial system based on where cash is actually flowing inside the Fed–Treasury plumbing.
Markets do not move on narratives.
They move on liquidity.
GLI measures that liquidity in real time by combining four institutional-grade signals:
• Fed Reverse Repo (RRP) – where excess cash is being parked
• 3-Month Treasury Bills – where short-term money prefers to earn yield
• IORB – the Federal Reserve’s policy floor
• SOFR – the true cost of funding in the system
By comparing these flows, GLI identifies which institution is currently in control of money:
Regime What It Means
FED DOMINANT Abundant reserves, liquidity flowing into risk assets
T-BILL DOMINANT Treasury absorbing liquidity, risk tightening
CASH GLUT Excess money trapped at the Fed (RRP high)
FUNDING STRESS Funding markets under pressure (SOFR > IORB)
NEUTRAL Transition state between regimes
These regimes are not opinions — they are the mechanical state of the dollar system.
Why this matters
Assets like NVDA, BTC, high-beta tech, and growth stocks don’t trade on earnings — they trade on marginal liquidity.
GLI tells you:
When rallies are supported by real money
When breakouts are likely to fail
When dips are being bought vs distributed
When risk is being quietly withdrawn
If you’ve ever wondered why price seems to hit invisible walls,
GLI shows you where those walls come from.
How to use it
Apply GLI to any chart.
When the background turns:
Green (Fed Dominant) → Risk assets are structurally supported
Orange (T-Bill Dominant) → Liquidity is draining from risk
Blue (Cash Glut) → Money is stuck at the Fed, rallies struggle
Red (Funding Stress) → Volatility and liquidation risk rise
The built-in Liquidity HUD shows:
RRP usage
Fed vs Treasury dominance
SOFR stress
Rate spreads in real time
No interpretation required.
What GLI is not
GLI is not a technical indicator.
It does not look at price, volume, or momentum.
It looks at the money behind the price.
That’s why it works.
ATR Suite ProDescription
A comprehensive ATR (Average True Range) toolkit providing multiple volatility metrics including standard ATR, normalized ATR, ATR percentage, and volatility state classification. Essential for position sizing, stop placement, and volatility regime detection.
TradeCraftly - Previous OHLC Levels📌 TradeCraftly – Previous OHLC Levels
TradeCraftly OHLC plots the most important higher-timeframe price levels directly on your chart, helping you identify key support, resistance, and reference zones with clarity.
🔹 What this indicator shows
Previous Day OHLC (High, Low, Open, Close)
Previous Week OHLC
Previous Month OHLC
Today’s Open (no historical clutter)
All levels are drawn as clean horizontal rays and extend only into the current session, keeping the chart focused and readable.
🔹 Key Features
Individual enable / disable controls for Day, Week, and Month levels
No historical clutter – only the most relevant levels are shown
Labels aligned to today’s first candle for quick level identification
Custom line width, color, and style (solid / dashed / dotted)
Works seamlessly on all intraday and higher timeframes
🔹 Why use Previous OHLC levels?
Previous period OHLC levels are widely used by:
Intraday traders
Swing traders
Index & futures traders
They often act as:
Strong support & resistance
Liquidity zones
Breakout / rejection levels
🔹 Best Use Cases
Market open bias using Today’s Open
Intraday trades around PDH / PDL
Weekly range reactions near PWH / PWL
Higher-timeframe context using Monthly levels
⚠️ Disclaimer
This indicator is for educational purposes only and does not provide trading signals or financial advice. Always manage risk and confirm with your own analysis.
Vertical line at 6PMVertical line deliniated every 6pm for the asian session trading and backtesting.
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.
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.
VWAP Institutional Trading Engine INDICATORVWAP Institutional Trading Engine
Adaptive Market Regime & Trading Model Indicator
🔍 Overview
The VWAP Institutional Trading Engine is an advanced, rule-based market analysis indicator designed to replicate institutional decision-making logic using VWAP, volatility, and session-based market behavior.
This indicator does not predict price.
Instead, it answers a more important question:
“What type of trading is appropriate right now – if any?”
The engine continuously evaluates:
Market regime (trend, range, dead market)
Volatility conditions
VWAP acceptance and deviation
Trading session (Asia / London / New York)
Based on this, it dynamically activates one of three trading models:
TREND
MEAN REVERSION
OFF (no trading)
This makes it ideal for:
Discretionary traders
Systematic traders
Risk-focused trading
Educational / portfolio-style trading approaches
🧠 Core Philosophy
Professional trading is not about finding more signals.
It is about knowing when not to trade.
This indicator is built around three institutional principles:
VWAP defines fair value
Volatility defines opportunity or danger
Different sessions require different behavior
⚙️ Indicator Components
1️⃣ VWAP & Statistical Deviation Bands
VWAP represents institutional fair price
±1σ bands indicate acceptance zones
±2σ bands represent statistical extremes
Used for:
Mean reversion zones
Trend acceptance confirmation
Go Score calculation
2️⃣ Volatility Engine
Volatility is measured using ATR relative to price
Compared against its own moving average
Classifications:
Low volatility → dead / untradable market
Normal volatility → structured behavior
High volatility → trend or liquidation events
3️⃣ Market Regime Detection
The engine classifies each moment into one regime:
Regime Meaning
TREND Price accepts above or below VWAP with volatility
RANGE Price rotates near VWAP
DEAD Low volatility, no opportunity
MIXED Unclear structure
4️⃣ Active Trading Model (Most Important)
Displayed in the dashboard as Model:
Model Interpretation
TREND Trade with momentum and continuation
MEAN_REVERT Trade extremes back to VWAP
OFF Do not trade
The Model tells you HOW you are allowed to trade right now.
5️⃣ Session Awareness (UTC)
The indicator adapts behavior based on session logic:
Session Preferred Behavior
Asia Mean Reversion
London Trend
New York Selective / adaptive
Trades are only allowed when model + session are aligned.
6️⃣ Go Score – Trade Quality Filter
Each potential setup receives a Go Score (0–100), based on:
Distance from VWAP
Market regime quality
Volatility penalties
Go Score Interpretation
≥ 80 High-quality (A+)
65–79 Acceptable
< 65 No trade
7️⃣ Risk Guidance (Informational)
The indicator outputs a Risk % suggestion, based on:
Go Score
Simulated drawdown logic
⚠️ This is guidance only, not position sizing.
📈 Visual Signals
The indicator plots contextual signals, not blind entries:
Mean Reversion Signals
▲ Long below −2σ
▼ Short above +2σ
Trend Signals
↑ Long after acceptance above +1σ
↓ Short after acceptance below −1σ
Signals appear only when trading is allowed by:
Model
Session
Go Score
🧩 Dashboard Explanation
The top-right dashboard displays real-time engine state:
Field Description
Session Current UTC session
Regime Detected market condition
Go Score Trade quality score
Risk % Suggested relative risk
Drawdown % Virtual defensive metric
Model Active trading model
If Model = OFF → do nothing.
🧭 Practical Trading Manual (Step-by-Step)
Step 1 – Check the Model
TREND → look for continuation
MEAN_REVERT → look for extremes
OFF → do not trade
Step 2 – Confirm Session Alignment
Asia + Mean Reversion ✔
London + Trend ✔
Misalignment = caution
Step 3 – Check Go Score
Below 65 → skip
65+ → proceed
Step 4 – Use Chart Structure
VWAP = anchor
σ bands = context
Signal = permission, not obligation
Step 5 – Manage Risk Manually
Use your own SL/TP rules
Follow the Risk % as guidance, not law
❌ What This Indicator Is NOT
Not a signal spam tool
Not a prediction system
Not a “holy grail”
It is a decision framework.
✅ Best Use Cases
Futures
Indices
Forex
Crypto
Intraday & swing trading
Recommended timeframes:
5m – 1H (intraday)
4H (contextual swing)
🏁 Final Notes
This indicator is intentionally transparent and rule-based.
It is designed to help traders:
Think in regimes
Trade with structure
Avoid overtrading
Protect capital
If you trade with the Model, not against it,
you will already be ahead of most market participants.






















