CS Basic Scripts - Stochastic Special (Strategy)This Stochastic Special Strategy features inputs for:
- Custom Backtesting Date Range
- Long and Short Strategy Discinctions
- Utilize SMI, RSI, Martingale, and Body-Filter Strategy
- Adjust the SMI Percent Lengths and Limit
- Automate with the Autoview Trading Bot
Strategy script may be tested by favoriting and adding to any chart.
Study script is available for automated trading at www.cryptoscores.org
"backtesting" için komut dosyalarını ara
Deviation Back Tester (Great for Credit Spreads)!Error with math fixed in this one. Please use this one.
This is great for credit spreads! Lets say you wanted to know if you had sold a 15% OTM Bull Put vertical 2 months out, how often would you win? This Turns green if you would have been correct with your credit spread had it expired on that date, or red if you would've been wrong. Great for Back testing!
This could also be used for ATM debit spreads credit spreads etc. Example, how often does SPY deviate outside a 10% range relative to two months, 5% (if your doing straddles perhaps) etc.
This Can be used with any stock.
PLEASE KEEP IN MIND THAT IT TESTS DEVIATION IN BOTH DIRECTIONS. THEREFORE IT WILL HIGHLIGHT RED ON BOTH THE UPSIDE AND DOWNSIDE. WHEN BACKTESTING BE SURE TO CHECK WHETHER IT IS RED BECAUSE OF DOWNSIDE OR UPSIDE.
Simple Candle Info This script shows the following simple information about the last candle:
- Candle size
- Body size included %
- Top Wick size
- Bottom Wick size
- Top Wick + Body size
- Bottom Wick + Body size
You can change:
- colors and position for labels
- add information for previous candle too
- change language
Laguerre RSI by KivancOzbilgic STRATEGYBacktesting.
" Laguerre RSI is based on John EHLERS' Laguerre Filter to avoid the noise of RSI .
Change alpha coefficient to increase/decrease lag and smoothness.
Buy when Laguerre RSI crosses upwards above 20.
Sell when Laguerre RSI crosses down below 80.
While indicator runs flat above 80 level, it means that an uptrend is strong.
While indicator runs flat below 20 level, it means that a downtrend is strong. "
Developer: John EHLERS
Author: KivancOzbilgic
Simple Price Momentum - How To Create A Simple Trading StrategyThis script was built using a logical approach to trading systems. All the details can be found in a step by step guide below. I hope you enjoy it. I am really glad to be part of this community. Thank you all. I hope you not only succeed on your trading career but also enjoy it.
docs.google.com
Moving Averages Cross - MTF - StrategyBacktesting Script for the following strategy
Strategy Injector Source: github.com
Dual Timeframe SMA Ribbon Crossover Backtest// Backtesting Dual SMA Ribbon Crossover Strategy
// see f.bpcdn.co
// including time limiting
Turned this study into a backtest.
Ultimate RSI [captainua]Ultimate RSI
Overview
This indicator combines multiple RSI calculations with volume analysis, divergence detection, and trend filtering to provide a comprehensive RSI-based trading system. The script calculates RSI using three different periods (6, 14, 24) and applies various smoothing methods to reduce noise while maintaining responsiveness. The combination of these features creates a multi-layered confirmation system that reduces false signals by requiring alignment across multiple indicators and timeframes.
The script includes optimized configuration presets for instant setup: Scalping, Day Trading, Swing Trading, and Position Trading. Simply select a preset to instantly configure all settings for your trading style, or use Custom mode for full manual control. All settings include automatic input validation to prevent configuration errors and ensure optimal performance.
Configuration Presets
The script includes preset configurations optimized for different trading styles, allowing you to instantly configure the indicator for your preferred trading approach. Simply select a preset from the "Configuration Preset" dropdown menu:
- Scalping: Optimized for fast-paced trading with shorter RSI periods (4, 7, 9) and minimal smoothing. Noise reduction is automatically disabled, and momentum confirmation is disabled to allow faster signal generation. Designed for quick entries and exits in volatile markets.
- Day Trading: Balanced configuration for intraday trading with moderate RSI periods (6, 9, 14) and light smoothing. Momentum confirmation is enabled for better signal quality. Ideal for day trading strategies requiring timely but accurate signals.
- Swing Trading: Configured for medium-term positions with standard RSI periods (14, 14, 21) and moderate smoothing. Provides smoother signals suitable for swing trading timeframes. All noise reduction features remain active.
- Position Trading: Optimized for longer-term trades with extended RSI periods (24, 21, 28) and heavier smoothing. Filters are configured for highest-quality signals. Best for position traders holding trades over multiple days or weeks.
- Custom: Full manual control over all settings. All input parameters are available for complete customization. This is the default mode and maintains full backward compatibility with previous versions.
When a preset is selected, it automatically adjusts RSI periods, smoothing lengths, and filter settings to match the trading style. The preset configurations ensure optimal settings are applied instantly, eliminating the need for manual configuration. All settings can still be manually overridden if needed, providing flexibility while maintaining ease of use.
Input Validation and Error Prevention
The script includes comprehensive input validation to prevent configuration errors:
- Cross-Input Validation: Smoothing lengths are automatically validated to ensure they are always less than their corresponding RSI period length. If you set a smoothing length greater than or equal to the RSI length, the script automatically adjusts it to (RSI Length - 1). This prevents logical errors and ensures valid configurations.
- Input Range Validation: All numeric inputs have minimum and maximum value constraints enforced by TradingView's input system, preventing invalid parameter values.
- Smart Defaults: Preset configurations use validated default values that are tested and optimized for each trading style. When switching between presets, all related settings are automatically updated to maintain consistency.
Core Calculations
Multi-Period RSI:
The script calculates RSI using the standard Wilder's RSI formula: RSI = 100 - (100 / (1 + RS)), where RS = Average Gain / Average Loss over the specified period. Three separate RSI calculations run simultaneously:
- RSI(6): Uses 6-period lookback for high sensitivity to recent price changes, useful for scalping and early signal detection
- RSI(14): Standard 14-period RSI for balanced analysis, the most commonly used RSI period
- RSI(24): Longer 24-period RSI for trend confirmation, provides smoother signals with less noise
Each RSI can be smoothed using EMA, SMA, RMA (Wilder's smoothing), WMA, or Zero-Lag smoothing. Zero-Lag smoothing uses the formula: ZL-RSI = RSI + (RSI - RSI ) to reduce lag while maintaining signal quality. You can apply individual smoothing lengths to each RSI period, or use global smoothing where all three RSIs share the same smoothing length.
Dynamic Overbought/Oversold Thresholds:
Static thresholds (default 70/30) are adjusted based on market volatility using ATR. The formula: Dynamic OB = Base OB + (ATR × Volatility Multiplier × Base Percentage / 100), Dynamic OS = Base OS - (ATR × Volatility Multiplier × Base Percentage / 100). This adapts to volatile markets where traditional 70/30 levels may be too restrictive. During high volatility, the dynamic thresholds widen, and during low volatility, they narrow. The thresholds are clamped between 0-100 to remain within RSI bounds. The ATR is cached for performance optimization, updating on confirmed bars and real-time bars.
Adaptive RSI Calculation:
An adaptive RSI adjusts the standard RSI(14) based on current volatility relative to average volatility. The calculation: Adaptive Factor = (Current ATR / SMA of ATR over 20 periods) × Volatility Multiplier. If SMA of ATR is zero (edge case), the adaptive factor defaults to 0. The adaptive RSI = Base RSI × (1 + Adaptive Factor), clamped to 0-100. This makes the indicator more responsive during high volatility periods when traditional RSI may lag. The adaptive RSI is used for signal generation (buy/sell signals) but is not plotted on the chart.
Overbought/Oversold Fill Zones:
The script provides visual fill zones between the RSI line and the threshold lines when RSI is in overbought or oversold territory. The fill logic uses inclusive conditions: fills are shown when RSI is currently in the zone OR was in the zone on the previous bar. This ensures complete coverage of entry and exit boundaries. A minimum gap of 0.1 RSI points is maintained between the RSI plot and threshold line to ensure reliable polygon rendering in TradingView. The fill uses invisible plots at the threshold levels and the RSI value, with the fill color applied between them. You can select which RSI (6, 14, or 24) to use for the fill zones.
Divergence Detection
Regular Divergence:
Bullish divergence: Price makes a lower low (current low < lowest low from previous lookback period) while RSI makes a higher low (current RSI > lowest RSI from previous lookback period). Bearish divergence: Price makes a higher high (current high > highest high from previous lookback period) while RSI makes a lower high (current RSI < highest RSI from previous lookback period). The script compares current price/RSI values to the lowest/highest values from the previous lookback period using ta.lowest() and ta.highest() functions with index to reference the previous period's extreme.
Pivot-Based Divergence:
An enhanced divergence detection method that uses actual pivot points instead of simple lowest/highest comparisons. This provides more accurate divergence detection by identifying significant pivot lows/highs in both price and RSI. The pivot-based method uses a tolerance-based approach with configurable constants: 1% tolerance for price comparisons (priceTolerancePercent = 0.01) and 1.0 RSI point absolute tolerance for RSI comparisons (pivotTolerance = 1.0). Minimum divergence threshold is 1.0 RSI point (minDivergenceThreshold = 1.0). It looks for two recent pivot points and compares them: for bullish divergence, price makes a lower low (at least 1% lower) while RSI makes a higher low (at least 1.0 point higher). This method reduces false divergences by requiring actual pivot points rather than just any low/high within a period. When enabled, pivot-based divergence replaces the traditional method for more accurate signal generation.
Strong Divergence:
Regular divergence is confirmed by an engulfing candle pattern. Bullish engulfing requires: (1) Previous candle is bearish (close < open ), (2) Current candle is bullish (close > open), (3) Current close > previous open, (4) Current open < previous close. Bearish engulfing is the inverse: previous bullish, current bearish, current close < previous open, current open > previous close. Strong divergence signals are marked with visual indicators (🐂 for bullish, 🐻 for bearish) and have separate alert conditions.
Hidden Divergence:
Continuation patterns that signal trend continuation rather than reversal. Bullish hidden divergence: Price makes a higher low (current low > lowest low from previous period) but RSI makes a lower low (current RSI < lowest RSI from previous period). Bearish hidden divergence: Price makes a lower high (current high < highest high from previous period) but RSI makes a higher high (current RSI > highest RSI from previous period). These patterns indicate the trend is likely to continue in the current direction.
Volume Confirmation System
Volume threshold filtering requires current volume to exceed the volume SMA multiplied by the threshold factor. The formula: Volume Confirmed = Volume > (Volume SMA × Threshold). If the threshold is set to 0.1 or lower, volume confirmation is effectively disabled (always returns true). This allows you to use the indicator without volume filtering if desired.
Volume Climax is detected when volume exceeds: Volume SMA + (Volume StdDev × Multiplier). This indicates potential capitulation moments where extreme volume accompanies price movements. Volume Dry-Up is detected when volume falls below: Volume SMA - (Volume StdDev × Multiplier), indicating low participation periods that may produce unreliable signals. The volume SMA is cached for performance, updating on confirmed and real-time bars.
Multi-RSI Synergy
The script generates signals when multiple RSI periods align in overbought or oversold zones. This creates a confirmation system that reduces false signals. In "ALL" mode, all three RSIs (6, 14, 24) must be simultaneously above the overbought threshold OR all three must be below the oversold threshold. In "2-of-3" mode, any two of the three RSIs must align in the same direction. The script counts how many RSIs are in each zone: twoOfThreeOB = ((rsi6OB ? 1 : 0) + (rsi14OB ? 1 : 0) + (rsi24OB ? 1 : 0)) >= 2.
Synergy signals require: (1) Multi-RSI alignment (ALL or 2-of-3), (2) Volume confirmation, (3) Reset condition satisfied (enough bars since last synergy signal), (4) Additional filters passed (RSI50, Trend, ADX, Volume Dry-Up avoidance). Separate reset conditions track buy and sell signals independently. The reset condition uses ta.barssince() to count bars since the last trigger, returning true if the condition never occurred (allowing first signal) or if enough bars have passed.
Regression Forecasting
The script uses historical RSI values to forecast future RSI direction using four methods. The forecast horizon is configurable (1-50 bars ahead). Historical data is collected into an array, and regression coefficients are calculated based on the selected method.
Linear Regression: Calculates the least-squares fit line (y = mx + b) through the last N RSI values. The calculation: meanX = sumX / horizon, meanY = sumY / horizon, denominator = sumX² - horizon × meanX², m = (sumXY - horizon × meanX × meanY) / denominator, b = meanY - m × meanX. The forecast projects this line forward: forecast = b + m × i for i = 1 to horizon.
Polynomial Regression: Fits a quadratic curve (y = ax² + bx + c) to capture non-linear trends. The system of equations is solved using Cramer's rule with a 3×3 determinant. If the determinant is too small (< 0.0001), the system falls back to linear regression. Coefficients are calculated by solving: n×c + sumX×b + sumX²×a = sumY, sumX×c + sumX²×b + sumX³×a = sumXY, sumX²×c + sumX³×b + sumX⁴×a = sumX²Y. Note: Due to the O(n³) computational complexity of polynomial regression, the forecast horizon is automatically limited to a maximum of 20 bars when using polynomial regression to maintain optimal performance. If you set a horizon greater than 20 bars with polynomial regression, it will be automatically capped at 20 bars.
Exponential Smoothing: Applies exponential smoothing with adaptive alpha = 2/(horizon+1). The smoothing iterates from oldest to newest value: smoothed = alpha × series + (1 - alpha) × smoothed. Trend is calculated by comparing current smoothed value to an earlier smoothed value (at 60% of horizon): trend = (smoothed - earlierSmoothed) / (horizon - earlierIdx). Forecast: forecast = base + trend × i.
Moving Average: Uses the difference between short MA (horizon/2) and long MA (horizon) to estimate trend direction. Trend = (maShort - maLong) / (longLen - shortLen). Forecast: forecast = maShort + trend × i.
Confidence bands are calculated using RMSE (Root Mean Squared Error) of historical forecast accuracy. The error calculation compares historical values with forecast values: RMSE = sqrt(sumSquaredError / count). If insufficient data exists, it falls back to calculating standard deviation of recent RSI values. Confidence bands = forecast ± (RMSE × confidenceLevel). All forecast values and confidence bands are clamped to 0-100 to remain within RSI bounds. The regression functions include comprehensive safety checks: horizon validation (must not exceed array size), empty array handling, edge case handling for horizon=1 scenarios, division-by-zero protection, and bounds checking for all array access operations to prevent runtime errors.
Strong Top/Bottom Detection
Strong buy signals require three conditions: (1) RSI is at its lowest point within the bottom period: rsiVal <= ta.lowest(rsiVal, bottomPeriod), (2) RSI is below the oversold threshold minus a buffer: rsiVal < (oversoldThreshold - rsiTopBottomBuffer), where rsiTopBottomBuffer = 2.0 RSI points, (3) The absolute difference between current RSI and the lowest RSI exceeds the threshold value: abs(rsiVal - ta.lowest(rsiVal, bottomPeriod)) > threshold. This indicates a bounce from extreme levels with sufficient distance from the absolute low.
Strong sell signals use the inverse logic: RSI at highest point, above overbought threshold + rsiTopBottomBuffer (2.0 RSI points), and difference from highest exceeds threshold. Both signals also require: volume confirmation, reset condition satisfied (separate reset for buy vs sell), and all additional filters passed (RSI50, Trend, ADX, Volume Dry-Up avoidance).
The reset condition uses separate logic for buy and sell: resetCondBuy checks bars since isRSIAtBottom, resetCondSell checks bars since isRSIAtTop. This ensures buy signals reset based on bottom conditions and sell signals reset based on top conditions, preventing incorrect signal blocking.
Filtering System
RSI(50) Filter: Only allows buy signals when RSI(14) > 50 (bullish momentum) and sell signals when RSI(14) < 50 (bearish momentum). This filter ensures you're buying in uptrends and selling in downtrends from a momentum perspective. The filter is optional and can be disabled. Recommended to enable for noise reduction.
Trend Filter: Uses a long-term EMA (default 200) to determine trend direction. Buy signals require price above EMA, sell signals require price below EMA. The EMA slope is calculated as: emaSlope = ema - ema . Optional EMA slope filter additionally requires the EMA to be rising (slope > 0) for buy signals or falling (slope < 0) for sell signals. This provides stronger trend confirmation by requiring both price position and EMA direction.
ADX Filter: Uses the Directional Movement Index (calculated via ta.dmi()) to measure trend strength. Signals only fire when ADX exceeds the threshold (default 20), indicating a strong trend rather than choppy markets. The ADX calculation uses separate length and smoothing parameters. This filter helps avoid signals during sideways/consolidation periods.
Volume Dry-Up Avoidance: Prevents signals during periods of extremely low volume relative to average. If volume dry-up is detected and the filter is enabled, signals are blocked. This helps avoid unreliable signals that occur during low participation periods.
RSI Momentum Confirmation: Requires RSI to be accelerating in the signal direction before confirming signals. For buy signals, RSI must be consistently rising (recovering from oversold) over the lookback period. For sell signals, RSI must be consistently falling (declining from overbought) over the lookback period. The momentum check verifies that all consecutive changes are in the correct direction AND the cumulative change is significant. This filter ensures signals only fire when RSI momentum aligns with the signal direction, reducing false signals from weak momentum.
Multi-Timeframe Confirmation: Requires higher timeframe RSI to align with the signal direction. For buy signals, current RSI must be below the higher timeframe RSI by at least the confirmation threshold. For sell signals, current RSI must be above the higher timeframe RSI by at least the confirmation threshold. This ensures signals align with the larger trend context, reducing counter-trend trades. The higher timeframe RSI is fetched using request.security() from the selected timeframe.
All filters use the pattern: filterResult = not filterEnabled OR conditionMet. This means if a filter is disabled, it always passes (returns true). Filters can be combined, and all must pass for a signal to fire.
RSI Centerline and Period Crossovers
RSI(50) Centerline Crossovers: Detects when the selected RSI source crosses above or below the 50 centerline. Bullish crossover: ta.crossover(rsiSource, 50), bearish crossover: ta.crossunder(rsiSource, 50). You can select which RSI (6, 14, or 24) to use for these crossovers. These signals indicate momentum shifts from bearish to bullish (above 50) or bullish to bearish (below 50).
RSI Period Crossovers: Detects when different RSI periods cross each other. Available pairs: RSI(6) × RSI(14), RSI(14) × RSI(24), or RSI(6) × RSI(24). Bullish crossover: fast RSI crosses above slow RSI (ta.crossover(rsiFast, rsiSlow)), indicating momentum acceleration. Bearish crossover: fast RSI crosses below slow RSI (ta.crossunder(rsiFast, rsiSlow)), indicating momentum deceleration. These crossovers can signal shifts in momentum before price moves.
StochRSI Calculation
Stochastic RSI applies the Stochastic oscillator formula to RSI values instead of price. The calculation: %K = ((RSI - Lowest RSI) / (Highest RSI - Lowest RSI)) × 100, where the lookback is the StochRSI length. If the range is zero, %K defaults to 50.0. %K is then smoothed using SMA with the %K smoothing length. %D is calculated as SMA of smoothed %K with the %D smoothing length. All values are clamped to 0-100. You can select which RSI (6, 14, or 24) to use as the source for StochRSI calculation.
RSI Bollinger Bands
Bollinger Bands are applied to RSI(14) instead of price. The calculation: Basis = SMA(RSI(14), BB Period), StdDev = stdev(RSI(14), BB Period), Upper = Basis + (StdDev × Deviation Multiplier), Lower = Basis - (StdDev × Deviation Multiplier). This creates dynamic zones around RSI that adapt to RSI volatility. When RSI touches or exceeds the bands, it indicates extreme conditions relative to recent RSI behavior.
Noise Reduction System
The script includes a comprehensive noise reduction system to filter false signals and improve accuracy. When enabled, signals must pass multiple quality checks:
Signal Strength Requirement: RSI must be at least X points away from the centerline (50). For buy signals, RSI must be at least X points below 50. For sell signals, RSI must be at least X points above 50. This ensures signals only trigger when RSI is significantly in oversold/overbought territory, not just near neutral.
Extreme Zone Requirement: RSI must be deep in the OB/OS zone. For buy signals, RSI must be at least X points below the oversold threshold. For sell signals, RSI must be at least X points above the overbought threshold. This ensures signals only fire in extreme conditions where reversals are more likely.
Consecutive Bar Confirmation: The signal condition must persist for N consecutive bars before triggering. This reduces false signals from single-bar spikes or noise. The confirmation checks that the signal condition was true for all bars in the lookback period.
Zone Persistence (Optional): Requires RSI to remain in the OB/OS zone for N consecutive bars, not just touch it. This ensures RSI is truly in an extreme state rather than just briefly touching the threshold. When enabled, this provides stricter filtering for higher-quality signals.
RSI Slope Confirmation (Optional): Requires RSI to be moving in the expected signal direction. For buy signals, RSI should be rising (recovering from oversold). For sell signals, RSI should be falling (declining from overbought). This ensures momentum is aligned with the signal direction. The slope is calculated by comparing current RSI to RSI N bars ago.
All noise reduction filters can be enabled/disabled independently, allowing you to customize the balance between signal frequency and accuracy. The default settings provide a good balance, but you can adjust them based on your trading style and market conditions.
Alert System
The script includes separate alert conditions for each signal type: buy/sell (adaptive RSI crossovers), divergence (regular, strong, hidden), crossovers (RSI50 centerline, RSI period crossovers), synergy signals, and trend breaks. Each alert type has its own alertcondition() declaration with a unique title and message.
An optional cooldown system prevents alert spam by requiring a minimum number of bars between alerts of the same type. The cooldown check: canAlert = na(lastAlertBar) OR (bar_index - lastAlertBar >= cooldownBars). If the last alert bar is na (first alert), it always allows the alert. Each alert type maintains its own lastAlertBar variable, so cooldowns are independent per signal type. The default cooldown is 10 bars, which is recommended for noise reduction.
Higher Timeframe RSI
The script can display RSI from a higher timeframe using request.security(). This allows you to see the RSI context from a larger timeframe (e.g., daily RSI on an hourly chart). The higher timeframe RSI uses RSI(14) calculation from the selected timeframe. This provides context for the current timeframe's RSI position relative to the larger trend.
RSI Pivot Trendlines
The script can draw trendlines connecting pivot highs and lows on RSI(6). This feature helps visualize RSI trends and identify potential trend breaks.
Pivot Detection: Pivots are detected using a configurable period. The script can require pivots to have minimum strength (RSI points difference from surrounding bars) to filter out weak pivots. Lower minPivotStrength values detect more pivots (more trendlines), while higher values detect only stronger pivots (fewer but more significant trendlines). Pivot confirmation is optional: when enabled, the script waits N bars to confirm the pivot remains the extreme, reducing repainting. Pivot confirmation functions (f_confirmPivotLow and f_confirmPivotHigh) are always called on every bar for consistency, as recommended by TradingView. When pivot bars are not available (na), safe default values are used, and the results are then used conditionally based on confirmation settings. This ensures consistent calculations and prevents calculation inconsistencies.
Trendline Drawing: Uptrend lines connect confirmed pivot lows (green), and downtrend lines connect confirmed pivot highs (red). By default, only the most recent trendline is shown (old trendlines are deleted when new pivots are confirmed). This keeps the chart clean and uncluttered. If "Keep Historical Trendlines" is enabled, the script preserves up to N historical trendlines (configurable via "Max Trendlines to Keep", default 5). When historical trendlines are enabled, old trendlines are saved to arrays instead of being deleted, allowing you to see multiple trendlines simultaneously for better trend analysis. The arrays are automatically limited to prevent memory accumulation.
Trend Break Detection: Signals are generated when RSI breaks above or below trendlines. Uptrend breaks (RSI crosses below uptrend line) generate buy signals. Downtrend breaks (RSI crosses above downtrend line) generate sell signals. Optional trend break confirmation requires the break to persist for N bars and optionally include volume confirmation. Trendline angle filtering can exclude flat/weak trendlines from generating signals (minTrendlineAngle > 0 filters out weak/flat trendlines).
How Components Work Together
The combination of multiple RSI periods provides confirmation across different timeframes, reducing false signals. RSI(6) catches early moves, RSI(14) provides balanced signals, and RSI(24) confirms longer-term trends. When all three align (synergy), it indicates strong consensus across timeframes.
Volume confirmation ensures signals occur with sufficient market participation, filtering out low-volume false breakouts. Volume climax detection identifies potential reversal points, while volume dry-up avoidance prevents signals during unreliable low-volume periods.
Trend filters align signals with the overall market direction. The EMA filter ensures you're trading with the trend, and the EMA slope filter adds an additional layer by requiring the trend to be strengthening (rising EMA for buys, falling EMA for sells).
ADX filter ensures signals only fire during strong trends, avoiding choppy/consolidation periods. RSI(50) filter ensures momentum alignment with the trade direction.
Momentum confirmation requires RSI to be accelerating in the signal direction, ensuring signals only fire when momentum is aligned. Multi-timeframe confirmation ensures signals align with higher timeframe trends, reducing counter-trend trades.
Divergence detection identifies potential reversals before they occur, providing early warning signals. Pivot-based divergence provides more accurate detection by using actual pivot points. Hidden divergence identifies continuation patterns, useful for trend-following strategies.
The noise reduction system combines multiple filters (signal strength, extreme zone, consecutive bars, zone persistence, RSI slope) to significantly reduce false signals. These filters work together to ensure only high-quality signals are generated.
The synergy system requires alignment across all RSI periods for highest-quality signals, significantly reducing false positives. Regression forecasting provides forward-looking context, helping anticipate potential RSI direction changes.
Pivot trendlines provide visual trend analysis and can generate signals when RSI breaks trendlines, indicating potential reversals or continuations.
Reset conditions prevent signal spam by requiring a minimum number of bars between signals. Separate reset conditions for buy and sell signals ensure proper signal management.
Usage Instructions
Configuration Presets (Recommended): The script includes optimized preset configurations for instant setup. Simply select your trading style from the "Configuration Preset" dropdown:
- Scalping Preset: RSI(4, 7, 9) with minimal smoothing. Noise reduction disabled, momentum confirmation disabled for fastest signals.
- Day Trading Preset: RSI(6, 9, 14) with light smoothing. Momentum confirmation enabled for better signal quality.
- Swing Trading Preset: RSI(14, 14, 21) with moderate smoothing. Balanced configuration for medium-term trades.
- Position Trading Preset: RSI(24, 21, 28) with heavier smoothing. Optimized for longer-term positions with all filters active.
- Custom Mode: Full manual control over all settings. Default behavior matches previous script versions.
Presets automatically configure RSI periods, smoothing lengths, and filter settings. You can still manually adjust any setting after selecting a preset if needed.
Getting Started: The easiest way to get started is to select a configuration preset matching your trading style (Scalping, Day Trading, Swing Trading, or Position Trading) from the "Configuration Preset" dropdown. This instantly configures all settings for optimal performance. Alternatively, use "Custom" mode for full manual control. The default configuration (Custom mode) shows RSI(6), RSI(14), and RSI(24) with their default smoothing. Overbought/oversold fill zones are enabled by default.
Customizing RSI Periods: Adjust the RSI lengths (6, 14, 24) based on your trading timeframe. Shorter periods (6) for scalping, standard (14) for day trading, longer (24) for swing trading. You can disable any RSI period you don't need.
Smoothing Selection: Choose smoothing method based on your needs. EMA provides balanced smoothing, RMA (Wilder's) is traditional, Zero-Lag reduces lag but may increase noise. Adjust smoothing lengths individually or use global smoothing for consistency. Note: Smoothing lengths are automatically validated to ensure they are always less than the corresponding RSI period length. If you set smoothing >= RSI length, it will be auto-adjusted to prevent invalid configurations.
Dynamic OB/OS: The dynamic thresholds automatically adapt to volatility. Adjust the volatility multiplier and base percentage to fine-tune sensitivity. Higher values create wider thresholds in volatile markets.
Volume Confirmation: Set volume threshold to 1.2 (default) for standard confirmation, higher for stricter filtering, or 0.1 to disable volume filtering entirely.
Multi-RSI Synergy: Use "ALL" mode for highest-quality signals (all 3 RSIs must align), or "2-of-3" mode for more frequent signals. Adjust the reset period to control signal frequency.
Filters: Enable filters gradually to find your preferred balance. Start with volume confirmation, then add trend filter, then ADX for strongest confirmation. RSI(50) filter is useful for momentum-based strategies and is recommended for noise reduction. Momentum confirmation and multi-timeframe confirmation add additional layers of accuracy but may reduce signal frequency.
Noise Reduction: The noise reduction system is enabled by default with balanced settings. Adjust minSignalStrength (default 3.0) to control how far RSI must be from centerline. Increase requireConsecutiveBars (default 1) to require signals to persist longer. Enable requireZonePersistence and requireRsiSlope for stricter filtering (higher quality but fewer signals). Start with defaults and adjust based on your needs.
Divergence: Enable divergence detection and adjust lookback periods. Strong divergence (with engulfing confirmation) provides higher-quality signals. Hidden divergence is useful for trend-following strategies. Enable pivot-based divergence for more accurate detection using actual pivot points instead of simple lowest/highest comparisons. Pivot-based divergence uses tolerance-based matching (1% for price, 1.0 RSI point for RSI) for better accuracy.
Forecasting: Enable regression forecasting to see potential RSI direction. Linear regression is simplest, polynomial captures curves, exponential smoothing adapts to trends. Adjust horizon based on your trading timeframe. Confidence bands show forecast uncertainty - wider bands indicate less reliable forecasts.
Pivot Trendlines: Enable pivot trendlines to visualize RSI trends and identify trend breaks. Adjust pivot detection period (default 5) - higher values detect fewer but stronger pivots. Enable pivot confirmation (default ON) to reduce repainting. Set minPivotStrength (default 1.0) to filter weak pivots - lower values detect more pivots (more trendlines), higher values detect only stronger pivots (fewer trendlines). Enable "Keep Historical Trendlines" to preserve multiple trendlines instead of just the most recent one. Set "Max Trendlines to Keep" (default 5) to control how many historical trendlines are preserved. Enable trend break confirmation for more reliable break signals. Adjust minTrendlineAngle (default 0.0) to filter flat trendlines - set to 0.1-0.5 to exclude weak trendlines.
Alerts: Set up alerts for your preferred signal types. Enable cooldown to prevent alert spam. Each signal type has its own alert condition, so you can be selective about which signals trigger alerts.
Visual Elements and Signal Markers
The script uses various visual markers to indicate signals and conditions:
- "sBottom" label (green): Strong bottom signal - RSI at extreme low with strong buy conditions
- "sTop" label (red): Strong top signal - RSI at extreme high with strong sell conditions
- "SyBuy" label (lime): Multi-RSI synergy buy signal - all RSIs aligned oversold
- "SySell" label (red): Multi-RSI synergy sell signal - all RSIs aligned overbought
- 🐂 emoji (green): Strong bullish divergence detected
- 🐻 emoji (red): Strong bearish divergence detected
- 🔆 emoji: Weak divergence signals (if enabled)
- "H-Bull" label: Hidden bullish divergence
- "H-Bear" label: Hidden bearish divergence
- ⚡ marker (top of pane): Volume climax detected (extreme volume) - positioned at top for visibility
- 💧 marker (top of pane): Volume dry-up detected (very low volume) - positioned at top for visibility
- ↑ triangle (lime): Uptrend break signal - RSI breaks below uptrend line
- ↓ triangle (red): Downtrend break signal - RSI breaks above downtrend line
- Triangle up (lime): RSI(50) bullish crossover
- Triangle down (red): RSI(50) bearish crossover
- Circle markers: RSI period crossovers
All markers are positioned at the RSI value where the signal occurs, using location.absolute for precise placement.
Signal Priority and Interpretation
Signals are generated independently and can occur simultaneously. Higher-priority signals generally indicate stronger setups:
1. Multi-RSI Synergy signals (SyBuy/SySell) - Highest priority: Requires alignment across all RSI periods plus volume and filter confirmation. These are the most reliable signals.
2. Strong Top/Bottom signals (sTop/sBottom) - High priority: Indicates extreme RSI levels with strong bounce conditions. Requires volume confirmation and all filters.
3. Divergence signals - Medium-High priority: Strong divergence (with engulfing) is more reliable than regular divergence. Hidden divergence indicates continuation rather than reversal.
4. Adaptive RSI crossovers - Medium priority: Buy when adaptive RSI crosses below dynamic oversold, sell when it crosses above dynamic overbought. These use volatility-adjusted RSI for more accurate signals.
5. RSI(50) centerline crossovers - Medium priority: Momentum shift signals. Less reliable alone but useful when combined with other confirmations.
6. RSI period crossovers - Lower priority: Early momentum shift indicators. Can provide early warning but may produce false signals in choppy markets.
Best practice: Wait for multiple confirmations. For example, a synergy signal combined with divergence and volume climax provides the strongest setup.
Chart Requirements
For proper script functionality and compliance with TradingView requirements, ensure your chart displays:
- Symbol name: The trading pair or instrument name should be visible
- Timeframe: The chart timeframe should be clearly displayed
- Script name: "Ultimate RSI " should be visible in the indicator title
These elements help traders understand what they're viewing and ensure proper script identification. The script automatically includes this information in the indicator title and chart labels.
Performance Considerations
The script is optimized for performance:
- ATR and Volume SMA are cached using var variables, updating only on confirmed and real-time bars to reduce redundant calculations
- Forecast line arrays are dynamically managed: lines are reused when possible, and unused lines are deleted to prevent memory accumulation
- Calculations use efficient Pine Script functions (ta.rsi, ta.ema, etc.) which are optimized by TradingView
- Array operations are minimized where possible, with direct calculations preferred
- Polynomial regression automatically caps the forecast horizon at 20 bars (POLYNOMIAL_MAX_HORIZON constant) to prevent performance degradation, as polynomial regression has O(n³) complexity. This safeguard ensures optimal performance even with large horizon settings
- Pivot detection includes edge case handling to ensure reliable calculations even on early bars with limited historical data. Regression forecasting functions include comprehensive safety checks: horizon validation (must not exceed array size), empty array handling, edge case handling for horizon=1 scenarios, and division-by-zero protection in all mathematical operations
The script should perform well on all timeframes. On very long historical data, forecast lines may accumulate if the horizon is large; consider reducing the forecast horizon if you experience performance issues. The polynomial regression performance safeguard automatically prevents performance issues for that specific regression type.
Known Limitations and Considerations
- Forecast lines are forward-looking projections and should not be used as definitive predictions. They provide context but are not guaranteed to be accurate.
- Dynamic OB/OS thresholds can exceed 100 or go below 0 in extreme volatility scenarios, but are clamped to 0-100 range. This means in very volatile markets, the dynamic thresholds may not widen as much as the raw calculation suggests.
- Volume confirmation requires sufficient historical volume data. On new instruments or very short timeframes, volume calculations may be less reliable.
- Higher timeframe RSI uses request.security() which may have slight delays on some data feeds.
- Regression forecasting requires at least N bars of history (where N = forecast horizon) before it can generate forecasts. Early bars will not show forecast lines.
- StochRSI calculation requires the selected RSI source to have sufficient history. Very short RSI periods on new charts may produce less reliable StochRSI values initially.
Practical Use Cases
The indicator can be configured for different trading styles and timeframes:
Swing Trading: Select the "Swing Trading" preset for instant optimal configuration. This preset uses RSI periods (14, 14, 21) with moderate smoothing. Alternatively, manually configure: Use RSI(24) with Multi-RSI Synergy in "ALL" mode, combined with trend filter (EMA 200) and ADX filter. This configuration provides high-probability setups with strong confirmation across multiple RSI periods.
Day Trading: Select the "Day Trading" preset for instant optimal configuration. This preset uses RSI periods (6, 9, 14) with light smoothing and momentum confirmation enabled. Alternatively, manually configure: Use RSI(6) with Zero-Lag smoothing for fast signal detection. Enable volume confirmation with threshold 1.2-1.5 for reliable entries. Combine with RSI(50) filter to ensure momentum alignment. Strong top/bottom signals work well for day trading reversals.
Trend Following: Enable trend filter (EMA) and EMA slope filter for strong trend confirmation. Use RSI(14) or RSI(24) with ADX filter to avoid choppy markets. Hidden divergence signals are useful for trend continuation entries.
Reversal Trading: Focus on divergence detection (regular and strong) combined with strong top/bottom signals. Enable volume climax detection to identify capitulation moments. Use RSI(6) for early reversal signals, confirmed by RSI(14) and RSI(24).
Forecasting and Planning: Enable regression forecasting with polynomial or exponential smoothing methods. Use forecast horizon of 10-20 bars for swing trading, 5-10 bars for day trading. Confidence bands help assess forecast reliability.
Multi-Timeframe Analysis: Enable higher timeframe RSI to see context from larger timeframes. For example, use daily RSI on hourly charts to understand the larger trend context. This helps avoid counter-trend trades.
Scalping: Select the "Scalping" preset for instant optimal configuration. This preset uses RSI periods (4, 7, 9) with minimal smoothing, disables noise reduction, and disables momentum confirmation for faster signals. Alternatively, manually configure: Use RSI(6) with minimal smoothing (or Zero-Lag) for ultra-fast signals. Disable most filters except volume confirmation. Use RSI period crossovers (RSI(6) × RSI(14)) for early momentum shifts. Set volume threshold to 1.0-1.2 for less restrictive filtering.
Position Trading: Select the "Position Trading" preset for instant optimal configuration. This preset uses extended RSI periods (24, 21, 28) with heavier smoothing, optimized for longer-term trades. Alternatively, manually configure: Use RSI(24) with all filters enabled (Trend, ADX, RSI(50), Volume Dry-Up avoidance). Multi-RSI Synergy in "ALL" mode provides highest-quality signals.
Practical Tips and Best Practices
Getting Started: The fastest way to get started is to select a configuration preset that matches your trading style. Simply choose "Scalping", "Day Trading", "Swing Trading", or "Position Trading" from the "Configuration Preset" dropdown to instantly configure all settings optimally. For advanced users, use "Custom" mode for full manual control. The default configuration (Custom mode) is balanced and works well across different markets. After observing behavior, customize settings to match your trading style.
Reducing Repainting: All signals are based on confirmed bars, minimizing repainting. The script uses confirmed bar data for all calculations to ensure backtesting accuracy.
Signal Quality: Multi-RSI Synergy signals in "ALL" mode provide the highest-quality signals because they require alignment across all three RSI periods. These signals have lower frequency but higher reliability. For more frequent signals, use "2-of-3" mode. The noise reduction system further improves signal quality by requiring multiple confirmations (signal strength, extreme zone, consecutive bars, optional zone persistence and RSI slope). Adjust noise reduction settings to balance signal frequency vs. accuracy.
Filter Combinations: Start with volume confirmation, then add trend filter for trend alignment, then ADX filter for trend strength. Combining all three filters significantly reduces false signals but also reduces signal frequency. Find your balance based on your risk tolerance.
Volume Filtering: Set volume threshold to 0.1 or lower to effectively disable volume filtering if you trade instruments with unreliable volume data or want to test without volume confirmation. Standard confirmation uses 1.2-1.5 threshold.
RSI Period Selection: RSI(6) is most sensitive and best for scalping or early signal detection. RSI(14) provides balanced signals suitable for day trading. RSI(24) is smoother and better for swing trading and trend confirmation. You can disable any RSI period you don't need to reduce visual clutter.
Smoothing Methods: EMA provides balanced smoothing with moderate lag. RMA (Wilder's smoothing) is traditional and works well for RSI. Zero-Lag reduces lag but may increase noise. WMA gives more weight to recent values. Choose based on your preference for responsiveness vs. smoothness.
Forecasting: Linear regression is simplest and works well for trending markets. Polynomial regression captures curves and works better in ranging markets. Exponential smoothing adapts to trends. Moving average method is most conservative. Use confidence bands to assess forecast reliability.
Divergence: Strong divergence (with engulfing confirmation) is more reliable than regular divergence. Hidden divergence indicates continuation rather than reversal, useful for trend-following strategies. Pivot-based divergence provides more accurate detection by using actual pivot points instead of simple lowest/highest comparisons. Adjust lookback periods based on your timeframe: shorter for day trading, longer for swing trading. Pivot divergence period (default 5) controls the sensitivity of pivot detection.
Dynamic Thresholds: Dynamic OB/OS thresholds automatically adapt to volatility. In volatile markets, thresholds widen; in calm markets, they narrow. Adjust the volatility multiplier and base percentage to fine-tune sensitivity. Higher values create wider thresholds in volatile markets.
Alert Management: Enable alert cooldown (default 10 bars, recommended) to prevent alert spam. Each alert type has its own cooldown, so you can set different cooldowns for different signal types. For example, use shorter cooldown for synergy signals (high quality) and longer cooldown for crossovers (more frequent). The cooldown system works independently for each signal type, preventing spam while allowing different signal types to fire when appropriate.
Technical Specifications
- Pine Script Version: v6
- Indicator Type: Non-overlay (displays in separate panel below price chart)
- Repainting Behavior: Minimal - all signals are based on confirmed bars, ensuring accurate backtesting results
- Performance: Optimized with caching for ATR and volume calculations. Forecast arrays are dynamically managed to prevent memory accumulation.
- Compatibility: Works on all timeframes (1 minute to 1 month) and all instruments (stocks, forex, crypto, futures, etc.)
- Edge Case Handling: All calculations include safety checks for division by zero, NA values, and boundary conditions. Reset conditions and alert cooldowns handle edge cases where conditions never occurred or values are NA.
- Reset Logic: Separate reset conditions for buy signals (based on bottom conditions) and sell signals (based on top conditions) ensure logical correctness.
- Input Parameters: 60+ customizable parameters organized into logical groups for easy configuration. Configuration presets available for instant setup (Scalping, Day Trading, Swing Trading, Position Trading, Custom).
- Noise Reduction: Comprehensive noise reduction system with multiple filters (signal strength, extreme zone, consecutive bars, zone persistence, RSI slope) to reduce false signals.
- Pivot-Based Divergence: Enhanced divergence detection using actual pivot points for improved accuracy.
- Momentum Confirmation: RSI momentum filter ensures signals only fire when RSI is accelerating in the signal direction.
- Multi-Timeframe Confirmation: Optional higher timeframe RSI alignment for trend confirmation.
- Enhanced Pivot Trendlines: Trendline drawing with strength requirements, confirmation, and trend break detection.
Technical Notes
- All RSI values are clamped to 0-100 range to ensure valid oscillator values
- ATR and Volume SMA are cached for performance, updating on confirmed and real-time bars
- Reset conditions handle edge cases: if a condition never occurred, reset returns true (allows first signal)
- Alert cooldown handles na values: if no previous alert, cooldown allows the alert
- Forecast arrays are dynamically sized based on horizon, with unused lines cleaned up
- Fill logic uses a minimum gap (0.1) to ensure reliable polygon rendering in TradingView
- All calculations include safety checks for division by zero and boundary conditions. Regression functions validate that horizon doesn't exceed array size, and all array access operations include bounds checking to prevent out-of-bounds errors
- The script uses separate reset conditions for buy signals (based on bottom conditions) and sell signals (based on top conditions) for logical correctness
- Background coloring uses a fallback system: dynamic color takes priority, then RSI(6) heatmap, then monotone if both are disabled
- Noise reduction filters are applied after accuracy filters, providing multiple layers of signal quality control
- Pivot trendlines use strength requirements to filter weak pivots, reducing noise in trendline drawing. Historical trendlines are stored in arrays and automatically limited to prevent memory accumulation when "Keep Historical Trendlines" is enabled
- Volume climax and dry-up markers are positioned at the top of the pane for better visibility
- All calculations are optimized with conditional execution - features only calculate when enabled (performance optimization)
- Input Validation: Automatic cross-input validation ensures smoothing lengths are always less than RSI period lengths, preventing configuration errors
- Configuration Presets: Four optimized preset configurations (Scalping, Day Trading, Swing Trading, Position Trading) for instant setup, plus Custom mode for full manual control
- Constants Management: Magic numbers extracted to documented constants for improved maintainability and easier tuning (pivot tolerance, divergence thresholds, fill gap, etc.)
- TradingView Function Consistency: All TradingView functions (ta.crossover, ta.crossunder, ta.atr, ta.lowest, ta.highest, ta.lowestbars, ta.highestbars, etc.) and custom functions that depend on historical results (f_consecutiveBarConfirmation, f_rsiSlopeConfirmation, f_rsiZonePersistence, f_applyAllFilters, f_rsiMomentum, f_forecast, f_confirmPivotLow, f_confirmPivotHigh) are called on every bar for consistency, as recommended by TradingView. Results are then used conditionally when needed. This ensures consistent calculations and prevents calculation inconsistencies.
Watermark | Bar Time | Average Daily RangeMulti Info Panel & Watermark
Multi Info Panel & Watermark is a utility indicator that displays several pieces of chart information in a single, customizable panel. It is designed to support intraday and swing analysis by making key data—such as symbol details, date, and average daily range—easy to see at a glance, as well as providing simple tools for notes and backtesting.
Features
Watermark / Custom Note
Optional text overlay that can be used as a watermark or personal note.
Can display a strategy name, reminder, or any other user-defined label on the chart.
Ticker Info
Shows information about the currently active symbol on the chart (for example, symbol name and other basic details depending on the inputs).
Helps keep track of which market or pair is being analyzed, especially when using multiple charts.
Current Date
Displays the current date directly on the chart.
Useful for screenshots, journaling, and documenting analysis.
Average Daily Range (ADR)
Calculates the average daily range of the active symbol over a user-defined number of recent days.
Helps visualize how much price typically moves in a day, which can support position sizing, target setting, or volatility awareness within your own trading approach.
Open Bar Time Marker
Marks the open time of a selected bar (for example, a session open or a specific reference bar).
Primarily intended as a visual aid for manual backtesting and reviewing historical price action.
Usage
Use the watermark and ticker info to keep your charts labeled and organized.
Refer to the ADR readout to understand typical daily volatility of the instrument you are studying.
Use the date and open bar time marker when creating screenshots, trade journals, or when replaying historical sessions for review.
This script does not generate trading signals and does not guarantee any performance or results. It is provided solely as an informational and visualization tool. Always combine it with your own analysis, risk management, and decision-making. Nothing in this indicator or description should be considered financial advice.
Game Theory Trading StrategyGame Theory Trading Strategy: Explanation and Working Logic
This Pine Script (version 5) code implements a trading strategy named "Game Theory Trading Strategy" in TradingView. Unlike the previous indicator, this is a full-fledged strategy with automated entry/exit rules, risk management, and backtesting capabilities. It uses Game Theory principles to analyze market behavior, focusing on herd behavior, institutional flows, liquidity traps, and Nash equilibrium to generate buy (long) and sell (short) signals. Below, I'll explain the strategy's purpose, working logic, key components, and usage tips in detail.
1. General Description
Purpose: The strategy identifies high-probability trading opportunities by combining Game Theory concepts (herd behavior, contrarian signals, Nash equilibrium) with technical analysis (RSI, volume, momentum). It aims to exploit market inefficiencies caused by retail herd behavior, institutional flows, and liquidity traps. The strategy is designed for automated trading with defined risk management (stop-loss/take-profit) and position sizing based on market conditions.
Key Features:
Herd Behavior Detection: Identifies retail panic buying/selling using RSI and volume spikes.
Liquidity Traps: Detects stop-loss hunting zones where price breaks recent highs/lows but reverses.
Institutional Flow Analysis: Tracks high-volume institutional activity via Accumulation/Distribution and volume spikes.
Nash Equilibrium: Uses statistical price bands to assess whether the market is in equilibrium or deviated (overbought/oversold).
Risk Management: Configurable stop-loss (SL) and take-profit (TP) percentages, dynamic position sizing based on Game Theory (minimax principle).
Visualization: Displays Nash bands, signals, background colors, and two tables (Game Theory status and backtest results).
Backtesting: Tracks performance metrics like win rate, profit factor, max drawdown, and Sharpe ratio.
Strategy Settings:
Initial capital: $10,000.
Pyramiding: Up to 3 positions.
Position size: 10% of equity (default_qty_value=10).
Configurable inputs for RSI, volume, liquidity, institutional flow, Nash equilibrium, and risk management.
Warning: This is a strategy, not just an indicator. It executes trades automatically in TradingView's Strategy Tester. Always backtest thoroughly and use proper risk management before live trading.
2. Working Logic (Step by Step)
The strategy processes each bar (candle) to generate signals, manage positions, and update performance metrics. Here's how it works:
a. Input Parameters
The inputs are grouped for clarity:
Herd Behavior (🐑):
RSI Period (14): For overbought/oversold detection.
Volume MA Period (20): To calculate average volume for spike detection.
Herd Threshold (2.0): Volume multiplier for detecting herd activity.
Liquidity Analysis (💧):
Liquidity Lookback (50): Bars to check for recent highs/lows.
Liquidity Sensitivity (1.5): Volume multiplier for trap detection.
Institutional Flow (🏦):
Institutional Volume Multiplier (2.5): For detecting large volume spikes.
Institutional MA Period (21): For Accumulation/Distribution smoothing.
Nash Equilibrium (⚖️):
Nash Period (100): For calculating price mean and standard deviation.
Nash Deviation (0.02): Multiplier for equilibrium bands.
Risk Management (🛡️):
Use Stop-Loss (true): Enables SL at 2% below/above entry price.
Use Take-Profit (true): Enables TP at 5% above/below entry price.
b. Herd Behavior Detection
RSI (14): Checks for extreme conditions:
Overbought: RSI > 70 (potential herd buying).
Oversold: RSI < 30 (potential herd selling).
Volume Spike: Volume > SMA(20) x 2.0 (herd_threshold).
Momentum: Price change over 10 bars (close - close ) compared to its SMA(20).
Herd Signals:
Herd Buying: RSI > 70 + volume spike + positive momentum = Retail buying frenzy (red background).
Herd Selling: RSI < 30 + volume spike + negative momentum = Retail selling panic (green background).
c. Liquidity Trap Detection
Recent Highs/Lows: Calculated over 50 bars (liquidity_lookback).
Psychological Levels: Nearest round numbers (e.g., $100, $110) as potential stop-loss zones.
Trap Conditions:
Up Trap: Price breaks recent high, closes below it, with a volume spike (volume > SMA x 1.5).
Down Trap: Price breaks recent low, closes above it, with a volume spike.
Visualization: Traps are marked with small red/green crosses above/below bars.
d. Institutional Flow Analysis
Volume Check: Volume > SMA(20) x 2.5 (inst_volume_mult) = Institutional activity.
Accumulation/Distribution (AD):
Formula: ((close - low) - (high - close)) / (high - low) * volume, cumulated over time.
Smoothed with SMA(21) (inst_ma_length).
Accumulation: AD > MA + high volume = Institutions buying.
Distribution: AD < MA + high volume = Institutions selling.
Smart Money Index: (close - open) / (high - low) * volume, smoothed with SMA(20). Positive = Smart money buying.
e. Nash Equilibrium
Calculation:
Price mean: SMA(100) (nash_period).
Standard deviation: stdev(100).
Upper Nash: Mean + StdDev x 0.02 (nash_deviation).
Lower Nash: Mean - StdDev x 0.02.
Conditions:
Near Equilibrium: Price between upper and lower Nash bands (stable market).
Above Nash: Price > upper band (overbought, sell potential).
Below Nash: Price < lower band (oversold, buy potential).
Visualization: Orange line (mean), red/green lines (upper/lower bands).
f. Game Theory Signals
The strategy generates three types of signals, combined into long/short triggers:
Contrarian Signals:
Buy: Herd selling + (accumulation or down trap) = Go against retail panic.
Sell: Herd buying + (distribution or up trap).
Momentum Signals:
Buy: Below Nash + positive smart money + no herd buying.
Sell: Above Nash + negative smart money + no herd selling.
Nash Reversion Signals:
Buy: Below Nash + rising close (close > close ) + volume > MA.
Sell: Above Nash + falling close + volume > MA.
Final Signals:
Long Signal: Contrarian buy OR momentum buy OR Nash reversion buy.
Short Signal: Contrarian sell OR momentum sell OR Nash reversion sell.
g. Position Management
Position Sizing (Minimax Principle):
Default: 1.0 (10% of equity).
In Nash equilibrium: Reduced to 0.5 (conservative).
During institutional volume: Increased to 1.5 (aggressive).
Entries:
Long: If long_signal is true and no existing long position (strategy.position_size <= 0).
Short: If short_signal is true and no existing short position (strategy.position_size >= 0).
Exits:
Stop-Loss: If use_sl=true, set at 2% below/above entry price.
Take-Profit: If use_tp=true, set at 5% above/below entry price.
Pyramiding: Up to 3 concurrent positions allowed.
h. Visualization
Nash Bands: Orange (mean), red (upper), green (lower).
Background Colors:
Herd buying: Red (90% transparency).
Herd selling: Green.
Institutional volume: Blue.
Signals:
Contrarian buy/sell: Green/red triangles below/above bars.
Liquidity traps: Red/green crosses above/below bars.
Tables:
Game Theory Table (Top-Right):
Herd Behavior: Buying frenzy, selling panic, or normal.
Institutional Flow: Accumulation, distribution, or neutral.
Nash Equilibrium: In equilibrium, above, or below.
Liquidity Status: Trap detected or safe.
Position Suggestion: Long (green), Short (red), or Wait (gray).
Backtest Table (Bottom-Right):
Total Trades: Number of closed trades.
Win Rate: Percentage of winning trades.
Net Profit/Loss: In USD, colored green/red.
Profit Factor: Gross profit / gross loss.
Max Drawdown: Peak-to-trough equity drop (%).
Win/Loss Trades: Number of winning/losing trades.
Risk/Reward Ratio: Simplified Sharpe ratio (returns / drawdown).
Avg Win/Loss Ratio: Average win per trade / average loss per trade.
Last Update: Current time.
i. Backtesting Metrics
Tracks:
Total trades, winning/losing trades.
Win rate (%).
Net profit ($).
Profit factor (gross profit / gross loss).
Max drawdown (%).
Simplified Sharpe ratio (returns / drawdown).
Average win/loss ratio.
Updates metrics on each closed trade.
Displays a label on the last bar with backtest period, total trades, win rate, and net profit.
j. Alerts
No explicit alertconditions defined, but you can add them for long_signal and short_signal (e.g., alertcondition(long_signal, "GT Long Entry", "Long Signal Detected!")).
Use TradingView's alert system with Strategy Tester outputs.
3. Usage Tips
Timeframe: Best for H1-D1 timeframes. Shorter frames (M1-M15) may produce noisy signals.
Settings:
Risk Management: Adjust sl_percent (e.g., 1% for volatile markets) and tp_percent (e.g., 3% for scalping).
Herd Threshold: Increase to 2.5 for stricter herd detection in choppy markets.
Liquidity Lookback: Reduce to 20 for faster markets (e.g., crypto).
Nash Period: Increase to 200 for longer-term analysis.
Backtesting:
Use TradingView's Strategy Tester to evaluate performance.
Check win rate (>50%), profit factor (>1.5), and max drawdown (<20%) for viability.
Test on different assets/timeframes to ensure robustness.
Live Trading:
Start with a demo account.
Combine with other indicators (e.g., EMAs, support/resistance) for confirmation.
Monitor liquidity traps and institutional flow for context.
Risk Management:
Always use SL/TP to limit losses.
Adjust position_size for risk tolerance (e.g., 5% of equity for conservative trading).
Avoid over-leveraging (pyramiding=3 can amplify risk).
Troubleshooting:
If no trades are executed, check signal conditions (e.g., lower herd_threshold or liquidity_sensitivity).
Ensure sufficient historical data for Nash and liquidity calculations.
If tables overlap, adjust position.top_right/bottom_right coordinates.
4. Key Differences from the Previous Indicator
Indicator vs. Strategy: The previous code was an indicator (VP + Game Theory Integrated Strategy) focused on visualization and alerts. This is a strategy with automated entries/exits and backtesting.
Volume Profile: Absent in this strategy, making it lighter but less focused on high-volume zones.
Wick Analysis: Not included here, unlike the previous indicator's heavy reliance on wick patterns.
Backtesting: This strategy includes detailed performance metrics and a backtest table, absent in the indicator.
Simpler Signals: Focuses on Game Theory signals (contrarian, momentum, Nash reversion) without the "Power/Ultra Power" hierarchy.
Risk Management: Explicit SL/TP and dynamic position sizing, not present in the indicator.
5. Conclusion
The "Game Theory Trading Strategy" is a sophisticated system leveraging herd behavior, institutional flows, liquidity traps, and Nash equilibrium to trade market inefficiencies. It’s designed for traders who understand Game Theory principles and want automated execution with robust risk management. However, it requires thorough backtesting and parameter optimization for specific markets (e.g., forex, crypto, stocks). The backtest table and visual aids make it easy to monitor performance, but always combine with other analysis tools and proper capital management.
If you need help with backtesting, adding alerts, or optimizing parameters, let me know!
Absorption DetectorABSORPTION DETECTOR -
The Absorption Detector identifies institutional order flow by detecting "absorption" patterns where smart money quietly accumulates or distributes positions by absorbing retail order flow. This creates high-probability support and resistance zones for trading. This is an approximation only and does not read any footprint data.
WHAT IS ABSORPTION?
Absorption occurs when institutions take the opposite side of retail trades, creating specific candlestick patterns with high volume and significant wicks. The indicator identifies two main patterns:
SELLING ABSORPTION (P-Pattern): Red zones above candles where institutions sell into retail buying pressure, creating resistance levels. Look for high volume candles with large upper wicks that close in the lower half.
BUYING ABSORPTION (B-Pattern): Green zones below candles where institutions buy from retail selling pressure, creating support levels. Look for high volume candles with large lower wicks that close in the upper half.
KEY FEATURES
- Automatic detection of institutional absorption patterns
- Dynamic support and resistance zone creation
- Customizable styling for all visual elements
- Historic zone display for backtesting analysis
- Strength-based filtering to show only high-probability setups
- Real-time alerts for new absorption patterns
- Professional info panel with key statistics
- Multi-timeframe compatibility
MAIN SETTINGS
Volume Threshold (1.2): Minimum volume surge required compared to average. Higher values = fewer but stronger signals.
Minimum Volume (2500): Absolute volume floor to prevent signals during low-volume periods.
Min Wick Size (0.2): Minimum wick size as ATR multiple. Ensures significant rejection occurred.
Minimum Strength (1.5): Combined volume and wick strength filter. Higher values = higher quality signals.
Show Historic Zones (OFF): Enable to see all historical zones for backtesting. Disable for better performance.
Zone Extension (20): How many bars to project zones forward for anticipating future reactions.
TRADING APPROACH
ZONE REACTION STRATEGY: Wait for price to approach absorption zones and trade the bounce or rejection. Use the zones as dynamic support and resistance levels.
BREAKOUT STRATEGY: Trade decisive breaks of strong absorption zones with proper risk management. Failed zones often lead to strong moves.
CONFLUENCE TRADING: Combine absorption zones with other technical analysis for highest probability setups. Look for alignment with trend lines, Fibonacci levels, and key support/resistance.
RISK MANAGEMENT: Always use stop losses beyond the absorption zones. Target minimum 1:2 risk-reward ratios. Position size appropriately based on zone strength.
OPTIMIZATION GUIDE
For Conservative Trading (fewer, higher quality signals):
- Volume Threshold: 1.5
- Minimum Strength: 2.0
- Min Wick Size: 0.3
For Aggressive Trading (more signals, requires careful filtering):
- Volume Threshold: 1.1
- Minimum Strength: 1.0
- Min Wick Size: 0.15
BEST PRACTICES
Markets: Works best on liquid instruments with good volume - major forex pairs, popular stocks, liquid futures, and established cryptocurrencies.
Timeframes: Effective on all timeframes from 1-minute scalping to daily swing trading. Adjust settings based on your timeframe and trading style.
Confirmation: Never trade absorption signals in isolation. Always combine with trend analysis, market structure, and proper risk management.
Session Timing: Be aware of market sessions and avoid trading during low liquidity periods or major news events.
Backtesting: Use the historic zones feature to validate performance on your chosen market and timeframe before live trading.
CUSTOMIZATION
The indicator offers complete visual customization including zone colors, border styles, label appearances, and info panel positioning. All colors can be adapted to match your chart theme and personal preferences.
Alert system provides both basic and custom message alerts for real-time notifications of new absorption patterns.
PERFORMANCE NOTES
Default settings are optimized for most markets and timeframes. For best performance on older charts, keep "Show Historic Zones" disabled unless specifically backtesting.
The indicator maintains excellent performance even with extensive historical analysis enabled, handling up to 500 zones and 100 labels for comprehensive backtesting.
Zero Lag Trend Signals (MTF) [Quant Trading] V7Overview
The Zero Lag Trend Signals (MTF) V7 is a comprehensive trend-following strategy that combines Zero Lag Exponential Moving Average (ZLEMA) with volatility-based bands to identify high-probability trade entries and exits. This strategy is designed to reduce lag inherent in traditional moving averages while incorporating dynamic risk management through ATR-based stops and multiple exit mechanisms.
This is a longer term horizon strategy that takes limited trades. It is not a high frequency trading and therefore will also have limited data and not > 100 trades.
How It Works
Core Signal Generation:
The strategy uses a Zero Lag EMA (ZLEMA) calculated by applying an EMA to price data that has been adjusted for lag:
Calculate lag period: floor((length - 1) / 2)
Apply lag correction: src + (src - src )
Calculate ZLEMA: EMA of lag-corrected price
Volatility bands are created using the highest ATR over a lookback period multiplied by a band multiplier. These bands are added to and subtracted from the ZLEMA line to create upper and lower boundaries.
Trend Detection:
The strategy maintains a trend variable that switches between bullish (1) and bearish (-1):
Long Signal: Triggers when price crosses above ZLEMA + volatility band
Short Signal: Triggers when price crosses below ZLEMA - volatility band
Optional ZLEMA Trend Confirmation:
When enabled, this filter requires ZLEMA to show directional momentum before entry:
Bullish Confirmation: ZLEMA must increase for 4 consecutive bars
Bearish Confirmation: ZLEMA must decrease for 4 consecutive bars
This additional filter helps avoid false signals in choppy or ranging markets.
Risk Management Features:
The strategy includes multiple stop-loss and take-profit mechanisms:
Volatility-Based Stops: Default stop-loss is placed at ZLEMA ± volatility band
ATR-Based Stops: Dynamic stop-loss calculated as entry price ± (ATR × multiplier)
ATR Trailing Stop: Ratcheting stop-loss that follows price but never moves against position
Risk-Reward Profit Target: Take-profit level set as a multiple of stop distance
Break-Even Stop: Moves stop to entry price after reaching specified R:R ratio
Trend-Based Exit: Closes position when price crosses EMA in opposite direction
Performance Tracking:
The strategy includes optional features for monitoring and analyzing trades:
Floating Statistics Table: Displays key metrics including win rate, GOA (Gain on Account), net P&L, and max drawdown
Trade Log Labels: Shows entry/exit prices, P&L, bars held, and exit reason for each closed trade
CSV Export Fields: Outputs trade data for external analysis
Default Strategy Settings
Commission & Slippage:
Commission: 0.1% per trade
Slippage: 3 ticks
Initial Capital: $1,000
Position Size: 100% of equity per trade
Main Calculation Parameters:
Length: 70 (range: 70-7000) - Controls ZLEMA calculation period
Band Multiplier: 1.2 - Adjusts width of volatility bands
Entry Conditions (All Disabled by Default):
Use ZLEMA Trend Confirmation: OFF - Requires ZLEMA directional momentum
Re-Enter on Long Trend: OFF - Allows multiple entries during sustained trends
Short Trades:
Allow Short Trades: OFF - Strategy is long-only by default
Performance Settings (All Disabled by Default):
Use Profit Target: OFF
Profit Target Risk-Reward Ratio: 2.0 (when enabled)
Dynamic TP/SL (All Disabled by Default):
Use ATR-Based Stop-Loss & Take-Profit: OFF
ATR Length: 14
Stop-Loss ATR Multiplier: 1.5
Profit Target ATR Multiplier: 2.5
Use ATR Trailing Stop: OFF
Trailing Stop ATR Multiplier: 1.5
Use Break-Even Stop-Loss: OFF
Move SL to Break-Even After RR: 1.5
Use Trend-Based Take Profit: OFF
EMA Exit Length: 9
Trade Data Display (All Disabled by Default):
Show Floating Stats Table: OFF
Show Trade Log Labels: OFF
Enable CSV Export: OFF
Trade Label Vertical Offset: 0.5
Backtesting Date Range:
Start Date: January 1, 2018
End Date: December 31, 2069
Important Usage Notes
Default Configuration: The strategy operates in its most basic form with default settings - using only ZLEMA crossovers with volatility bands and volatility-based stop-losses. All advanced features must be manually enabled.
Stop-Loss Priority: If multiple stop-loss methods are enabled simultaneously, the strategy will use whichever condition is hit first. ATR-based stops override volatility-based stops when enabled.
Long-Only by Default: Short trading is disabled by default. Enable "Allow Short Trades" to trade both directions.
Performance Monitoring: Enable the floating stats table and trade log labels to visualize strategy performance during backtesting.
Exit Mechanisms: The strategy can exit trades through multiple methods: stop-loss hit, take-profit reached, trend reversal, or trailing stop activation. The trade log identifies which exit method was used.
Re-Entry Logic: When "Re-Enter on Long Trend" is enabled with ZLEMA trend confirmation, the strategy can take multiple long positions during extended uptrends as long as all entry conditions remain valid.
Capital Efficiency: Default setting uses 100% of equity per trade. Adjust "default_qty_value" to manage position sizing based on risk tolerance.
Realistic Backtesting: Strategy includes commission (0.1%) and slippage (3 ticks) to provide realistic performance expectations. These values should be adjusted based on your broker and market conditions.
Recommended Use Cases
Trending Markets: Best suited for markets with clear directional moves where trend-following strategies excel
Medium to Long-Term Trading: The default length of 70 makes this strategy more appropriate for swing trading rather than scalping
Risk-Conscious Traders: Multiple stop-loss options allow traders to customize risk management to their comfort level
Backtesting & Optimization: Comprehensive performance tracking features make this strategy ideal for testing different parameter combinations
Limitations & Considerations
Like all trend-following strategies, performance may suffer in choppy or ranging markets
Default 100% position sizing means full capital exposure per trade - consider reducing for conservative risk management
Higher length values (70+) reduce signal frequency but may improve signal quality
Multiple simultaneous risk management features may create conflicting exit signals
Past performance shown in backtests does not guarantee future results
Customization Tips
For more aggressive trading:
Reduce length parameter (minimum 70)
Decrease band multiplier for tighter bands
Enable short trades
Use lower profit target R:R ratios
For more conservative trading:
Increase length parameter
Enable ZLEMA trend confirmation
Use wider ATR stop-loss multipliers
Enable break-even stop-loss
Reduce position size from 100% default
For optimal choppy market performance:
Enable ZLEMA trend confirmation
Increase band multiplier
Use tighter profit targets
Avoid re-entry on trend continuation
Visual Elements
The strategy plots several elements on the chart:
ZLEMA line (color-coded by trend direction)
Upper and lower volatility bands
Long entry markers (green triangles)
Short entry markers (red triangles, when enabled)
Stop-loss levels (when positions are open)
Take-profit levels (when enabled and positions are open)
Trailing stop lines (when enabled and positions are open)
Optional ZLEMA trend markers (triangles at highs/lows)
Optional trade log labels showing complete trade information
Exit Reason Codes (for CSV Export)
When CSV export is enabled, exit reasons are coded as:
0 = Manual/Other
1 = Trailing Stop-Loss
2 = Profit Target
3 = ATR Stop-Loss
4 = Trend Change
Conclusion
Zero Lag Trend Signals V7 provides a robust framework for trend-following with extensive customization options. The strategy balances simplicity in its core logic with sophisticated risk management features, making it suitable for both beginner and advanced traders. By reducing moving average lag while incorporating volatility-based signals, it aims to capture trends earlier while managing risk through multiple configurable exit mechanisms.
The modular design allows traders to start with basic trend-following and progressively add complexity through ZLEMA confirmation, multiple stop-loss methods, and advanced exit strategies. Comprehensive performance tracking and export capabilities make this strategy an excellent tool for systematic testing and optimization.
Note: This strategy is provided for educational and backtesting purposes. All trading involves risk. Past performance does not guarantee future results. Always test thoroughly with paper trading before risking real capital, and adjust position sizing and risk parameters according to your risk tolerance and account size.
================================================================================
TAGS:
================================================================================
trend following, ZLEMA, zero lag, volatility bands, ATR stops, risk management, swing trading, momentum, trend confirmation, backtesting
================================================================================
CATEGORY:
================================================================================
Strategies
================================================================================
CHART SETUP RECOMMENDATIONS:
================================================================================
For optimal visualization when publishing:
Use a clean chart with no other indicators overlaid
Select a timeframe that shows multiple trade signals (4H or Daily recommended)
Choose a trending asset (crypto, forex major pairs, or trending stocks work well)
Show at least 6-12 months of data to demonstrate strategy across different market conditions
Enable the floating stats table to display key performance metrics
Ensure all indicator lines (ZLEMA, bands, stops) are clearly visible
Use the default chart type (candlesticks) - avoid Heikin Ashi, Renko, etc.
Make sure symbol information and timeframe are clearly visible
================================================================================
COMPLIANCE NOTES:
================================================================================
✅ Open-source publication with complete code visibility
✅ English-only title and description
✅ Detailed explanation of methodology and calculations
✅ Realistic commission (0.1%) and slippage (3 ticks) included
✅ All default parameters clearly documented
✅ Performance limitations and risks disclosed
✅ No unrealistic claims about performance
✅ No guaranteed results promised
✅ Appropriate for public library (original trend-following implementation with ZLEMA)
✅ Educational disclaimers included
✅ All features explained in detail
================================================================================
Asset Rotation System [InvestorUnknown]Overview
This system creates a comprehensive trend "matrix" by analyzing the performance of six assets against both the US Dollar and each other. The objective is to identify and hold the asset that is currently outperforming all others, thereby focusing on maintaining an investment in the most "optimal" asset at any given time.
- - - Key Features - - -
1. Trend Classification:
The system evaluates the trend for each of the six assets, both individually against USD and in pairs (assetX/assetY), to determine which asset is currently outperforming others.
Utilizes five distinct trend indicators: RSI (50 crossover), CCI, SuperTrend, DMI, and Parabolic SAR.
Users can customize the trend analysis by selecting all indicators or choosing a single one via the "Trend Classification Method" input setting.
2. Backtesting:
Calculates an equity curve for each asset and for the system itself, which assumes holding only the asset deemed optimal at any time.
Customizable start date for backtesting; by default, it begins either 5000 bars ago (the maximum in TradingView) or at the inception of the youngest asset included, whichever is shorter. If the youngest asset's history exceeds 5000 bars, the system uses 5000 bars to prevent errors.
The equity curve is dynamically colored based on the asset held at each point, with this coloring also reflected on the chart via barcolor().
Performance metrics like returns, standard deviation of returns, Sharpe, Sortino, and Omega ratios, along with maximum drawdown, are computed for each asset and the system's equity curve.
3 Alerts:
Supports alerts for when a new, confirmed optimal asset is identified. However, due to TradingView limitations, the specific asset cannot be included in the alert message.
- - - Usage - - -
1. Select Assets/Tickers:
Choose which assets or tickers you want to include in the rotation system. Ensure that all selected tickers are denominated in USD to maintain consistency in analysis.
2. Configure Trend Classification:
Decide on the trend classification method from the available options (RSI, CCI, SuperTrend, DMI, or Parabolic SAR, All) and adjust the settings to your preferences. This customization allows you to tailor the system to different market conditions or your specific trading strategy.
3. Utilize Backtesting for Calibration:
Use the backtesting results, including equity curves and performance metrics, to fine-tune your chosen trend indicators.
Be cautious not to overemphasize performance maximization, as this can lead to overfitting. The goal is to achieve a robust system that performs well across various market conditions, rather than just optimizing for past data.
- - - Parameters - - -
Tickers:
Asset 1: Select the symbol for the first asset.
Asset 2: Select the symbol for the second asset.
Asset 3: Select the symbol for the third asset.
Asset 4: Select the symbol for the fourth asset.
Asset 5: Select the symbol for the fifth asset.
Asset 6: Select the symbol for the sixth asset.
General Settings:
Trend Classification Method: Choose from RSI, CCI, SuperTrend, DMI, PSAR, or "All" to determine how trends are analyzed.
Use Custom Starting Date for Backtest: Toggle to use a custom date for beginning the backtest.
Custom Starting Date: Set the custom start date for backtesting.
Plot Perf. Metrics Table: Option to display performance metrics in a table on the chart.
RSI (Relative Strength Index):
RSI Source: Choose the price data source for RSI calculation.
RSI Length: Set the period for the RSI calculation.
CCI (Commodity Channel Index):
CCI Source: Select the price data source for CCI calculation.
CCI Length: Determine the period for the CCI.
SuperTrend:
SuperTrend Factor: Adjust the sensitivity of the SuperTrend indicator.
SuperTrend Length: Set the period for the SuperTrend calculation.
DMI (Directional Movement Index):
DMI Length: Define the period for DMI calculations.
Parabolic SAR:
PSAR Start: Initial acceleration factor for the Parabolic SAR.
PSAR Increment: Increment value for the acceleration factor.
PSAR Max Value: Maximum value the acceleration factor can reach.
Notes/Recommendations:
While this system is operational, it's important to recognize that it relies on "basic" indicators, which may not be ideal for generating trading signals on their own. I strongly suggest that users delve into the code to grasp the underlying logic of the system. Consider customizing it by integrating more sophisticated and higher-quality trend-following indicators to enhance its performance and reliability.
Disclaimer:
This system's backtest results are historical and do not predict future performance. Use for educational purposes only; not investment advice.
Intraday Session Levels: Pre-Mkt, 5m, 15m (Replay/Toggle/Labels)Intraday Session Levels: Pre-Mkt, 5m, 15m (Replay/Toggle/Labels)
Version v1.0
Live session levels for every trader!
This indicator automatically tracks and draws the most actionable intraday levels as they develop—live in real-time and fully compatible with TradingView’s bar replay and backtesting.
How it works:
Pre-Market High & Low:
Levels appear and update live as soon as the pre-market session starts (4:00am ET), then “freeze” at the official open (9:30am ET) and remain visible for the rest of the day.
First 5-Minute Candle High/Low:
Drawn instantly after the first 5-minute candle (9:30–9:35am ET) completes.
First 15-Minute Candle High/Low:
Drawn right after the first 15-minute candle (9:30–9:45am ET) completes.
Labels on every line
Each level is clearly labeled on your chart (“PreMkt High”, “5m Low”, “15m High”, etc).
Perfect for backtesting:
All levels display exactly as they would have appeared in real time, making this indicator fully bar replay and historical test compatible.
Flexible ON/OFF toggles:
Instantly show or hide Pre-Mkt, 5m, and 15m levels via the settings panel.
Why use it?
Identify support/resistance and key reaction zones intraday
Fade or break the opening range with confidence
Backtest your strategies with accurate historical context
Reduce chart clutter with customizable, minimal visuals
Whether you’re a scalper, day trader, or backtest enthusiast, this tool keeps your charts focused and your edge sharp.
Developed by
Markov Chain [3D] | FractalystWhat exactly is a Markov Chain?
This indicator uses a Markov Chain model to analyze, quantify, and visualize the transitions between market regimes (Bull, Bear, Neutral) on your chart. It dynamically detects these regimes in real-time, calculates transition probabilities, and displays them as animated 3D spheres and arrows, giving traders intuitive insight into current and future market conditions.
How does a Markov Chain work, and how should I read this spheres-and-arrows diagram?
Think of three weather modes: Sunny, Rainy, Cloudy.
Each sphere is one mode. The loop on a sphere means “stay the same next step” (e.g., Sunny again tomorrow).
The arrows leaving a sphere show where things usually go next if they change (e.g., Sunny moving to Cloudy).
Some paths matter more than others. A more prominent loop means the current mode tends to persist. A more prominent outgoing arrow means a change to that destination is the usual next step.
Direction isn’t symmetric: moving Sunny→Cloudy can behave differently than Cloudy→Sunny.
Now relabel the spheres to markets: Bull, Bear, Neutral.
Spheres: market regimes (uptrend, downtrend, range).
Self‑loop: tendency for the current regime to continue on the next bar.
Arrows: the most common next regime if a switch happens.
How to read: Start at the sphere that matches current bar state. If the loop stands out, expect continuation. If one outgoing path stands out, that switch is the typical next step. Opposite directions can differ (Bear→Neutral doesn’t have to match Neutral→Bear).
What states and transitions are shown?
The three market states visualized are:
Bullish (Bull): Upward or strong-market regime.
Bearish (Bear): Downward or weak-market regime.
Neutral: Sideways or range-bound regime.
Bidirectional animated arrows and probability labels show how likely the market is to move from one regime to another (e.g., Bull → Bear or Neutral → Bull).
How does the regime detection system work?
You can use either built-in price returns (based on adaptive Z-score normalization) or supply three custom indicators (such as volume, oscillators, etc.).
Values are statistically normalized (Z-scored) over a configurable lookback period.
The normalized outputs are classified into Bull, Bear, or Neutral zones.
If using three indicators, their regime signals are averaged and smoothed for robustness.
How are transition probabilities calculated?
On every confirmed bar, the algorithm tracks the sequence of detected market states, then builds a rolling window of transitions.
The code maintains a transition count matrix for all regime pairs (e.g., Bull → Bear).
Transition probabilities are extracted for each possible state change using Laplace smoothing for numerical stability, and frequently updated in real-time.
What is unique about the visualization?
3D animated spheres represent each regime and change visually when active.
Animated, bidirectional arrows reveal transition probabilities and allow you to see both dominant and less likely regime flows.
Particles (moving dots) animate along the arrows, enhancing the perception of regime flow direction and speed.
All elements dynamically update with each new price bar, providing a live market map in an intuitive, engaging format.
Can I use custom indicators for regime classification?
Yes! Enable the "Custom Indicators" switch and select any three chart series as inputs. These will be normalized and combined (each with equal weight), broadening the regime classification beyond just price-based movement.
What does the “Lookback Period” control?
Lookback Period (default: 100) sets how much historical data builds the probability matrix. Shorter periods adapt faster to regime changes but may be noisier. Longer periods are more stable but slower to adapt.
How is this different from a Hidden Markov Model (HMM)?
It sets the window for both regime detection and probability calculations. Lower values make the system more reactive, but potentially noisier. Higher values smooth estimates and make the system more robust.
How is this Markov Chain different from a Hidden Markov Model (HMM)?
Markov Chain (as here): All market regimes (Bull, Bear, Neutral) are directly observable on the chart. The transition matrix is built from actual detected regimes, keeping the model simple and interpretable.
Hidden Markov Model: The actual regimes are unobservable ("hidden") and must be inferred from market output or indicator "emissions" using statistical learning algorithms. HMMs are more complex, can capture more subtle structure, but are harder to visualize and require additional machine learning steps for training.
A standard Markov Chain models transitions between observable states using a simple transition matrix, while a Hidden Markov Model assumes the true states are hidden (latent) and must be inferred from observable “emissions” like price or volume data. In practical terms, a Markov Chain is transparent and easier to implement and interpret; an HMM is more expressive but requires statistical inference to estimate hidden states from data.
Markov Chain: states are observable; you directly count or estimate transition probabilities between visible states. This makes it simpler, faster, and easier to validate and tune.
HMM: states are hidden; you only observe emissions generated by those latent states. Learning involves machine learning/statistical algorithms (commonly Baum–Welch/EM for training and Viterbi for decoding) to infer both the transition dynamics and the most likely hidden state sequence from data.
How does the indicator avoid “repainting” or look-ahead bias?
All regime changes and matrix updates happen only on confirmed (closed) bars, so no future data is leaked, ensuring reliable real-time operation.
Are there practical tuning tips?
Tune the Lookback Period for your asset/timeframe: shorter for fast markets, longer for stability.
Use custom indicators if your asset has unique regime drivers.
Watch for rapid changes in transition probabilities as early warning of a possible regime shift.
Who is this indicator for?
Quants and quantitative researchers exploring probabilistic market modeling, especially those interested in regime-switching dynamics and Markov models.
Programmers and system developers who need a probabilistic regime filter for systematic and algorithmic backtesting:
The Markov Chain indicator is ideally suited for programmatic integration via its bias output (1 = Bull, 0 = Neutral, -1 = Bear).
Although the visualization is engaging, the core output is designed for automated, rules-based workflows—not for discretionary/manual trading decisions.
Developers can connect the indicator’s output directly to their Pine Script logic (using input.source()), allowing rapid and robust backtesting of regime-based strategies.
It acts as a plug-and-play regime filter: simply plug the bias output into your entry/exit logic, and you have a scientifically robust, probabilistically-derived signal for filtering, timing, position sizing, or risk regimes.
The MC's output is intentionally "trinary" (1/0/-1), focusing on clear regime states for unambiguous decision-making in code. If you require nuanced, multi-probability or soft-label state vectors, consider expanding the indicator or stacking it with a probability-weighted logic layer in your scripting.
Because it avoids subjectivity, this approach is optimal for systematic quants, algo developers building backtested, repeatable strategies based on probabilistic regime analysis.
What's the mathematical foundation behind this?
The mathematical foundation behind this Markov Chain indicator—and probabilistic regime detection in finance—draws from two principal models: the (standard) Markov Chain and the Hidden Markov Model (HMM).
How to use this indicator programmatically?
The Markov Chain indicator automatically exports a bias value (+1 for Bullish, -1 for Bearish, 0 for Neutral) as a plot visible in the Data Window. This allows you to integrate its regime signal into your own scripts and strategies for backtesting, automation, or live trading.
Step-by-Step Integration with Pine Script (input.source)
Add the Markov Chain indicator to your chart.
This must be done first, since your custom script will "pull" the bias signal from the indicator's plot.
In your strategy, create an input using input.source()
Example:
//@version=5
strategy("MC Bias Strategy Example")
mcBias = input.source(close, "MC Bias Source")
After saving, go to your script’s settings. For the “MC Bias Source” input, select the plot/output of the Markov Chain indicator (typically its bias plot).
Use the bias in your trading logic
Example (long only on Bull, flat otherwise):
if mcBias == 1
strategy.entry("Long", strategy.long)
else
strategy.close("Long")
For more advanced workflows, combine mcBias with additional filters or trailing stops.
How does this work behind-the-scenes?
TradingView’s input.source() lets you use any plot from another indicator as a real-time, “live” data feed in your own script (source).
The selected bias signal is available to your Pine code as a variable, enabling logical decisions based on regime (trend-following, mean-reversion, etc.).
This enables powerful strategy modularity : decouple regime detection from entry/exit logic, allowing fast experimentation without rewriting core signal code.
Integrating 45+ Indicators with Your Markov Chain — How & Why
The Enhanced Custom Indicators Export script exports a massive suite of over 45 technical indicators—ranging from classic momentum (RSI, MACD, Stochastic, etc.) to trend, volume, volatility, and oscillator tools—all pre-calculated, centered/scaled, and available as plots.
// Enhanced Custom Indicators Export - 45 Technical Indicators
// Comprehensive technical analysis suite for advanced market regime detection
//@version=6
indicator('Enhanced Custom Indicators Export | Fractalyst', shorttitle='Enhanced CI Export', overlay=false, scale=scale.right, max_labels_count=500, max_lines_count=500)
// |----- Input Parameters -----| //
momentum_group = "Momentum Indicators"
trend_group = "Trend Indicators"
volume_group = "Volume Indicators"
volatility_group = "Volatility Indicators"
oscillator_group = "Oscillator Indicators"
display_group = "Display Settings"
// Common lengths
length_14 = input.int(14, "Standard Length (14)", minval=1, maxval=100, group=momentum_group)
length_20 = input.int(20, "Medium Length (20)", minval=1, maxval=200, group=trend_group)
length_50 = input.int(50, "Long Length (50)", minval=1, maxval=200, group=trend_group)
// Display options
show_table = input.bool(true, "Show Values Table", group=display_group)
table_size = input.string("Small", "Table Size", options= , group=display_group)
// |----- MOMENTUM INDICATORS (15 indicators) -----| //
// 1. RSI (Relative Strength Index)
rsi_14 = ta.rsi(close, length_14)
rsi_centered = rsi_14 - 50
// 2. Stochastic Oscillator
stoch_k = ta.stoch(close, high, low, length_14)
stoch_d = ta.sma(stoch_k, 3)
stoch_centered = stoch_k - 50
// 3. Williams %R
williams_r = ta.stoch(close, high, low, length_14) - 100
// 4. MACD (Moving Average Convergence Divergence)
= ta.macd(close, 12, 26, 9)
// 5. Momentum (Rate of Change)
momentum = ta.mom(close, length_14)
momentum_pct = (momentum / close ) * 100
// 6. Rate of Change (ROC)
roc = ta.roc(close, length_14)
// 7. Commodity Channel Index (CCI)
cci = ta.cci(close, length_20)
// 8. Money Flow Index (MFI)
mfi = ta.mfi(close, length_14)
mfi_centered = mfi - 50
// 9. Awesome Oscillator (AO)
ao = ta.sma(hl2, 5) - ta.sma(hl2, 34)
// 10. Accelerator Oscillator (AC)
ac = ao - ta.sma(ao, 5)
// 11. Chande Momentum Oscillator (CMO)
cmo = ta.cmo(close, length_14)
// 12. Detrended Price Oscillator (DPO)
dpo = close - ta.sma(close, length_20)
// 13. Price Oscillator (PPO)
ppo = ta.sma(close, 12) - ta.sma(close, 26)
ppo_pct = (ppo / ta.sma(close, 26)) * 100
// 14. TRIX
trix_ema1 = ta.ema(close, length_14)
trix_ema2 = ta.ema(trix_ema1, length_14)
trix_ema3 = ta.ema(trix_ema2, length_14)
trix = ta.roc(trix_ema3, 1) * 10000
// 15. Klinger Oscillator
klinger = ta.ema(volume * (high + low + close) / 3, 34) - ta.ema(volume * (high + low + close) / 3, 55)
// 16. Fisher Transform
fisher_hl2 = 0.5 * (hl2 - ta.lowest(hl2, 10)) / (ta.highest(hl2, 10) - ta.lowest(hl2, 10)) - 0.25
fisher = 0.5 * math.log((1 + fisher_hl2) / (1 - fisher_hl2))
// 17. Stochastic RSI
stoch_rsi = ta.stoch(rsi_14, rsi_14, rsi_14, length_14)
stoch_rsi_centered = stoch_rsi - 50
// 18. Relative Vigor Index (RVI)
rvi_num = ta.swma(close - open)
rvi_den = ta.swma(high - low)
rvi = rvi_den != 0 ? rvi_num / rvi_den : 0
// 19. Balance of Power (BOP)
bop = (close - open) / (high - low)
// |----- TREND INDICATORS (10 indicators) -----| //
// 20. Simple Moving Average Momentum
sma_20 = ta.sma(close, length_20)
sma_momentum = ((close - sma_20) / sma_20) * 100
// 21. Exponential Moving Average Momentum
ema_20 = ta.ema(close, length_20)
ema_momentum = ((close - ema_20) / ema_20) * 100
// 22. Parabolic SAR
sar = ta.sar(0.02, 0.02, 0.2)
sar_trend = close > sar ? 1 : -1
// 23. Linear Regression Slope
lr_slope = ta.linreg(close, length_20, 0) - ta.linreg(close, length_20, 1)
// 24. Moving Average Convergence (MAC)
mac = ta.sma(close, 10) - ta.sma(close, 30)
// 25. Trend Intensity Index (TII)
tii_sum = 0.0
for i = 1 to length_20
tii_sum += close > close ? 1 : 0
tii = (tii_sum / length_20) * 100
// 26. Ichimoku Cloud Components
ichimoku_tenkan = (ta.highest(high, 9) + ta.lowest(low, 9)) / 2
ichimoku_kijun = (ta.highest(high, 26) + ta.lowest(low, 26)) / 2
ichimoku_signal = ichimoku_tenkan > ichimoku_kijun ? 1 : -1
// 27. MESA Adaptive Moving Average (MAMA)
mama_alpha = 2.0 / (length_20 + 1)
mama = ta.ema(close, length_20)
mama_momentum = ((close - mama) / mama) * 100
// 28. Zero Lag Exponential Moving Average (ZLEMA)
zlema_lag = math.round((length_20 - 1) / 2)
zlema_data = close + (close - close )
zlema = ta.ema(zlema_data, length_20)
zlema_momentum = ((close - zlema) / zlema) * 100
// |----- VOLUME INDICATORS (6 indicators) -----| //
// 29. On-Balance Volume (OBV)
obv = ta.obv
// 30. Volume Rate of Change (VROC)
vroc = ta.roc(volume, length_14)
// 31. Price Volume Trend (PVT)
pvt = ta.pvt
// 32. Negative Volume Index (NVI)
nvi = 0.0
nvi := volume < volume ? nvi + ((close - close ) / close ) * nvi : nvi
// 33. Positive Volume Index (PVI)
pvi = 0.0
pvi := volume > volume ? pvi + ((close - close ) / close ) * pvi : pvi
// 34. Volume Oscillator
vol_osc = ta.sma(volume, 5) - ta.sma(volume, 10)
// 35. Ease of Movement (EOM)
eom_distance = high - low
eom_box_height = volume / 1000000
eom = eom_box_height != 0 ? eom_distance / eom_box_height : 0
eom_sma = ta.sma(eom, length_14)
// 36. Force Index
force_index = volume * (close - close )
force_index_sma = ta.sma(force_index, length_14)
// |----- VOLATILITY INDICATORS (10 indicators) -----| //
// 37. Average True Range (ATR)
atr = ta.atr(length_14)
atr_pct = (atr / close) * 100
// 38. Bollinger Bands Position
bb_basis = ta.sma(close, length_20)
bb_dev = 2.0 * ta.stdev(close, length_20)
bb_upper = bb_basis + bb_dev
bb_lower = bb_basis - bb_dev
bb_position = bb_dev != 0 ? (close - bb_basis) / bb_dev : 0
bb_width = bb_dev != 0 ? (bb_upper - bb_lower) / bb_basis * 100 : 0
// 39. Keltner Channels Position
kc_basis = ta.ema(close, length_20)
kc_range = ta.ema(ta.tr, length_20)
kc_upper = kc_basis + (2.0 * kc_range)
kc_lower = kc_basis - (2.0 * kc_range)
kc_position = kc_range != 0 ? (close - kc_basis) / kc_range : 0
// 40. Donchian Channels Position
dc_upper = ta.highest(high, length_20)
dc_lower = ta.lowest(low, length_20)
dc_basis = (dc_upper + dc_lower) / 2
dc_position = (dc_upper - dc_lower) != 0 ? (close - dc_basis) / (dc_upper - dc_lower) : 0
// 41. Standard Deviation
std_dev = ta.stdev(close, length_20)
std_dev_pct = (std_dev / close) * 100
// 42. Relative Volatility Index (RVI)
rvi_up = ta.stdev(close > close ? close : 0, length_14)
rvi_down = ta.stdev(close < close ? close : 0, length_14)
rvi_total = rvi_up + rvi_down
rvi_volatility = rvi_total != 0 ? (rvi_up / rvi_total) * 100 : 50
// 43. Historical Volatility
hv_returns = math.log(close / close )
hv = ta.stdev(hv_returns, length_20) * math.sqrt(252) * 100
// 44. Garman-Klass Volatility
gk_vol = math.log(high/low) * math.log(high/low) - (2*math.log(2)-1) * math.log(close/open) * math.log(close/open)
gk_volatility = math.sqrt(ta.sma(gk_vol, length_20)) * 100
// 45. Parkinson Volatility
park_vol = math.log(high/low) * math.log(high/low)
parkinson = math.sqrt(ta.sma(park_vol, length_20) / (4 * math.log(2))) * 100
// 46. Rogers-Satchell Volatility
rs_vol = math.log(high/close) * math.log(high/open) + math.log(low/close) * math.log(low/open)
rogers_satchell = math.sqrt(ta.sma(rs_vol, length_20)) * 100
// |----- OSCILLATOR INDICATORS (5 indicators) -----| //
// 47. Elder Ray Index
elder_bull = high - ta.ema(close, 13)
elder_bear = low - ta.ema(close, 13)
elder_power = elder_bull + elder_bear
// 48. Schaff Trend Cycle (STC)
stc_macd = ta.ema(close, 23) - ta.ema(close, 50)
stc_k = ta.stoch(stc_macd, stc_macd, stc_macd, 10)
stc_d = ta.ema(stc_k, 3)
stc = ta.stoch(stc_d, stc_d, stc_d, 10)
// 49. Coppock Curve
coppock_roc1 = ta.roc(close, 14)
coppock_roc2 = ta.roc(close, 11)
coppock = ta.wma(coppock_roc1 + coppock_roc2, 10)
// 50. Know Sure Thing (KST)
kst_roc1 = ta.roc(close, 10)
kst_roc2 = ta.roc(close, 15)
kst_roc3 = ta.roc(close, 20)
kst_roc4 = ta.roc(close, 30)
kst = ta.sma(kst_roc1, 10) + 2*ta.sma(kst_roc2, 10) + 3*ta.sma(kst_roc3, 10) + 4*ta.sma(kst_roc4, 15)
// 51. Percentage Price Oscillator (PPO)
ppo_line = ((ta.ema(close, 12) - ta.ema(close, 26)) / ta.ema(close, 26)) * 100
ppo_signal = ta.ema(ppo_line, 9)
ppo_histogram = ppo_line - ppo_signal
// |----- PLOT MAIN INDICATORS -----| //
// Plot key momentum indicators
plot(rsi_centered, title="01_RSI_Centered", color=color.purple, linewidth=1)
plot(stoch_centered, title="02_Stoch_Centered", color=color.blue, linewidth=1)
plot(williams_r, title="03_Williams_R", color=color.red, linewidth=1)
plot(macd_histogram, title="04_MACD_Histogram", color=color.orange, linewidth=1)
plot(cci, title="05_CCI", color=color.green, linewidth=1)
// Plot trend indicators
plot(sma_momentum, title="06_SMA_Momentum", color=color.navy, linewidth=1)
plot(ema_momentum, title="07_EMA_Momentum", color=color.maroon, linewidth=1)
plot(sar_trend, title="08_SAR_Trend", color=color.teal, linewidth=1)
plot(lr_slope, title="09_LR_Slope", color=color.lime, linewidth=1)
plot(mac, title="10_MAC", color=color.fuchsia, linewidth=1)
// Plot volatility indicators
plot(atr_pct, title="11_ATR_Pct", color=color.yellow, linewidth=1)
plot(bb_position, title="12_BB_Position", color=color.aqua, linewidth=1)
plot(kc_position, title="13_KC_Position", color=color.olive, linewidth=1)
plot(std_dev_pct, title="14_StdDev_Pct", color=color.silver, linewidth=1)
plot(bb_width, title="15_BB_Width", color=color.gray, linewidth=1)
// Plot volume indicators
plot(vroc, title="16_VROC", color=color.blue, linewidth=1)
plot(eom_sma, title="17_EOM", color=color.red, linewidth=1)
plot(vol_osc, title="18_Vol_Osc", color=color.green, linewidth=1)
plot(force_index_sma, title="19_Force_Index", color=color.orange, linewidth=1)
plot(obv, title="20_OBV", color=color.purple, linewidth=1)
// Plot additional oscillators
plot(ao, title="21_Awesome_Osc", color=color.navy, linewidth=1)
plot(cmo, title="22_CMO", color=color.maroon, linewidth=1)
plot(dpo, title="23_DPO", color=color.teal, linewidth=1)
plot(trix, title="24_TRIX", color=color.lime, linewidth=1)
plot(fisher, title="25_Fisher", color=color.fuchsia, linewidth=1)
// Plot more momentum indicators
plot(mfi_centered, title="26_MFI_Centered", color=color.yellow, linewidth=1)
plot(ac, title="27_AC", color=color.aqua, linewidth=1)
plot(ppo_pct, title="28_PPO_Pct", color=color.olive, linewidth=1)
plot(stoch_rsi_centered, title="29_StochRSI_Centered", color=color.silver, linewidth=1)
plot(klinger, title="30_Klinger", color=color.gray, linewidth=1)
// Plot trend continuation
plot(tii, title="31_TII", color=color.blue, linewidth=1)
plot(ichimoku_signal, title="32_Ichimoku_Signal", color=color.red, linewidth=1)
plot(mama_momentum, title="33_MAMA_Momentum", color=color.green, linewidth=1)
plot(zlema_momentum, title="34_ZLEMA_Momentum", color=color.orange, linewidth=1)
plot(bop, title="35_BOP", color=color.purple, linewidth=1)
// Plot volume continuation
plot(nvi, title="36_NVI", color=color.navy, linewidth=1)
plot(pvi, title="37_PVI", color=color.maroon, linewidth=1)
plot(momentum_pct, title="38_Momentum_Pct", color=color.teal, linewidth=1)
plot(roc, title="39_ROC", color=color.lime, linewidth=1)
plot(rvi, title="40_RVI", color=color.fuchsia, linewidth=1)
// Plot volatility continuation
plot(dc_position, title="41_DC_Position", color=color.yellow, linewidth=1)
plot(rvi_volatility, title="42_RVI_Volatility", color=color.aqua, linewidth=1)
plot(hv, title="43_Historical_Vol", color=color.olive, linewidth=1)
plot(gk_volatility, title="44_GK_Volatility", color=color.silver, linewidth=1)
plot(parkinson, title="45_Parkinson_Vol", color=color.gray, linewidth=1)
// Plot final oscillators
plot(rogers_satchell, title="46_RS_Volatility", color=color.blue, linewidth=1)
plot(elder_power, title="47_Elder_Power", color=color.red, linewidth=1)
plot(stc, title="48_STC", color=color.green, linewidth=1)
plot(coppock, title="49_Coppock", color=color.orange, linewidth=1)
plot(kst, title="50_KST", color=color.purple, linewidth=1)
// Plot final indicators
plot(ppo_histogram, title="51_PPO_Histogram", color=color.navy, linewidth=1)
plot(pvt, title="52_PVT", color=color.maroon, linewidth=1)
// |----- Reference Lines -----| //
hline(0, "Zero Line", color=color.gray, linestyle=hline.style_dashed, linewidth=1)
hline(50, "Midline", color=color.gray, linestyle=hline.style_dotted, linewidth=1)
hline(-50, "Lower Midline", color=color.gray, linestyle=hline.style_dotted, linewidth=1)
hline(25, "Upper Threshold", color=color.gray, linestyle=hline.style_dotted, linewidth=1)
hline(-25, "Lower Threshold", color=color.gray, linestyle=hline.style_dotted, linewidth=1)
// |----- Enhanced Information Table -----| //
if show_table and barstate.islast
table_position = position.top_right
table_text_size = table_size == "Tiny" ? size.tiny : table_size == "Small" ? size.small : size.normal
var table info_table = table.new(table_position, 3, 18, bgcolor=color.new(color.white, 85), border_width=1, border_color=color.gray)
// Headers
table.cell(info_table, 0, 0, 'Category', text_color=color.black, text_size=table_text_size, bgcolor=color.new(color.blue, 70))
table.cell(info_table, 1, 0, 'Indicator', text_color=color.black, text_size=table_text_size, bgcolor=color.new(color.blue, 70))
table.cell(info_table, 2, 0, 'Value', text_color=color.black, text_size=table_text_size, bgcolor=color.new(color.blue, 70))
// Key Momentum Indicators
table.cell(info_table, 0, 1, 'MOMENTUM', text_color=color.purple, text_size=table_text_size, bgcolor=color.new(color.purple, 90))
table.cell(info_table, 1, 1, 'RSI Centered', text_color=color.purple, text_size=table_text_size)
table.cell(info_table, 2, 1, str.tostring(rsi_centered, '0.00'), text_color=color.purple, text_size=table_text_size)
table.cell(info_table, 0, 2, '', text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 1, 2, 'Stoch Centered', text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 2, 2, str.tostring(stoch_centered, '0.00'), text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 0, 3, '', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 1, 3, 'Williams %R', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 2, 3, str.tostring(williams_r, '0.00'), text_color=color.red, text_size=table_text_size)
table.cell(info_table, 0, 4, '', text_color=color.orange, text_size=table_text_size)
table.cell(info_table, 1, 4, 'MACD Histogram', text_color=color.orange, text_size=table_text_size)
table.cell(info_table, 2, 4, str.tostring(macd_histogram, '0.000'), text_color=color.orange, text_size=table_text_size)
table.cell(info_table, 0, 5, '', text_color=color.green, text_size=table_text_size)
table.cell(info_table, 1, 5, 'CCI', text_color=color.green, text_size=table_text_size)
table.cell(info_table, 2, 5, str.tostring(cci, '0.00'), text_color=color.green, text_size=table_text_size)
// Key Trend Indicators
table.cell(info_table, 0, 6, 'TREND', text_color=color.navy, text_size=table_text_size, bgcolor=color.new(color.navy, 90))
table.cell(info_table, 1, 6, 'SMA Momentum %', text_color=color.navy, text_size=table_text_size)
table.cell(info_table, 2, 6, str.tostring(sma_momentum, '0.00'), text_color=color.navy, text_size=table_text_size)
table.cell(info_table, 0, 7, '', text_color=color.maroon, text_size=table_text_size)
table.cell(info_table, 1, 7, 'EMA Momentum %', text_color=color.maroon, text_size=table_text_size)
table.cell(info_table, 2, 7, str.tostring(ema_momentum, '0.00'), text_color=color.maroon, text_size=table_text_size)
table.cell(info_table, 0, 8, '', text_color=color.teal, text_size=table_text_size)
table.cell(info_table, 1, 8, 'SAR Trend', text_color=color.teal, text_size=table_text_size)
table.cell(info_table, 2, 8, str.tostring(sar_trend, '0'), text_color=color.teal, text_size=table_text_size)
table.cell(info_table, 0, 9, '', text_color=color.lime, text_size=table_text_size)
table.cell(info_table, 1, 9, 'Linear Regression', text_color=color.lime, text_size=table_text_size)
table.cell(info_table, 2, 9, str.tostring(lr_slope, '0.000'), text_color=color.lime, text_size=table_text_size)
// Key Volatility Indicators
table.cell(info_table, 0, 10, 'VOLATILITY', text_color=color.yellow, text_size=table_text_size, bgcolor=color.new(color.yellow, 90))
table.cell(info_table, 1, 10, 'ATR %', text_color=color.yellow, text_size=table_text_size)
table.cell(info_table, 2, 10, str.tostring(atr_pct, '0.00'), text_color=color.yellow, text_size=table_text_size)
table.cell(info_table, 0, 11, '', text_color=color.aqua, text_size=table_text_size)
table.cell(info_table, 1, 11, 'BB Position', text_color=color.aqua, text_size=table_text_size)
table.cell(info_table, 2, 11, str.tostring(bb_position, '0.00'), text_color=color.aqua, text_size=table_text_size)
table.cell(info_table, 0, 12, '', text_color=color.olive, text_size=table_text_size)
table.cell(info_table, 1, 12, 'KC Position', text_color=color.olive, text_size=table_text_size)
table.cell(info_table, 2, 12, str.tostring(kc_position, '0.00'), text_color=color.olive, text_size=table_text_size)
// Key Volume Indicators
table.cell(info_table, 0, 13, 'VOLUME', text_color=color.blue, text_size=table_text_size, bgcolor=color.new(color.blue, 90))
table.cell(info_table, 1, 13, 'Volume ROC', text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 2, 13, str.tostring(vroc, '0.00'), text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 0, 14, '', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 1, 14, 'EOM', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 2, 14, str.tostring(eom_sma, '0.000'), text_color=color.red, text_size=table_text_size)
// Key Oscillators
table.cell(info_table, 0, 15, 'OSCILLATORS', text_color=color.purple, text_size=table_text_size, bgcolor=color.new(color.purple, 90))
table.cell(info_table, 1, 15, 'Awesome Osc', text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 2, 15, str.tostring(ao, '0.000'), text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 0, 16, '', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 1, 16, 'Fisher Transform', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 2, 16, str.tostring(fisher, '0.000'), text_color=color.red, text_size=table_text_size)
// Summary Statistics
table.cell(info_table, 0, 17, 'SUMMARY', text_color=color.black, text_size=table_text_size, bgcolor=color.new(color.gray, 70))
table.cell(info_table, 1, 17, 'Total Indicators: 52', text_color=color.black, text_size=table_text_size)
regime_color = rsi_centered > 10 ? color.green : rsi_centered < -10 ? color.red : color.gray
regime_text = rsi_centered > 10 ? "BULLISH" : rsi_centered < -10 ? "BEARISH" : "NEUTRAL"
table.cell(info_table, 2, 17, regime_text, text_color=regime_color, text_size=table_text_size)
This makes it the perfect “indicator backbone” for quantitative and systematic traders who want to prototype, combine, and test new regime detection models—especially in combination with the Markov Chain indicator.
How to use this script with the Markov Chain for research and backtesting:
Add the Enhanced Indicator Export to your chart.
Every calculated indicator is available as an individual data stream.
Connect the indicator(s) you want as custom input(s) to the Markov Chain’s “Custom Indicators” option.
In the Markov Chain indicator’s settings, turn ON the custom indicator mode.
For each of the three custom indicator inputs, select the exported plot from the Enhanced Export script—the menu lists all 45+ signals by name.
This creates a powerful, modular regime-detection engine where you can mix-and-match momentum, trend, volume, or custom combinations for advanced filtering.
Backtest regime logic directly.
Once you’ve connected your chosen indicators, the Markov Chain script performs regime detection (Bull/Neutral/Bear) based on your selected features—not just price returns.
The regime detection is robust, automatically normalized (using Z-score), and outputs bias (1, -1, 0) for plug-and-play integration.
Export the regime bias for programmatic use.
As described above, use input.source() in your Pine Script strategy or system and link the bias output.
You can now filter signals, control trade direction/size, or design pairs-trading that respect true, indicator-driven market regimes.
With this framework, you’re not limited to static or simplistic regime filters. You can rigorously define, test, and refine what “market regime” means for your strategies—using the technical features that matter most to you.
Optimize your signal generation by backtesting across a universe of meaningful indicator blends.
Enhance risk management with objective, real-time regime boundaries.
Accelerate your research: iterate quickly, swap indicator components, and see results with minimal code changes.
Automate multi-asset or pairs-trading by integrating regime context directly into strategy logic.
Add both scripts to your chart, connect your preferred features, and start investigating your best regime-based trades—entirely within the TradingView ecosystem.
References & Further Reading
Ang, A., & Bekaert, G. (2002). “Regime Switches in Interest Rates.” Journal of Business & Economic Statistics, 20(2), 163–182.
Hamilton, J. D. (1989). “A New Approach to the Economic Analysis of Nonstationary Time Series and the Business Cycle.” Econometrica, 57(2), 357–384.
Markov, A. A. (1906). "Extension of the Limit Theorems of Probability Theory to a Sum of Variables Connected in a Chain." The Notes of the Imperial Academy of Sciences of St. Petersburg.
Guidolin, M., & Timmermann, A. (2007). “Asset Allocation under Multivariate Regime Switching.” Journal of Economic Dynamics and Control, 31(11), 3503–3544.
Murphy, J. J. (1999). Technical Analysis of the Financial Markets. New York Institute of Finance.
Brock, W., Lakonishok, J., & LeBaron, B. (1992). “Simple Technical Trading Rules and the Stochastic Properties of Stock Returns.” Journal of Finance, 47(5), 1731–1764.
Zucchini, W., MacDonald, I. L., & Langrock, R. (2017). Hidden Markov Models for Time Series: An Introduction Using R (2nd ed.). Chapman and Hall/CRC.
On Quantitative Finance and Markov Models:
Lo, A. W., & Hasanhodzic, J. (2009). The Heretics of Finance: Conversations with Leading Practitioners of Technical Analysis. Bloomberg Press.
Patterson, S. (2016). The Man Who Solved the Market: How Jim Simons Launched the Quant Revolution. Penguin Press.
TradingView Pine Script Documentation: www.tradingview.com
TradingView Blog: “Use an Input From Another Indicator With Your Strategy” www.tradingview.com
GeeksforGeeks: “What is the Difference Between Markov Chains and Hidden Markov Models?” www.geeksforgeeks.org
What makes this indicator original and unique?
- On‑chart, real‑time Markov. The chain is drawn directly on your chart. You see the current regime, its tendency to stay (self‑loop), and the usual next step (arrows) as bars confirm.
- Source‑agnostic by design. The engine runs on any series you select via input.source() — price, your own oscillator, a composite score, anything you compute in the script.
- Automatic normalization + regime mapping. Different inputs live on different scales. The script standardizes your chosen source and maps it into clear regimes (e.g., Bull / Bear / Neutral) without you micromanaging thresholds each time.
- Rolling, bar‑by‑bar learning. Transition tendencies are computed from a rolling window of confirmed bars. What you see is exactly what the market did in that window.
- Fast experimentation. Switch the source, adjust the window, and the Markov view updates instantly. It’s a rapid way to test ideas and feel regime persistence/switch behavior.
Integrate your own signals (using input.source())
- In settings, choose the Source . This is powered by input.source() .
- Feed it price, an indicator you compute inside the script, or a custom composite series.
- The script will automatically normalize that series and process it through the Markov engine, mapping it to regimes and updating the on‑chart spheres/arrows in real time.
Credits:
Deep gratitude to @RicardoSantos for both the foundational Markov chain processing engine and inspiring open-source contributions, which made advanced probabilistic market modeling accessible to the TradingView community.
Special thanks to @Alien_Algorithms for the innovative and visually stunning 3D sphere logic that powers the indicator’s animated, regime-based visualization.
Disclaimer
This tool summarizes recent behavior. It is not financial advice and not a guarantee of future results.
Lorentzian Classification Strategy Based in the model of Machine learning: Lorentzian Classification by @jdehorty, you will be able to get into trending moves and get interesting entries in the market with this strategy. I also put some new features for better backtesting results!
Backtesting context: 2022-07-19 to 2023-04-14 of US500 1H by PEPPERSTONE. Commissions: 0.03% for each entry, 0.03% for each exit. Risk per trade: 2.5% of the total account
For this strategy, 3 indicators are used:
Machine learning: Lorentzian Classification by @jdehorty
One Ema of 200 periods for identifying the trend
Supertrend indicator as a filter for some exits
Atr stop loss from Gatherio
Trade conditions:
For longs:
Close price is above 200 Ema
Lorentzian Classification indicates a buying signal
This gives us our long signal. Stop loss will be determined by atr stop loss (white point), break even(blue point) by a risk/reward ratio of 1:1 and take profit of 3:1 where half position will be closed. This will be showed as buy.
The other half will be closed when the model indicates a selling signal or Supertrend indicator gives a bearish signal. This will be showed as cl buy.
For shorts:
Close price is under 200 Ema
Lorentzian Classification indicates a selling signal
This gives us our short signal. Stop loss will be determined by atr stop loss (white point), break even(blue point) by a risk/reward ratio of 1:1 and take profit of 3:1 where half position will be closed. This will be showed as sell.
The other half will be closed when the model indicates a buying signal or Supertrend indicator gives a bullish signal. This will be showed as cl sell.
Risk management
To calculate the amount of the position you will use just a small percent of your initial capital for the strategy and you will use the atr stop loss or last swing for this.
Example: You have 1000 usd and you just want to risk 2,5% of your account, there is a buy signal at price of 4,000 usd. The stop loss price from atr stop loss or last swing is 3,900. You calculate the distance in percent between 4,000 and 3,900. In this case, that distance would be of 2.50%. Then, you calculate your position by this way: (initial or current capital * risk per trade of your account) / (stop loss distance).
Using these values on the formula: (1000*2,5%)/(2,5%) = 1000usd. It means, you have to use 1000 usd for risking 2.5% of your account.
We will use this risk management for applying compound interest.
> In settings, with position amount calculator, you can enter the amount in usd of your account and the amount in percentage for risking per trade of the account. You will see this value in green color in the upper left corner that shows the amount in usd to use for risking the specific percentage of your account.
> You can also choose a fixed amount, so you will have to activate fixed amount in risk management for trades and set the fixed amount for backtesting.
Script functions
Inside of settings, you will find some utilities for display atr stop loss, break evens, positions, signals, indicators, a table of some stats from backtesting, etc.
You will find the settings for risk management at the end of the script if you want to change something or trying new values for other assets for backtesting.
If you want to change the initial capital for backtest the strategy, go to properties, and also enter the commisions of your exchange and slippage for more realistic results.
In risk managment you can find an option called "Use leverage ?", activate this if you want to backtest using leverage, which means that in case of not having enough money for risking the % determined by you of your account using your initial capital, you will use leverage for using the enough amount for risking that % of your acount in a buy position. Otherwise, the amount will be limited by your initial/current capital
I also added a function for backtesting if you had added or withdrawn money frequently:
Adding money: You can choose how often you want to add money (Monthly, yearly, daily or weekly). Then a fixed amount of money and activate or deactivate this function
Withdraw money: You can choose if you want to withdraw a fixed amount or a percentage of earnings. Then you can choose a fixed amount of money, the period of time and activate or deactivate this function. Also, the percentage of earnings if you choosed this option.
Some other assets where strategy has worked
BTCUSD 4H, 1D
ETHUSD 4H, 1D
BNBUSD 4H
SPX 1D
BANKNIFTY 4H, 15 min
Some things to consider
USE UNDER YOUR OWN RISK. PAST RESULTS DO NOT REPRESENT THE FUTURE.
DEPENDING OF % ACCOUNT RISK PER TRADE, YOU COULD REQUIRE LEVERAGE FOR OPEN SOME POSITIONS, SO PLEASE, BE CAREFULL AND USE CORRECTLY THE RISK MANAGEMENT
Do not forget to change commissions and other parameters related with back testing results!. If you have problems loading the script reduce max bars back number in general settings
Strategies for trending markets use to have more looses than wins and it takes a long time to get profits, so do not forget to be patient and consistent !
Please, visit the post from @jdehorty called Machine Learning: Lorentzian Classification for a better understanding of his script!
Any support and boosts will be well received. If you have any question, do not doubt to ask!
Athena Momentum Squeeze - Short, Lean, and Mean This is a very profitable strategy focusing on 15 minute intervals on the Micro Nasdaq Futures contracts. CME_MINI:MNQH2023
As this contract only keeps positions for on average about an hour risk is managed. At a profit factor of 3.382 with a max drawdown of $123 from January 1st to February 15. Looking back to Dec 2019 still maintains a profit factor of 1.3.
See backtesting: www.screencast.com
2019 backtesting: www.screencast.com
Based on the classic Lazy Bear Oscillator Squeeze with a number of modifications from ADX, MAs and adding fibonacci levels.
We like keeping strategies simple yet powerful, no completely where you can't understand your own trades.
Our team is always modifying and improving the strategy. Always open to collaborating on improving as there is no perfect strategy. www.screencast.com
[Sextan] T-Step LSMA MTF BacktestLevel: 1
NOTE: This is a request by @scantor516 to backtest T-Step LSMA by alexgrover with my Sextan framework. You can backtest many of my indicators in minutes now! Of course,you can define your own indicator in the highlighted area in compliance with the uniform format, which guarantee when you use "Indicator on Indicator" function, it would not produce any error.
Courtesy of alexgrover for his T-Step LSMA
Background
Backtesting of technical indicators and strategies is the most common way to understand a quantitative strategy. However, the complicated configuration and adaptation work of backtesting many quantitative tools makes many traders who do not understand the code daunted. Moreover, although I have written a lot of strategies, I am still not very satisfied with the backtest configuration and writing efficiency. Therefore, I have been thinking about how to build a backtesting framework that can quickly and easily evaluate the backtesting performance of any indicator with a "long/short entry" indicator, that is, a "simple backtesting tool for dummies". The performance requirements should be stable, and the operation should be simple and convenient. It is best to "copy", "paste", and "a few mouse clicks" to complete the quick backtest and evaluation of a new indicator.
Luckily, I recently realized that TradingView provides an "Indicator on Indicator" feature, which is the perfect foundation for doing "hot swap" backtesting. My basic idea is to use a two-layer design. The first layer is the technical indicator signal source that needs to be embedded, which is only used to provide buy and sell signals of custom strategies; the second layer is the trading system, which is used to receive the output signals of the first layer, and filter the signals according to the agreed specifications. , Take Profit, Stop Loss, draw buy and sell signals and cost lines, define and send custom buy and sell alert messages to mobile phones, social software or trading interfaces. In general, this two-layer design is a flexible combination of "death and alive", which can meet the needs of most traders to quickly evaluate the performance of a certain technical indicator. The first layer here is flexible. Users can insert their own strategy codes according to my template, and they can draw buy and sell signals and output them to the second layer. The second layer is fixed, and the overall framework is solidified to ensure the stability and unity of the trading system. It is convenient to compare different or similar strategies under the same conditions. Finally, all trading signals are drawn on the chart, and the output strategy returns. test report.
The main function:
The first layer: "{Sextan} Your Indicator Source", the script provides a template for personalized strategy input, and the signal and definition interfaces ensure full compatibility with the second layer. Backtesting is performed stably in the backtesting framework of the layer. The first layer of this script is also relatively simple: enter your script in the highlighted custom script area, and after ensuring the final buy and sell signals long = bool condition, short = bool condition, the design of the first layer is considered complete. Input it into the PINE script editor of TradingView, save it and add it to the chart, you can see the pulse sequence in yellow (buy) and purple (sell) on the sub-picture, corresponding to the main picture, you can subjectively judge that the quality of the trading point of the strategy is good Bad.
The second layer: "{Sextan} PINEv4 Sextans Backtest Framework". This script is the standardized trading system strategy execution and alarm, used to generate the final report of the strategy backtest and some key indicators that I have customized that I find useful, such as: winning rate , Odds, Winning Surface, Kelly Ratio, Take Profit and Stop Loss Thresholds, Trading Frequency, etc. are evaluated according to the Kelly formula. To use the second layer, first load it into the TrainingView chart, no markers will appear on the chart, since you have not specified any strategy source signals, click on the gear-shaped setting next to the "{Sextan} PINEv4 Sextans BTFW" header button, you can open the backtest settings, the first item is to select your custom strategy source. Because we have added the strategy source to the chart in the previous step, you can easily find an option "{Sextan} Your Indicator Source: Signal" at the bottom of the list, this is the strategy source input we need, select and confirm , you can see various markers on the main graph, and quickly generate a backtesting profit graph and a list of backtesting reports. You can generate files and download the backtesting reports locally. You can also click the gear on the backtest chart interface to customize some conditions of the backtest, including: initial capital amount, currency type, percentage of each order placed, amount of pyramid additions, commission fees, slippage, etc. configuration. Note: The configuration in the interface dialog overrides the same configuration implemented by the code in the backtest script.
How to output charts:
The first layer: "{Sextan} Your Indicator Source", the output of this script is the pulse value of yellow and purple, yellow +1 means buy, purple -1 means sell.
The second layer: PINEv4 Sextans Backtest Framework". The output of this script is a bit complicated. After all, it is the entire trading system with a lot of information:
1. Blue and red arrows. The blue upward arrow indicates long position, the red downward arrow indicates short position, and the horizontal bar at the end of the purple arrow indicates take profit or stop loss exit.
2. Red and green lines. This is the holding cost line of the strategy, green represents the cost of holding a long position, and red represents the cost of holding a short position. The cost line is a continuous solid line and the price action is relatively close.
3. Green and yellow long take profit and stop loss area and green and yellow long take profit and stop loss fork. Once a long position is held, there is a conditional order for take profit and stop loss. The green horizontal line is the long take profit ratio line, and the yellow is the long stop loss ratio line; the green cross indicates the long take profit price, and the yellow cross indicates the long position. Stop loss price. It's worth noting that the prongs and wires don't necessarily go together. Because of the optimization of the algorithm, for a strong market, the take profit will occur after breaking the take profit line, and the profit will not be taken until the price falls.
4. The purple and red short take profit and stop loss area and the purple red short stop loss fork. Once a short position is held, there will be a take profit and stop loss conditional order, the red is the short take profit ratio line, and the purple is the short stop loss ratio line; the red cross indicates the short take profit price, and the purple cross indicates the short stop loss price.
5. In addition to the above signs, there are also text and numbers indicating the profit and loss values of long and short positions. "L" means long; "S" means short; "XL" means close long; "XS" means close short.
TradingView Strategy Tester Panel:
The overview graph is an intuitive graph that plots the blue (gain) and red (loss) curves of all backtest periods together, and notes: the absolute value and percentage of net profit, the number of all closed positions, the winning percentage, the profit factor, The maximum trading loss, the absolute value and ratio of the average trading profit and loss, and the average number of K-lines held in all trades.
Another is the performance summary. This is to display all long and short statistical indicators of backtesting in the form of a list, such as: net profit, gross profit, Sharpe ratio, maximum position, commission, times of profit and loss, etc.
Finally, the transaction list is a table indexed by the transaction serial number, showing the signal direction, date and time, price, profit and loss, accumulated profit and loss, maximum transaction profit, transaction loss and other values.
Remarks
Finally, I will explain that this is just the beginning of this model. I will continue to optimize the trading system of the second layer. Various optimization feedback and suggestions are welcome. For valuable feedback, I am willing to provide some L4/L5 technical indicators as rewards for free subscription rights.
[Sextan] %R Trend Exhaustion BacktestLevel: 1
NOTE: This is a request by @upslidedown to backtest %R Trend Exhaustion by upslidedown with my Sextan framework. You can backtest many of my indicators in minutes now! Of course,you can define your own indicator in the highlighted area in compliance with the uniform format, which guarantee when you use "Indicator on Indicator" function, it would not produce any error.
Courtesy of upslidedown for his %R Trend Exhaustionindicator
Background
Backtesting of technical indicators and strategies is the most common way to understand a quantitative strategy. However, the complicated configuration and adaptation work of backtesting many quantitative tools makes many traders who do not understand the code daunted. Moreover, although I have written a lot of strategies, I am still not very satisfied with the backtest configuration and writing efficiency. Therefore, I have been thinking about how to build a backtesting framework that can quickly and easily evaluate the backtesting performance of any indicator with a "long/short entry" indicator, that is, a "simple backtesting tool for dummies". The performance requirements should be stable, and the operation should be simple and convenient. It is best to "copy", "paste", and "a few mouse clicks" to complete the quick backtest and evaluation of a new indicator.
Luckily, I recently realized that TradingView provides an "Indicator on Indicator" feature, which is the perfect foundation for doing "hot swap" backtesting. My basic idea is to use a two-layer design. The first layer is the technical indicator signal source that needs to be embedded, which is only used to provide buy and sell signals of custom strategies; the second layer is the trading system, which is used to receive the output signals of the first layer, and filter the signals according to the agreed specifications. , Take Profit, Stop Loss, draw buy and sell signals and cost lines, define and send custom buy and sell alert messages to mobile phones, social software or trading interfaces. In general, this two-layer design is a flexible combination of "death and alive", which can meet the needs of most traders to quickly evaluate the performance of a certain technical indicator. The first layer here is flexible. Users can insert their own strategy codes according to my template, and they can draw buy and sell signals and output them to the second layer. The second layer is fixed, and the overall framework is solidified to ensure the stability and unity of the trading system. It is convenient to compare different or similar strategies under the same conditions. Finally, all trading signals are drawn on the chart, and the output strategy returns. test report.
The main function:
The first layer: "{Sextan} Your Indicator Source", the script provides a template for personalized strategy input, and the signal and definition interfaces ensure full compatibility with the second layer. Backtesting is performed stably in the backtesting framework of the layer. The first layer of this script is also relatively simple: enter your script in the highlighted custom script area, and after ensuring the final buy and sell signals long = bool condition, short = bool condition, the design of the first layer is considered complete. Input it into the PINE script editor of TradingView, save it and add it to the chart, you can see the pulse sequence in yellow (buy) and purple (sell) on the sub-picture, corresponding to the main picture, you can subjectively judge that the quality of the trading point of the strategy is good Bad.
The second layer: "{Sextan} PINEv4 Sextans Backtest Framework". This script is the standardized trading system strategy execution and alarm, used to generate the final report of the strategy backtest and some key indicators that I have customized that I find useful, such as: winning rate , Odds, Winning Surface, Kelly Ratio, Take Profit and Stop Loss Thresholds, Trading Frequency, etc. are evaluated according to the Kelly formula. To use the second layer, first load it into the TrainingView chart, no markers will appear on the chart, since you have not specified any strategy source signals, click on the gear-shaped setting next to the "{Sextan} PINEv4 Sextans BTFW" header button, you can open the backtest settings, the first item is to select your custom strategy source. Because we have added the strategy source to the chart in the previous step, you can easily find an option "{Sextan} Your Indicator Source: Signal" at the bottom of the list, this is the strategy source input we need, select and confirm , you can see various markers on the main graph, and quickly generate a backtesting profit graph and a list of backtesting reports. You can generate files and download the backtesting reports locally. You can also click the gear on the backtest chart interface to customize some conditions of the backtest, including: initial capital amount, currency type, percentage of each order placed, amount of pyramid additions, commission fees, slippage, etc. configuration. Note: The configuration in the interface dialog overrides the same configuration implemented by the code in the backtest script.
How to output charts:
The first layer: "{Sextan} Your Indicator Source", the output of this script is the pulse value of yellow and purple, yellow +1 means buy, purple -1 means sell.
The second layer: PINEv4 Sextans Backtest Framework". The output of this script is a bit complicated. After all, it is the entire trading system with a lot of information:
1. Blue and red arrows. The blue upward arrow indicates long position, the red downward arrow indicates short position, and the horizontal bar at the end of the purple arrow indicates take profit or stop loss exit.
2. Red and green lines. This is the holding cost line of the strategy, green represents the cost of holding a long position, and red represents the cost of holding a short position. The cost line is a continuous solid line and the price action is relatively close.
3. Green and yellow long take profit and stop loss area and green and yellow long take profit and stop loss fork. Once a long position is held, there is a conditional order for take profit and stop loss. The green horizontal line is the long take profit ratio line, and the yellow is the long stop loss ratio line; the green cross indicates the long take profit price, and the yellow cross indicates the long position. Stop loss price. It's worth noting that the prongs and wires don't necessarily go together. Because of the optimization of the algorithm, for a strong market, the take profit will occur after breaking the take profit line, and the profit will not be taken until the price falls.
4. The purple and red short take profit and stop loss area and the purple red short stop loss fork. Once a short position is held, there will be a take profit and stop loss conditional order, the red is the short take profit ratio line, and the purple is the short stop loss ratio line; the red cross indicates the short take profit price, and the purple cross indicates the short stop loss price.
5. In addition to the above signs, there are also text and numbers indicating the profit and loss values of long and short positions. "L" means long; "S" means short; "XL" means close long; "XS" means close short.
TradingView Strategy Tester Panel:
The overview graph is an intuitive graph that plots the blue (gain) and red (loss) curves of all backtest periods together, and notes: the absolute value and percentage of net profit, the number of all closed positions, the winning percentage, the profit factor, The maximum trading loss, the absolute value and ratio of the average trading profit and loss, and the average number of K-lines held in all trades.
Another is the performance summary. This is to display all long and short statistical indicators of backtesting in the form of a list, such as: net profit, gross profit, Sharpe ratio, maximum position, commission, times of profit and loss, etc.
Finally, the transaction list is a table indexed by the transaction serial number, showing the signal direction, date and time, price, profit and loss, accumulated profit and loss, maximum transaction profit, transaction loss and other values.
Remarks
Finally, I will explain that this is just the beginning of this model. I will continue to optimize the trading system of the second layer. Various optimization feedback and suggestions are welcome. For valuable feedback, I am willing to provide some L4/L5 technical indicators as rewards for free subscription rights.
[Sextan] Your Indicator Source PINE v5 MTFLevel: 1
NOTE1: As requested, this is a multiple time frame(MTF) version of input signal source, which enable you to backtest any indicator/strategy MTF with "{Sextan} PINEv4 Sextans Backtest Framework". Courtesy of cheatcountry for his request.security() wrapper in PINE v5 to avoid repainting caused by request.security() function.
NOTE2: Many request this indicator template to support PINE v5. Now, here it is .This is ONLY an PINE v5 EXAMPLE on HOW-TO produce a customized "{Sextan} PINEv4 Sextans Backtest Framework" (for bactest framework it does not need to be written by PINE v5)intput signal source, you can define your own indicator in the highlighted area in compliance with the uniform format, which guarantee when you use "Indicator on Indicator" function, it would not produce any error.
I use two simple moving average crossings to produce long and short entry signal with SMA3 and SMA8 in the example.
Background
Backtesting of technical indicators and strategies is the most common way to understand a quantitative strategy. However, the complicated configuration and adaptation work of backtesting many quantitative tools makes many traders who do not understand the code daunted. Moreover, although I have written a lot of strategies, I am still not very satisfied with the backtest configuration and writing efficiency. Therefore, I have been thinking about how to build a backtesting framework that can quickly and easily evaluate the backtesting performance of any indicator with a "long/short entry" indicator, that is, a "simple backtesting tool for dummies". The performance requirements should be stable, and the operation should be simple and convenient. It is best to "copy", "paste", and "a few mouse clicks" to complete the quick backtest and evaluation of a new indicator.
Luckily, I recently realized that TradingView provides an "Indicator on Indicator" feature, which is the perfect foundation for doing "hot swap" backtesting. My basic idea is to use a two-layer design. The first layer is the technical indicator signal source that needs to be embedded, which is only used to provide buy and sell signals of custom strategies; the second layer is the trading system, which is used to receive the output signals of the first layer, and filter the signals according to the agreed specifications. , Take Profit, Stop Loss, draw buy and sell signals and cost lines, define and send custom buy and sell alert messages to mobile phones, social software or trading interfaces. In general, this two-layer design is a flexible combination of "death and alive", which can meet the needs of most traders to quickly evaluate the performance of a certain technical indicator. The first layer here is flexible. Users can insert their own strategy codes according to my template, and they can draw buy and sell signals and output them to the second layer. The second layer is fixed, and the overall framework is solidified to ensure the stability and unity of the trading system. It is convenient to compare different or similar strategies under the same conditions. Finally, all trading signals are drawn on the chart, and the output strategy returns. test report.
The main function:
The first layer: "{Sextan} Your Indicator Source", the script provides a template for personalized strategy input, and the signal and definition interfaces ensure full compatibility with the second layer. Backtesting is performed stably in the backtesting framework of the layer. The first layer of this script is also relatively simple: enter your script in the highlighted custom script area, and after ensuring the final buy and sell signals long = bool condition, short = bool condition, the design of the first layer is considered complete. Input it into the PINE script editor of TradingView, save it and add it to the chart, you can see the pulse sequence in yellow (buy) and purple (sell) on the sub-picture, corresponding to the main picture, you can subjectively judge that the quality of the trading point of the strategy is good Bad.
The second layer: "{Sextan} PINEv4 Sextans Backtest Framework". This script is the standardized trading system strategy execution and alarm, used to generate the final report of the strategy backtest and some key indicators that I have customized that I find useful, such as: winning rate , Odds, Winning Surface, Kelly Ratio, Take Profit and Stop Loss Thresholds, Trading Frequency, etc. are evaluated according to the Kelly formula. To use the second layer, first load it into the TrainingView chart, no markers will appear on the chart, since you have not specified any strategy source signals, click on the gear-shaped setting next to the "{Sextan} PINEv4 Sextans BTFW" header button, you can open the backtest settings, the first item is to select your custom strategy source. Because we have added the strategy source to the chart in the previous step, you can easily find an option "{Sextan} Your Indicator Source: Signal" at the bottom of the list, this is the strategy source input we need, select and confirm , you can see various markers on the main graph, and quickly generate a backtesting profit graph and a list of backtesting reports. You can generate files and download the backtesting reports locally. You can also click the gear on the backtest chart interface to customize some conditions of the backtest, including: initial capital amount, currency type, percentage of each order placed, amount of pyramid additions, commission fees, slippage, etc. configuration. Note: The configuration in the interface dialog overrides the same configuration implemented by the code in the backtest script.
How to output charts:
The first layer: "{Sextan} Your Indicator Source", the output of this script is the pulse value of yellow and purple, yellow +1 means buy, purple -1 means sell.
The second layer: PINEv4 Sextans Backtest Framework". The output of this script is a bit complicated. After all, it is the entire trading system with a lot of information:
1. Blue and red arrows. The blue upward arrow indicates long position, the red downward arrow indicates short position, and the horizontal bar at the end of the purple arrow indicates take profit or stop loss exit.
2. Red and green lines. This is the holding cost line of the strategy, green represents the cost of holding a long position, and red represents the cost of holding a short position. The cost line is a continuous solid line and the price action is relatively close.
3. Green and yellow long take profit and stop loss area and green and yellow long take profit and stop loss fork. Once a long position is held, there is a conditional order for take profit and stop loss. The green horizontal line is the long take profit ratio line, and the yellow is the long stop loss ratio line; the green cross indicates the long take profit price, and the yellow cross indicates the long position. Stop loss price. It's worth noting that the prongs and wires don't necessarily go together. Because of the optimization of the algorithm, for a strong market, the take profit will occur after breaking the take profit line, and the profit will not be taken until the price falls.
4. The purple and red short take profit and stop loss area and the purple red short stop loss fork. Once a short position is held, there will be a take profit and stop loss conditional order, the red is the short take profit ratio line, and the purple is the short stop loss ratio line; the red cross indicates the short take profit price, and the purple cross indicates the short stop loss price.
5. In addition to the above signs, there are also text and numbers indicating the profit and loss values of long and short positions. "L" means long; "S" means short; "XL" means close long; "XS" means close short.
TradingView Strategy Tester Panel:
The overview graph is an intuitive graph that plots the blue (gain) and red (loss) curves of all backtest periods together, and notes: the absolute value and percentage of net profit, the number of all closed positions, the winning percentage, the profit factor, The maximum trading loss, the absolute value and ratio of the average trading profit and loss, and the average number of K-lines held in all trades.
Another is the performance summary. This is to display all long and short statistical indicators of backtesting in the form of a list, such as: net profit, gross profit, Sharpe ratio, maximum position, commission, times of profit and loss, etc.
Finally, the transaction list is a table indexed by the transaction serial number, showing the signal direction, date and time, price, profit and loss, accumulated profit and loss, maximum transaction profit, transaction loss and other values.
Remarks
Finally, I will explain that this is just the beginning of this model. I will continue to optimize the trading system of the second layer. Various optimization feedback and suggestions are welcome. For valuable feedback, I am willing to provide some L4/L5 technical indicators as rewards for free subscription rights.






















