Pine Script® ストラテジー
インジケーターとストラテジー
VANTYX Scalper Bot DR ABIRAM SIVPRASADVANTYX Scalper Bot – Trend & Momentum System
Strategy Overview
VANTYX™ Scalper Bot is a high-precision algorithmic trading strategy designed for Crypto & Forex scalping. It combines multi-timeframe trend analysis with momentum validation to filter out noise and capture high-probability moves.
This specific version includes a "Reversal Fix" engine, meaning it auto-corrects bias: if a Long condition is met while a Short is active, it immediately closes the Short and flips Long (and vice versa), ensuring you are always on the right side of the immediate trend.
Core Technology & Indicators
This strategy does not rely on a single indicator. Instead, it uses a "Confluence Engine" requiring 4 layers of confirmation before taking a trade:
1. Half Trend (Primary Signal)
Acts as the immediate trigger for entry.
Uses a proprietary amplitude algorithm to detect valid trend shifts while ignoring minor chop.
Bullish: Price breaks above the Half Trend channel.
Bearish: Price breaks below the Half Trend channel.
2. Multi-Timeframe (MTF) ADX & DMI
Momentum Filter: The strategy checks the ADX (Average Directional Index) on a higher timeframe (default: 15m) to ensure the trend has real strength.
Threshold: Trades are only taken if ADX > 23 (configurable), preventing entries during dead/ranging markets.
Non-Repainting: Uses strict "bar merge" logic to ensure backtest results match live performance.
3. MTF EMA Trend Filter
The "Big Trend" Guardrail: Checks a higher timeframe EMA (default: 200 EMA on 1H) to define the macro bias.
Rule: The bot will ONLY Long if price is above the MTF EMA, and ONLY Short if price is below it. This prevents "catching falling knives."
4. Volume Validation
Fakeout Prevention: Checks if the current volume is above the Volume Moving Average (20-period).
Logic: Volume must confirm price action. Low-volume breakouts are ignored.
Risk Management (VANTYX AI Logic)
The bot features a dynamic, ATR-based risk engine that adapts to market volatility:
Dynamic Stop Loss: Hard Stop is calculated using ATR (default 1.5x). In volatile markets, the stop widens; in quiet markets, it tightens.
Take Profit: Fixed ATR-based target (default 3.0x).
Trailing Stop (Ratchet System): Once in profit, a Trailing Stop activates.
For Longs: The stop only moves UP.
For Shorts: The stop only moves DOWN.
This locks in profits during strong impulsive moves.
⚙️How to Use & Best Settings
Recommended Timeframe: 1 minute - 5 minutes (for Scalping).
Asset Class: Crypto Perpetuals (BTC, ETH, SOL) or Major Forex Pairs.
Default Settings:
ADX TF: 15 Minutes
EMA TF: 60 Minutes
Risk: 1.5x SL / 3.0x TP / 2.0x Trail
Customization: All parameters (Amplitude, EMA lengths, ATR multipliers) are fully adjustable in the settings menu.
Alert Setup
This strategy is fully Alert-Ready for automation (3Commas, PineConnector, etc.).
Add to Chart.
Create Alert -> Select "VANTYX Scalper Bot".
IMPORTANT: Select "Order Fills Only" in the action settings.
The bot will output "LONG ENTRY", "EXIT LONG", etc., dynamically.
Disclaimer
This script is for educational and backtesting purposes only. Past performance does not guarantee future results. Please manage your risk responsibly and test on a demo account before live trading.
Trade Safe. Trade Smart.
~ Dr. Abhiram SS
Pine Script® ストラテジー
Strategy: Institutional Liquidity Engin💎 Institutional Liquidity Engine
Introducing the flagship update to our trading system, engineered at the intersection of statistical analysis and market gravity models. Version 25.2 isn't just a strategy—it’s a comprehensive engine designed to hunt and execute based on institutional liquidity.
🧠 What’s New in v25.2?
Unlike traditional indicators, this engine analyzes the market as a physical system where liquidity levels possess "mass" and "attraction."
Core Technology Modules:
Gravity Model 2.0 🧲 — The system calculates a dynamic Gravity Ratio. When price is squeezed between large order blocks, the algorithm determines which side has the strongest "magnetism," applying a Decay Constant to age out stale levels.
HTF Context Bias 🌐 — A built-in High-Timeframe (H1) filter. The system blocks shorts during strong bullish hourly closes and vice versa, preventing you from trading against the primary institutional flow.
Adaptive Z-Score Normalization 📊 — Every "sweep" (liquidity grab) undergoes a statistical stress test. A signal is only generated when the Confidence Level exceeds 70%, based on volume anomalies and volatility expansion.
Shutterstock
Открыть
Cause Model 2.0 🏗️ — Based on the law of "Cause and Effect." The algorithm measures the quality of consolidation (compression). The longer the market builds a "Cause," the more ambitious the Take Profit targets become.
🛡 Risk Management & Execution
The system features a Dynamic Risk Scaling module. Position size is never static—it adaptively increases when signals align with the HTF trend and gravity bias, and scales down during "choppy" market regimes.
Anti-Chop Logic: Automatically blocks entries in the middle of a range when ADX is low.
Automatic Scale-out: Locks in 50% profit at the first target to move the trade to Breakeven.
ML Feature Export: Every trade generates a high-dimensional data vector (Z-Score, Confidence, Gravity Ratio, Vol Ratio) ready for neural network training.
📋 Specifications:
Platform: Pine Script v5 (TradingView)
Type: Mean Reversion / Momentum Continuation (on Sweeps)
Assets: Futures, Crypto, FX (Optimized for high-volatility instruments)
Timeframe: M5 execution with H1 context analysis
Summary: This is a professional-grade workspace for traders who want to move beyond "indicators" and trade the underlying logic of liquidity and statistical anomalies.
#TradingView #PineScript #SmartMoney #LiquidityEngine #AlgoTrading #QuantitativeTrading #MachineLearning #FinTech
Pine Script® ストラテジー
Swing Strategy Feature Set W [theEccentricTrader]█ OVERVIEW
This swing strategy is part of a broader research and exploration framework designed to encourage users to experiment with a variety of technical concepts and evaluate the comparative effectiveness of different strategy configurations. For example, users can first configure a core strategy as a benchmark, then iteratively test a range of feature configurations as additional entry conditions and compare their performance against one another and against the core strategy.
Feature Set W includes concepts beginning with the letter "W" and forms part of a larger swing strategy suite that covers a wide range of technical concepts. The objective of the suite is not curve-fitting, but rather structured experimentation, exploration and statistical validation (or invalidation) of technical concepts.
Concepts exclusive to the feature set are as follows:
Wave Period Oscillator
Williams Accumulation/Distribution
Williams Variable Accumulation/Distribution
Williams Fractal
Williams Percent Range
█ OPERATIONAL
Initial Capital
The initial capital is defined as a monetary value denominated in a given base currency.
The default initial capital is set to 100,000.
The default base currency is set to the selected symbol's default base currency.
Users can adjust the initial capital and select an alternative base currency via strategy Settings/Properties.
Risk as Percentage of Equity
The equity is defined as the sum of initial capital, net profit and open profit.
The risk is defined as a percentage of equity per-trade. As a result, net profit outcomes are subject to compounding effects over time.
The default risk is set to 1% of equity.
Users can adjust the strategy's per-trade risk via strategy Settings/Inputs/STRATEGY.
For further information on how the risk is applied in practice, refer to the position sizing section below.
Unit of Value
The unit of value is defined as a decimal precision factor that converts user-defined point or pip distances into actual price units used by the selected symbol.
Different symbols express price movement using different conventions. For example, some symbols are quoted directly in whole price points, while others use pips or fractional point increments. The unit of value provides a normalisation layer that allows all distance-based logic in the strategy to operate consistently across symbols.
Examples:
A unit of value of 1 corresponds to a price increment of 1.0.
A unit of value of 10 corresponds to a price increment of 0.1.
A unit of value of 100 corresponds to a price increment of 0.01.
A unit of value of 1000 corresponds to a price increment of 0.001.
A unit of value of 10000 corresponds to a price increment of 0.0001.
Users should consult their broker’s published symbol specifications to confirm how price movement is defined for the symbols they intend to backtest. Incorrect configuration of the unit of value may result in misaligned stop distances, targets and/or risk calculations.
The default unit of value is set to 1.
Users can adjust the unit of value via strategy Settings/Inputs/STRATEGY.
Stop Buffer
The stop buffer is defined as the number of points or pips beyond a stop loss level required for the level to be considered clearly breached.
The default stop buffer is set to 0 points/pips.
Users can adjust the stop buffer via strategy Settings/Inputs/STRATEGY.
Risk Range
The risk range is defined as the difference between the entry price and the stop loss price (inclusive of the stop buffer) for any given trade.
Position Sizing
Position sizing determines the quantity of contracts, shares or units opened for each trade based on the user-defined risk and the selected symbol’s pricing structure.
"syminfo.pointvalue" is a built-in Pine Script variable that defines the number of underlying units contained within a single contract for any given symbol, and is critical for accurate position size calculations.
The position size is calculated as follows:
The risk range is multiplied by the syminfo.pointvalue to convert the price movement into its monetary equivalent.
The user-defined risk amount (expressed as a percentage of equity) is divided by this monetary risk per unit to determine the position size.
This ensures that each trade risks a consistent proportion of account equity regardless of point or pip based quoting conventions, symbol price scale or contract specifications.
While the strategy targets a fixed percentage of equity risk per-trade, the exact risk applied cannot always be matched precisely due to symbol-specific constraints such as contract sizing and margin requirements. In these cases, the strategy opens the largest permissible position that does not violate operational constraints, resulting in a realised risk that is as close as possible to the user-defined risk without exceeding it.
For further information on the syminfo.pointvalue variable, please refer to:
www.tradingview.com
Margin
The margin is defined as the minimum percentage of a position’s notional value that must be covered by the strategy’s available equity in order for TradingView's strategy tester to simulate opening and maintaining that position. For example, a margin setting of 25% means the simulated account must hold equity equal to at least 25% of the position’s notional value in order to enter or maintain that trade, the remaining 75% is considered provided by the simulated broker.
A lower margin percentage allows the account to open larger positions relative to its equity, because the required equity portion is smaller. Conversely, a higher margin percentage demands more of the account's equity be committed to any given position.
When the account’s equity falls below the required margin, the strategy tester emulates a margin call event, in which the broker emulator forcibly closes or reduces positions so that remaining positions no longer exceed available equity relative to the margin requirement. This behaviour is documented as part of TradingView’s margin/leverage feature for strategies.
Margin settings in a strategy are used solely for simulation purposes and do not automatically match any broker’s real-world margin requirements (which can vary by broker, asset class and symbol). Users should consult their broker’s published specifications for further details.
The default margin is set to 25% for both long and short positions.
Users can adjust the margin for long and short positions independently via strategy Settings/Properties/MARGIN.
For further information on the strategy tester's margin functionality, please refer to:
www.tradingview.com
www.tradingview.com
Pyramiding
The pyramiding count is defined as the maximum number of open positions permitted at any one time. TradingView's strategy tester does not facilitate hedging, as such, long entries will close any open short positions and short entries will close any open long positions.
The default pyramiding count is set to 100.
Users can adjust the pyramiding count via strategy Settings/Properties.
For further information on TradingView's strategy tester and broker emulator, please refer to:
www.tradingview.com
Spread
The spread is defined as the difference between a given symbol's bid (buy) price and ask (sell) price.
Typical spreads vary by broker and symbol. Some brokers offer fixed spreads on certain symbols, while others offer variable spreads that fluctuate with market conditions. Users should consult their broker's published specifications for further details.
Commission
The commission is defined as a transaction cost applied by a broker and may be expressed as a percentage of position size, a per-contract fee or a fixed fee per-transaction.
Commission structures vary by broker and symbol. Some brokers charge no explicit commission and instead generate revenue through the spread or other indirect sources, while others will typically apply one of the three aforementioned commission types, depending on the product offered. Users should consult their broker's published specifications for further details.
The default commission is set to 0.005% of position size.
Users can select and adjust the commission type via strategy Settings/Properties/COST SIMULATION.
█ CORE STRATEGY
Green and Red Candles
A green candle is defined as a candle that closes at or above its open price and a red candle is defined as a candle that closes below its open price.
Swing Highs and Swing Lows
A swing high is defined as a green candle, or a series of consecutive green candles, followed by a single red candle that completes the swing and forms the peak.
A swing low is defined as a red candle, or a series of consecutive red candles, followed by a single green candle that completes the swing and forms the trough.
Peak and Trough Prices
The peak price of a complete swing high is either the high of the red candle that completes the swing high or the high of the preceding green candle, depending on which is higher.
The trough price of a complete swing low is either the low of the green candle that completes the swing low or the low of the preceding red candle, depending on which is lower.
Fixed Reward-to-Risk
Fixed reward-to-risk is defined as a user-defined reward multiple for a given unit of risk.
Variable Reward-to-Risk
Variable reward-to-risk is defined as a path-dependent reward multiple for a given unit of risk.
Swing High Swing Low (SHSL) Strategy
The SHSL strategy uses swing lows for core long entry conditions and swing highs for core short entry conditions. The strategy is designed for standard OHLC candlestick charts only and will not behave as intended on other chart types.
All entries are processed at candle close and use the candle close price for the entry price.
Long stop losses are anchored to the most recent trough and short stop losses are anchored to the most recent peak.
Users can choose between long-only and short-only configurations, or alternatively simulate trades in both directions (long-short). However, when the "Both" option is selected, long entries will close any open short positions and short entries will close any open long positions (as mentioned in the pyramiding sub-section above). This can and will result in variable reward-to-risk outcomes.
The default direction is set to "Long" for a long-only configuration.
The default exit type is set to "Target" for a fixed reward-to-risk configuration.
Long targets are determined by adding a user-defined multiple of the risk range to the entry price and short targets are determined by subtracting a user-defined multiple of the risk range from the entry price.
Even when using a fixed reward-to-risk configuration, realised reward-to-risk outcomes may vary due to market gaps, particularly when positions are held across session boundaries or market closures. Gaps can cause stop losses or exits to be executed at prices materially different from those implied by the strategy’s static distance calculations. Users who wish to minimise gap-related variability may consider applying the close at end of session filter (see core filters section below), accepting that this introduces its own form of reward-to-risk variability.
The default reward-to-risk is set to 1.
Users can adjust strategy parameters via strategy Settings/Inputs/STRATEGY. Selecting a non-target exit type removes profit targets and renders the reward-to-risk input inactive.
Trailing Stop Loss
A trailing stop loss is defined as an exit type that dynamically moves a stop loss level in a favourable direction when a predefined condition is met. For example, a predefined point move or the formation of a higher trough or lower peak.
Risk Range Trailing Stop Loss
The risk range trailing stop loss is defined as a trailing stop mechanism that activates once price has moved favourably by one full risk range. Upon activation, the stop loss is moved to breakeven and subsequently trails favourable price movement by the risk range into profit.
Users can apply this exit type by selecting "Trail" via strategy Settings/Inputs/STRATEGY.
Trend Trailing Stop Loss
The trend trailing stop loss is defined as a trailing stop mechanism that dynamically moves a stop loss level to newly formed higher troughs (for longs) or lower peaks (for shorts).
Users can apply this exit type by selecting "Trend Trail" via strategy Settings/Inputs/STRATEGY.
Candle Trailing Stop Loss
The candle trailing stop loss is defined as a trailing stop mechanism that dynamically moves a stop loss level to newly formed higher candle lows (for longs) or lower candle highs (for shorts).
Users can apply this exit type by selecting "Candle Trail" via strategy Settings/Inputs/STRATEGY.
Opposing Candle Colour Close
The opposing candle colour close exit type is defined as an exit condition that closes any long positions when a new red candle forms and closes any short positions when a new green candle forms.
Users can apply this exit type by selecting "Opposing Candle" via strategy Settings/Inputs/STRATEGY.
█ CORE FILTERS
Minimum Risk Range Filter
The minimum risk range filter is defined as an entry filter that invalidates trade signals with a risk range below a user-defined threshold.
The default minimum risk range is set to 4 points/pips.
Users can adjust the minimum risk range via strategy Settings/Inputs/RISK RANGE FILTER.
It is recommended that users set the minimum risk range at least 1–2 points/pips above the selected symbol’s spread to invalidate trades that would be completely impractical under realistic trading conditions.
Time Zone
The time zone is defined using either an IANA region identifier (e.g. Europe/London, America/New_York) or a fixed UTC/GMT offset (e.g. UTC+1, GMT-05:30). Fixed offsets do not account for daylight saving time.
The default time zone is set to Europe/London.
Users can change the time zone via strategy Settings/Inputs/TIME ZONE.
For further information on time zone configuration, please refer to:
data.iana.org
en.wikipedia.org
Session Filter
The session filter is defined as an entry filter that invalidates trade signals that fall outside a user-defined intraday trading session, with session start and end times bound to the strategy time zone.
TradingView candle timestamps represent the candle open time, not the candle close time. As a result, session boundaries are evaluated based on when a candle opens, even though entries and exits are processed at candle close.
To avoid trades being entered or held beyond the intended session end, users should configure the session end time at least one full timeframe period earlier than the desired practical session close. For example, on a 5-minute chart with a desired session end at 22:00, the session should typically be configured to end at 21:55. This ensures that no new trades are taken at the final session close and that any session-dependent exit logic is applied before the session ends in practice.
When using custom or non-standard timeframes where the desired session end does not align cleanly with candle boundaries, it is recommended that users set the session end two full timeframe periods earlier than the desired session end. This provides an additional safety buffer, ensuring the strategy avoids taking trades near the session boundary.
By default, the session filter is set to false and the default session is set to "2300-2155".
Users can apply the session filter and adjust session boundaries via strategy Settings/Inputs/SESSION FILTER.
Close At End of Session Filter
The close at end of session filter is defined as an exit filter that closes all open positions when the active trading session ends, provided that the session filter is appropriately configured and applied.
When enabled, the strategy monitors the session filter state and detects the transition from an active session to an inactive session. All open trades are closed on the first candle that falls outside the defined session window. This ensures that no positions are carried beyond the user-defined trading session.
The close at end of session filter operates independently of entry conditions and other exit types. When enabled, it will force the closure of all open positions at session end regardless of the selected exit configuration.
Enabling the close at end of session filter can result in variable reward-to-risk outcomes. Because positions are forcibly closed at session end regardless of stop loss or target placement, exits may occur at prices that differ from those implied by the fixed reward-to-risk configuration. This behaviour is intentional and reflects a design trade-off between enforcing strict session boundaries and allowing trades to reach their predefined directional objectives, regardless of how severely distorted the realised reward-to-risk outcomes could be in the event of price gaps.
By default, the close at end of session filter is set to false.
Users can apply the close at end of session filter via strategy Settings/Inputs/CLOSE AT END OF SESSION FILTER.
Users should also ensure that the session filter is applied and that session boundaries are configured appropriately with respect to candle timestamp behaviour, as described in the session filter section above.
Sample Period Filter
The sample period filter is defined as an entry filter that invalidates trade signals that fall outside a user-defined date-time range, with start and end date-times bound to the strategy time zone.
TradingView candle timestamps represent the candle open time, not the candle close time. As a result, sample period boundaries are evaluated based on when a candle opens, even though entries and exits are processed at candle close.
To avoid trades being entered beyond the intended sample period end, users should configure the sample period end date-time at least one full timeframe period earlier than the desired practical sample period end date-time. For example, on a 5-minute chart with a desired end date-time of 01/01/2026 22:00, the end date-time should typically be configured to 01/01/2026 21:55.
The default sample period start and end date-times are set to 01/01/1900 00:00 and 01/01/3000 00:00, respectively.
Users can adjust the sample period via strategy Settings/Inputs/SAMPLE PERIOD FILTER.
█ GENERIC FILTERS
Generic Filter Behaviour
Unless otherwise stated:
"None" inputs return true.
Filters return true only when their selected condition is satisfied.
Minimum and Maximum Boundary Filters
Minimum and maximum boundary filters are defined as entry filters used to constrain time-series values to predefined minimum and/or maximum thresholds, invalidating trade signals that do not satisfy a user-defined threshold criteria. The filters consist of two independent threshold components, minimum (above-equal) and maximum (below-equal), which may be applied individually or together.
When both components are applied simultaneously the filters act as a value range constraint, invalidating trade signals that fall outside of the specified bounds.
"Above-Equal" returns true when the evaluated value is greater than or equal to the user-defined minimum boundary.
"Below-Equal" returns true when the evaluated value is less than or equal to the user-defined maximum boundary.
Minimum Percentage Change Positive-Flat/Negative Filter
The minimum percentage change filter is an entry filter that measures the relative change of a time-series value over a configurable historical window and applies a directional threshold condition, invalidating trade signals that do not meet the directional threshold criteria.
The filter compares the current value to its value n bars ago and computes the percentage difference. A signal returns true only if this percentage change satisfies both:
The selected directional requirement.
The user-defined minimum percentage change magnitude.
"Positive-Flat" direction logic:
Accepts values that have increased or remained unchanged, provided the percentage change is greater than or equal to the minimum threshold.
"Negative" direction logic:
Accepts values that have decreased, provided the magnitude of the decrease meets or exceeds the minimum threshold.
When the minimum threshold is set to 0%, the filter behaves as a pure directional check:
"Positive-Flat" accepts ≥ 0% changes.
"Negative" accepts < 0% changes only.
Basic and Multi-Part Trend Filters
Basic and multi-part trend filters are defined as entry filters that evaluate changes in time-series values from one period to the next and invalidate trade signals that do not satisfy a user-defined trend condition.
Basic trends operate independently of prior trend state, whereas multi-part trends are defined by the presence or absence of preceding trend sequences. The multi-part trend states are distinguished numerically and the conditions are bound to a user-defined trend count.
"Basic Uptrend" returns true when a time-series value is greater than the preceding value. For example, a basic volume uptrend filter returns true if the most recent candle's volume is greater than the preceding candle's volume.
"Basic Downtrend" returns true when a time-series value is less than the preceding value. For example, a basic volume downtrend filter returns true if the most recent candle's volume is less than the preceding candle's volume.
"Uptrend" returns true while a multi-part uptrend state is valid. The uptrend state begins when a new basic uptrend forms following a basic downtrend and remains valid until a new basic downtrend forms. The user-defined trend count will determine which multi-part trend condition is selected. For example, if the user-defined trend count is set to 3, then only 3-part uptrend conditions will return true.
"Downtrend" returns true while a multi-part downtrend state is valid. The downtrend state begins when a new basic downtrend forms following a basic uptrend and remains valid until a new basic uptrend forms. The user-defined trend count will determine which multi-part trend condition is selected. For example, if the user-defined trend count is set to 3, then only 3-part downtrend conditions will return true.
█ FEATURE SET W SPECIFIC FILTERS
All feature set specific indicators use the same calculations as the built-in TradingView indicators unless otherwise stated in the relevant filter sub-section. While users do not need to apply the indicators for the strategy to function, they can of course apply the relevant indicators as visual aids if they so desire.
For further information on how to apply built-in TradingView indicators, please refer to:
www.tradingview.com
As there are no built-in TradingView indicators for the WPO, WAD and WVAD values used in this script, code samples are provided in the relevant sections so that users can build their own Pine Script indicators.
For further information on how to build Pine Script indicators, please refer to:
www.tradingview.com
www.tradingview.com
Wave Period Oscillator (WPO) Filters
As there is no built-in indicator for the WPO value used in this script, users can build their own WPO indicator in Pine Script by copying the following code and pasting it into a new indicator:
//@version=6
indicator(title = "Wave Period Oscillator", shorttitle = "WPO", overlay = false)
import TradingView/ta/12 as ta
wpo_length = input.int(title = 'WPO Length', defval = 10, minval = 1, group = 'Wave Period Oscillator (WPO)')
wpo = ta.wpo(wpo_length)
plot(wpo, color = color.blue)
The default WPO length is set to 10.
Users can adjust the WPO length via strategy Settings/Inputs/WAVE PERIOD OSCILLATOR (WPO).
The WPO minimum and maximum boundary filter (see generic filters section above) defaults are as follows:
Apply WPO above-equal is set to false.
WPO above-equal threshold is set to -100.
Apply WPO below-equal is set to false.
WPO below-equal threshold is set to 0.
The WPO minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The WPO trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the WPO filters and adjust filter parameters via strategy Settings/Inputs/WPO FILTERS.
Williams Accumulation/Distribution (WAD) Filters
As there is no built-in indicator for the WAD value used in this script, users can build their own WAD indicator in Pine Script by copying the following code and pasting it into a new indicator:
//@version=6
indicator(title = "Williams Accumulation/Distribution", shorttitle = "WAD", overlay = false)
wad = ta.wad
plot(wad, color = color.blue)
The WAD minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The WAD trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the WAD filters and adjust filter parameters via strategy Settings/Inputs/WILLIAMS ACCUMULATION/DISTRIBUTION (WAD) FILTERS.
Williams Variable Accumulation/Distribution (WVAD) Filters
As there is no built-in indicator for the WVAD value used in this script, users can build their own WVAD indicator in Pine Script by copying the following code and pasting it into a new indicator:
//@version=6
indicator(title = "Williams Variable Accumulation/Distribution", shorttitle = "WVAD", overlay = false)
wvad = ta.wvad
plot(wvad, color = color.blue)
The WVAD minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The WVAD trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the WVAD filters and adjust filter parameters via strategy Settings/Inputs/WILLIAMS VARIABLE ACCUMULATION/DISTRIBUTION (WVAD) FILTERS.
Williams Fractal (WF) Filter
Although TradingView provides a built-in WF indicator that users may apply as a visual aid, the fractal logic used in this script is hard-fixed to a 2-period WF calculation. This fixed length ensures structural compatibility with the core swing high and swing low entry logic used throughout the strategy. Fractal lengths greater than 2 would introduce confirmation delays that conflict with the strategy’s swing completion rules and would therefore be incompatible with the intended entry structure.
The WF filter is defined as an entry filter that requires structural alignment between swing conditions and confirmed fractal signals.
When applied:
For long trades, the filter returns true only when a swing low forms and a 2-period up fractal is confirmed.
For short trades, the filter returns true only when a swing high forms and a 2-period down fractal is confirmed.
By default, the WF filter is set to false.
Users can apply the WF filter via strategy Settings/Inputs/WILLIAMS FRACTAL (WF) FILTER.
Williams Percent Range (WPR) Filters
The default WPR settings are as follows:
Length is set to 14.
Source is set to "Close".
Users can adjust the WPR inputs via strategy Settings/Inputs/WILLIAMS PERCENT RANGE (WPR).
The WPR minimum and maximum boundary filter (see generic filters section above) defaults are as follows:
Apply WPR above-equal is set to false.
WPR above-equal threshold is set to -100.
Apply WPR below-equal is set to false.
WPR below-equal threshold is set to 0.
The WPR minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The WPR trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the WPR filters and adjust filter parameters via strategy Settings/Inputs/WPR FILTERS.
█ ALERTS
Users can set alerts for any given strategy configuration via the alerts dialogue box.
Users must first ensure that the correct condition (the strategy title) is selected from the first drop-down list in the alert dialogue box's condition field.
Default alert messages have been configured for both entries and exits so that users can more effectively distinguish between long and short entries and exits while using long-short configurations.
To get alerts for both entries and exits the user should change the value in the condition field's second drop-down list from "Order fills only and alert() function calls" to "Order fills only". When using "Order fills only" with long-short configurations, it is recommended that users define their alert via the alert name field and use only the default {{strategy.order.alert_message}} call in the alert message field.
Alert conditions generated by "Order fills only" are evaluated after entry conditions have been satisfied and operational constraints (risk, position size and margin requirements) have been applied. As such, trade signals that would result in position sizes exceeding the simulated account's margin constraints will not generate alerts.
To get alerts for entries only the user should change the value in the condition field's second drop-down list from "Order fills only and alert() function calls" to "alert() function calls only".
The default alert messages generated by "Order fills only" are as follows:
"long entry".
"long exit".
"short entry".
"short exit".
The default alert messages generated by "alert() function calls only" are as follows:
"long entry".
"short entry".
Alert conditions generated by "alert() function calls only" are operational-constraint-agnostic and will generate alerts whenever entry conditions are satisfied, regardless of the simulated account's margin constraints.
For further information on setting and managing alerts, please refer to:
www.tradingview.com
www.tradingview.com
www.tradingview.com
█ LIMITATIONS AND CONSIDERATIONS
Backtesting
Backtest results should always be interpreted cautiously. Strategy performance can vary significantly across time periods and sample sets. While strong historical performance does not guarantee future results, poor historical performance reliably indicates a weak strategy when sample sizes are statistically meaningful.
Statistical Significance and Path-Dependent Outcomes (Overfitting)
In statistical practice, sample sizes of 100 observations are sometimes cited as a rough lower bound for certain forms of basic significance testing. In the context of trading strategy evaluation, such sample sizes are rarely sufficient to produce results that are meaningfully reliable or replicable. Based on practical experience, sample sizes closer to 1,000 observations or more are generally required before performance characteristics begin to stabilise. As a general rule, larger sample sizes increase the reliability and replicability of observed results.
Path dependence refers to situations in which outcomes are determined not only by initial conditions, but by the specific and unique sequence of price movements over a given time period.
Even with large sample sizes, favourable net profit outcomes should be interpreted with caution when they are primarily driven by either variable reward-to-risk configurations or fixed reward-to-risk configurations that employ unrealistically high reward multiples. In both cases, performance is often strongly influenced by path-dependent effects, making such outcomes less reliable and less replicable.
Fixed reward-to-risk configurations are generally less susceptible to path dependence when the reward multiple is kept within reasonable bounds. However, empirical studies and practitioner research suggest that reward multiples above approximately 3:1 increasingly exhibit the same path-dependent characteristics observed in variable reward-to-risk strategies.
Bar Magnifier
Due to the limitations of OHLC data, intra-bar price movement cannot be precisely determined.
When both stop loss and target levels are reached within the same candle, assumptions are made by the strategy tester.
Pine Script's bar magnifier partially mitigates this limitation by evaluating lower-timeframe data. However, this feature is available only to TradingView Premium users and remains inherently limited.
For further information on the bar magnifier functionality, please refer to:
www.tradingview.com
www.tradingview.com
TradingView Premium users can enable bar magnifier via strategy Settings/Properties/FILL ORDERS.
Processing Orders at Candle Close
Backtests cannot accurately account for slippage between signal generation and trade execution.
A practical mitigation is to use fixed-distance stop losses and targets rather than absolute price levels, a feature supported by many brokers and APIs.
Empirical Probabilities
Empirical probabilities are derived directly from observed outcomes rather than from theoretical models or assumed distributions. In the context of trading, they are calculated by measuring the relative frequency of events (such as wins and losses) across a large sample of historical trades.
Unlike conditional or model-based probabilities, empirical probabilities make no assumptions. Their validity relies primarily on sample size and the consistency of the rules used to generate observations, making them particularly relevant for trading systems evaluated under the law of large numbers.
Empirical probabilities are most useful for comparative analysis, such as assessing how different configurations, filters or exit mechanisms alter the statistical behaviour of a strategy under identical conditions. They are not intended to represent true predictive probabilities or to imply stable future performance.
To study empirical probabilities for comparative purposes, it is recommended that users set commission and both long and short margin values to 0% in order to maximise sample size. However, users should not interpret any resulting profits as realistic. Setting commission and margin (in particular) to 0% produces highly distorted outcomes that are not representative of realistic live trading conditions.
█ DISCLAIMER
This Pine Script strategy is provided for educational purposes only and does not constitute financial advice in any form.
Pine Script® ストラテジー
MACD HTF - Accurate Backtest Metrics// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║ MACD HTF STRATEGY WITH ACCURATE BACKTEST ║
// ╚══════════════════════════════════════════════════════════════════════════════╝
//
// 📊 STRATEGY OVERVIEW:
// This advanced MACD strategy allows you to execute trades based on Higher Timeframe (HTF)
// signals while operating on lower timeframe charts for precise entry timing.
//
// ⚡ KEY FEATURES:
// • Higher Timeframe Signal Detection (e.g., 15min signals on 1min chart)
// • Accurate Backtest Calculations with Commission & Slippage
// • Trailing Stop Loss with Offset
// • Hard Stop Loss (Percentage or Points based)
// • Cooldown Period after trade exits
// • Detailed Performance Metrics Panel
// • Visual Stop Loss Lines
// • Real-time Signal State Tracking
//
// 📈 HOW IT WORKS:
// 1. SIGNAL GENERATION:
// - Detects MACD crossovers on selected timeframe (current or HTF)
// - HTF mode: Captures 15min (or custom) signals while on 1min chart
// - Bullish: MACD crosses above Signal line → BUY
// - Bearish: MACD crosses below Signal line → SELL
//
// 2. ENTRY EXECUTION:
// - Current TF Mode: Executes immediately on signal
// - HTF Mode + Close: Waits for HTF candle close (more accurate)
// - HTF Mode + Immediate: Executes as soon as HTF signal appears
//
// 3. RISK MANAGEMENT:
// - Hard Stop Loss: Fixed percentage or points from entry
// - Trailing Stop: Activates after reaching trail points profit
// - Trail Offset: Maintains distance from highest/lowest point
// - Cooldown: Prevents overtrading after exits
//
// 4. POSITION MANAGEMENT:
// - Long Only / Short Only / Both directions
// - Automatic position reversal on opposite signals
// - One position at a time (no pyramiding)
//
// 🎯 RECOMMENDED SETTINGS:
// • For Scalping: 1min chart with 15min HTF signals
// • For Day Trading: 5min chart with 1H HTF signals
// • For Swing Trading: 1H chart with 4H/Daily HTF signals
//
// 📊 BACKTEST ACCURACY:
// • Commission: 0.1% per trade (adjustable)
// • Slippage: 3 ticks default (adjustable)
// • Execution: On bar close for realistic results
// • No repainting: lookahead=false on security calls
//
// ⚠️ IMPORTANT NOTES:
// • HTF signals may appear delayed on lower timeframes
// • Always wait for HTF close for most accurate backtesting
// • Stop losses may trigger intrabar (not visible in backtest)
// • Past performance does not guarantee future results
//
// 📝 USAGE INSTRUCTIONS:
// 1. Add to chart (recommended: 1min or 5min)
// 2. Enable "Use Higher Timeframe Signals"
// 3. Set Signal Timeframe (15min, 30min, 1H, etc.)
// 4. Configure Stop Loss settings
// 5. Set appropriate Cooldown period
// 6. Review backtest metrics in bottom-right panel
//
// 🔧 CUSTOMIZATION:
// • Adjust MACD parameters (Fast/Slow/Signal)
// • Modify Stop Loss percentage or points
// • Change trailing stop activation and offset
// • Set custom backtest date range
// • Fine-tune commission and slippage
//
// 💡 PRO TIPS:
// • Use HTF for trend direction, LTF for entry timing
// • Higher commission/slippage = more realistic results
// • Longer cooldown periods reduce overtrading
// • Trail offset prevents premature exits
//
// 📧 SUPPORT:
// For questions or suggestions, please comment on TradingView
Pine Script® ストラテジー
Solaris-XAUUSD
Strategy Overview
• Rather than using decorative or complex visuals the chart is intentionally kept simple and uncluttered to emphasize readability and precision over aesthetics.
• Designed for 15 minute intraday charts. These settings are for XAUUSD
• Each asset (stocks, indices, commodities, cryptocurrencies, etc..) requires individual calibration. Since market dynamics shift weekly, how can indicator values stay constant, and how can one asset’s settings apply to all assets?
• Retracement entry is best.
• Restrict trading to the first two signals per day.
• Fine tune input values weekly to adjust for changing volatility.
• Refer to the above pic for value setting.
Strategy Settings
• More than 80% of trades should be profitable (calibration goal).
• Minimum of 10 trades in the last 30 days (more is better).
• Strategy uses 10 input values that must be precisely fine tuned.
Important Notes
• There is no holy grail—discipline and risk management are essential.
• Always forward test thoroughly before live trading.
• For questions, feel free to DM me.
Current settings for XAUUSD
Sun 4.53
Pluto 86
Mars 18
Charon 1 10
Charon 2 0
Rahu 1.15
Laxmi 0.1
Sun Moon A 100
Mercury 25
ISM 0.5
Less important --ATR Period 14, ATR Smoothing EMA , ATR multiplier 1.25
In style untick following for clean chart--
Bar color
Trades on chart
Signal labels
Quantity
Disclaimer : This strategy is for educational and research purposes only and should not be considered investment advice. Always conduct your own research and consult your financial advisor before making trading decisions. Past performance does not guarantee future results.
Pine Script® ストラテジー
SBP Multimode Trading System v1.0 (Invite Only)Overview
SBP Multimode Trading System is a fully adaptive, professional-grade trading system designed for Scalping, Intraday, and Swing Trading across Index, Commodity, and Crypto markets.
This system integrates AI-style consensus logic, dynamic trend filtering, volatility adaptation, and liquidity-aware protection to deliver high-quality, low-noise trading signals.
Built for serious traders who value precision, discipline, and consistency.
🚀 Key Features
✅ Multi-Mode Trading Engine
Scalping / Intraday / Swing presets
Automatic parameter optimization per mode
✅ AI Smart Consensus System
Combines Trend + DTF + UW MA + Momentum + Ribbon
Generates high-confidence Buy/Sell signals
Anti-overtrading alternation lock
✅ Dynamic Trend Filter (DTF)
Auto / Stable / Dynamic modes
Adapts to volatility and timeframe
Non-repainting confirmation
✅ Adaptive UW Moving Average
Volatility-based length adjustment
Market-specific presets
Strong trend validation
✅ PMR Ribbon System
Trend direction
Choppy market detection
Reversal & trap signals
✅ Momentum & Impulse Engine
Strength-based entries
Cooldown protection
Noise filtering
✅ SM-Lite Liquidity Filters
Stop-hunt detection
Equal high/low blocking
Wick spike protection
✅ Automatic Market Detection
Index / Commodity / Crypto
Instrument-aware presets
✅ Auto Timeframe Optimization
ATR, DTF, Momentum auto scaling
Optimized for 1m to 30m charts
✅ Fibonacci Golden Zone
Auto swing detection
23%–38% retracement zones
Trend-based projection
✅ Professional Risk Engine (Backtest Mode)
ATR-based SL / TP
Trailing stops
Daily trade limits
✅ Strategy + Indicator Hybrid
Indicator Mode (Manual Trading)
Strategy Mode (Backtesting)
📊 Signal Types
🔹 AI Buy / Sell – High-confidence consensus signals
🔹 Scalping Arrows & Dots – Fast momentum entries
🔹 Ribbon Trap Signals – False breakout reversals
🔹 Swing / Intraday Signals – Trend-based setups
🔹 Exit Labels – Clear position management
All signals are non-repainting (bar-confirmed).
⚙️ Recommended Usage
Trading Style Timeframe Mode
Scalping 1m – 5m SCALPING
Intraday 5m – 15m INTRADAY
Swing 15m – Daily SWING
✔ Works best on:
NIFTY / BANKNIFTY / FINNIFTY
Gold / Crude / Silver
BTC / ETH / Major Alts
📈 How to Trade (Basic Rules)
🟢 Buy Setup
AI Buy / Scalp Buy / Trend Buy appears
Price above DTF & UW MA
Ribbon turns bullish
Enter on candle close
🔴 Sell Setup
AI Sell / Scalp Sell / Trend Sell appears
Price below DTF & UW MA
Ribbon turns bearish
Enter on candle close
🎯 Exit
Use Exit Labels
Or ATR-based targets
Or trail with market structure
⚠️ Always follow your own risk management.
🔒 Access Policy
This is a Private / Invite-Only proprietary system.
✔ No redistribution
✔ No resale
✔ No sharing
✔ License bound to account
Unauthorized usage may lead to permanent revocation.
📞 Support & Updates
Subscribers receive:
✔ Regular updates
✔ Performance improvements
✔ Bug fixes
✔ Feature enhancements
For access and support, contact the author.
⚠️ Disclaimer
This tool is for educational and analytical purposes only.
Not financial advice
No guaranteed returns
Trading involves substantial risk
Past performance does not guarantee future results
Use at your own responsibility.
Pine Script® ストラテジー
The Best trend following strategy suited for upward BTC markets!🚀 BTC Trend Beast – Simple, High-Conviction, Low-Frequency Trend Strategy
Designed for volatile assets like Bitcoin ; catches big trends while keeping your mind at peace. 🧠
We favor long-only trades (very few shorts) to avoid unnecessary stress and whipsaws.
Real Backtest Highlights (Jan 2022 – Feb 2026 on BTC, extended to 10+ years historical):
Winner Mode ("Trend Confirm"):
Sharpe Ratio: 0.95
Total Return: +213% (vs. Buy & Hold +44.5%)
Annualized Return: +31.9%
Max Drawdown: -30.5% (manageable in crypto volatility)
Win Rate: 67%
Total Trades: Just 12 (~3 per year!)
Profit Factor: 1.23
Why this crushes in trending/volatile markets:
Extremely low trade frequency → fewer decisions, less emotional trading
Event-based signals (no repainting or daily noise/flicker)
Zero warmup issues — pure SMA logic
Built for BTC but shines on any strong-trending volatile asset (ETH, SOL, major forex pairs in trends, etc.)
Three Built-in Modes (switch easily in settings):
Trend Confirm → The proven winner above (our flagship)
Low Drawdown → SMA(20/200) Golden Cross + Donchian Channel exit → Only -13.6% max DD! (Ultra-defensive)
Breakout → Classic Donchian(55/10) Turtle-style → Great for explosive moves
All modes use clean, event-driven entries/exits — no over-optimization fluff.
Perfect if you're:
Tired of over-trading
Want real edge in BTC bull runs
Prefer set-it-and-forget-it style with infrequent high-quality signals
📊 Test it yourself on BTC daily/weekly charts — backtest further if you like!
DISCLAIMER: This is for educational and research purposes only. Not financial advice. Past performance ≠ future results. Crypto is highly volatile — trade at your own risk, use proper position sizing, and never risk more than you can afford to lose.
Pine Script® ストラテジー
LBR Medallion Jim Simmons Mean Reversion Regime FilteredLinda Bradford Raschke's Mean Reversion Strategy Inspired by Quantitative Approaches
This is a short-term mean reversion strategy that attempts to capture small inefficiencies when price deviates from a dynamic mean (EMA), confirmed by volatility bands (ATR-based), RSI extremes, and an ADX filter to avoid strong trends.
Core Logic:
- Entry Long: Price below lower band (EMA - mult * ATR), RSI oversold, ADX below threshold (ranging market)
- Entry Short: Price above upper band, RSI overbought, ADX low
- Optional filters:
- Regime: Aligns with higher-timeframe trend (price >/< Daily EMA200)
- Volume: Requires above-average volume for confirmation
- Exits: Either fixed ATR-based TP/SL or reversion to EMA
Designed primarily for ranging or mildly trending markets on liquid assets (e.g., XAUUSD 4H tested). It performs best in non-trending conditions; strong trends can lead to drawdowns.
Features:
- Market-neutral long/short capability
- Volatility-adjusted bands for adaptive deviation
- Toggleable regime and volume filters
- Visual plots for EMA, bands, and daily regime line
Usage Recommendations:
- Timeframe: 1H to 4H (tested on 4H XAUUSD)
- Assets: High-liquidity instruments (forex pairs, indices, commodities)
- Risk: Use proper position sizing (1-2% risk per trade recommended). Backtest on your symbol/timeframe.
- This is not financial advice. Past performance does not guarantee future results. Trading involves substantial risk of loss.
No external dependencies or repainting issues. Educational/experimental script.
Feedback welcome — happy to discuss improvements!
Pine Script® ストラテジー
SquadAlgo-FoxtrotSquadAlgo-Foxtrot 🤖 runs directly inside TradingView, so you skip extra accounts and avoid platform switching. Open your chart, apply the algorithm, and move straight into execution.
Built on an AI backed strategy and validated through deep historical testing 📊, Foxtrot focuses on disciplined trades instead of emotional decisions. Each rule follows measurable data so you operate with clarity.
The setup stays simple ⚡. Load the script, connect your market, and start analyzing within minutes. The layout feels familiar because you remain inside TradingView, one of the most trusted charting platforms among active traders.
Customization drives performance 🛠️. Adjust inputs, test variants, and review results before placing capital at risk. This workflow supports tighter risk control and stronger consistency.
SquadAlgo-Foxtrot fits traders who value precision, speed, and full control without juggling multiple systems 🚀.
Pine Script® ストラテジー
EMA 19/91 Cross + Candle Confirm + 91 Trend FilterSimple Average Strategy Gives signal to buy and sell u wukll get another warning no doubt but i cannot add alert untill it is published
Pine Script® ストラテジー
ORB MASTER V10 - AUTOPILOTThis is a custom-built Opening Range Breakout (ORB) Algorithm designed for US Futures (NQ, MNQ, ES). It features an automated dynamic Risk Management System (Auto SL & TP), a smart Chandelier Trailing Stop, and a Multi-Timeframe Trend Filter (EMA 200). Perfect for the 15:30 NY Open.
Pine Script® ストラテジー
WindsThis is a 5-minute trading strategy designed for gold, incorporating trend filtering, entry signals, and fixed percentage risk management (stop-loss and take-profit). It includes visual aids such as position range boxes and cost lines to enhance trade monitoring. The strategy aims to capture short-term price movements while maintaining clear risk control and visual feedback for traders.
Pine Script® ストラテジー
ORB StrategyOpening Range Break Strategy. It works, sometimes. Stop loss to break even is not currently working, dont rely on that. To be honest in backtesting, it hurt more than it helped. The ORB strategy has been around for a long time; it has ebbs and flows on when it is working. You'll know that it's currently working because your Youtube feed will be full of videos for it.
Native Quantlynk and Ghost integration using {{strategy.order.alert_message}}
NOT FINANCIAL ADVICE. NO GUARANTEES OF ANY KIND.
Pine Script® ストラテジー
Volume ScalperScalping strategy; Only tested it on the 1 and 2 MNQ. Good luck.
Native Quantlynk and Ghost alerts using {{strategy.order.alert_message}}
NOT FINANCIAL ADVICE. NO GUARANTEES OF ANY KIND.
Pine Script® ストラテジー
TSM RSI Shift Zone StrategyTSM RSI Shift Zone Strategy is a momentum-based system using RSI shift levels.
Enters Long after RSI crosses above 70 and confirms momentum.
Enters Short after RSI crosses below 30 and confirms momentum.
Exits when RSI crosses 50 or optional SL/TP is hit.
Designed for trending markets.
Trading involves risk.
Pine Script® ストラテジー
TSM RSI Shift Zone Strategy [Converted]This strategy is a momentum breakout system based on RSI levels.
It enters long when RSI crosses above 70 (strong bullish momentum).
It enters short when RSI crosses below 30 (strong bearish momentum).
It exits trades when RSI crosses back through 50 (momentum weakening).
Optional stop loss and take profit can be enabled.
It trades strength and weakness breakouts — not reversals.
Pine Script® ストラテジー
Nasdaq Liquidity Fade Engine (NLFE)Summary in one paragraph
Nasdaq Liquidity Fade Engine is a daily timeframe strategy for Nasdaq index futures and close proxies such as NQ, MNQ, and NDX. It is designed to act only when a small set of tape, mean location, and trend energy conditions align, and it expresses risk using an ATR sized bracket so the same settings scale across NQ and MNQ. It is original because it can optionally anchor its signal feed to a single continuous Nasdaq tape while executing on related instruments, reducing symbol noise when you want one consistent decision stream. Add it to a clean chart and read entries and exits from the built in strategy markers. Orders confirm on bar close, so markers settle on close.
Scope and intent
• Markets. NQ, MNQ, NDX, and other highly liquid Nasdaq linked instruments
• Timeframes. Primarily daily, other timeframes are supported but not the optimization target
• Default demo used in the publication. CME_MINI:NQ1! on 1D
• Purpose. Provide a compact, auditable daily decision engine for Nasdaq instruments with explicit volatility scaled risk
• Limits. This is a strategy. Orders are simulated by the TradingView engine on standard candles only
Originality and usefulness
This is not a stack of common indicators. It is a minimal asymmetric rule set with a portability layer.
• Unique concept or fusion. Optional tape anchored signal feed plus asymmetric long and short gating plus ATR normalized risk brackets
• What failure mode it addresses. Reduces discretionary over trading by restricting entries to specific tape states and by enforcing a hard stop framework instead of indefinite holds
• Portable yardstick. ATR on the traded symbol is the common unit for stop and target sizing across NQ and MNQ
• Protected scripts. The implementation is protected to reduce low effort cloning and to preserve version integrity, while the method and practical use are disclosed here
Method overview in plain language
The strategy evaluates a small set of state conditions on each bar. It uses a selected signal feed for its tape inputs and applies risk on the traded chart symbol. Long and short are intentionally asymmetric to reflect Nasdaq drift and downside behavior.
Base measures
• Tape state. Candle direction and relative participation measured from the selected signal feed
• Mean location. A rolling mean reference used to define location and fade context
• Trend energy. A trend strength filter used to avoid low quality fades
• Risk unit. ATR of the traded symbol used as a volatility scaled sizing unit for exits
Components
• Tape contraction state. Detects low participation pullback behavior on the signal feed. Used to qualify long opportunity context in a way that is not tied to a fixed point value.
• Mean location state. Uses a rolling mean reference to avoid taking fades in the wrong location regime.
• Trend energy gate. Uses a trend strength threshold to require sufficient directional energy when the short side activates.
• ATR bracket risk. Uses ATR multiples for stop and target distances on the traded symbol, keeping risk scalable across NQ and MNQ.
Fusion rule
The model uses two separate gate sets. Long and short do not share identical prerequisites. The intent is to capture pullback opportunity under contraction while only enabling shorts when location and energy align.
Signal rule
• Long suggestion appears when the tape state indicates a contraction style pullback and the regime filter is satisfied
• Short suggestion appears when the tape state indicates a fadeable push that is location constrained under the mean reference and trend energy is above the threshold
• Long only mode disables opening shorts, while still allowing the short condition to flatten an open long
• Long and short mode allows directional flips when the opposite condition triggers
Inputs with guidance
Setup
• Use NQ as signal source. When enabled, the tape inputs are sourced from the chosen NQ feed so signals can remain consistent across NQ, MNQ, and NDX charts. When disabled, tape inputs come from the chart symbol.
• NQ symbol. The anchor feed used when signal sourcing is enabled.
• Signal timeframe. Blank uses the chart timeframe. For the intended daily workflow, use 1D.
Logic
• EMA length. Typical range 10 to 60. Higher values smooth the mean reference and reduce sensitivity. Lower values increase responsiveness.
• Start year filter. Use to constrain testing to the regime you want to study. Defaults reflect the post 2008 regime focus.
Filters
• ADX length and smoothing. Typical range 10 to 20. Shorter reacts faster and can increase churn.
• ADX minimum. Typical range 15 to 30. Raising it filters shorts and concentrates on higher energy phases.
Risk
• Use ATR stop and target. Enables ATR sized bracket exits.
• ATR length. Typical range 10 to 21 on daily.
• Stop ATR multiple. Typical range 0.3 to 2.5. Raising it gives more room and increases risk per trade.
• Target ATR multiple. Typical range 4 to 30 for more frequent targets. Very large values behave like an expansion capture mode where exits are dominated by the stop or by an opposite regime switch rather than by the target.
Properties visible in this publication
• Initial capital for the example. 100000
• Base currency. USD
• request.security uses lookahead off everywhere
• Strategy only. Default order size method Fixed with value 1 contract. Pyramiding 0. Commission 5 USD per contract. Slippage 5 ticks. Process orders on close On. Bar magnifier Off. Recalculate after order is filled Off. Calc on every tick Off.
Realism and responsible publication
• No performance claims. Past results never guarantee future outcomes
• Execution varies by venue, liquidity, and volatility
• Orders process on bar close and fills use TradingView engine assumptions
• Non standard chart types are not supported for strategies
Honest limitations and failure modes
• This is optimized for the daily timeframe. Intraday use can change signal frequency and behavior materially.
• If you enable tape anchoring, volume and candle state come from the selected feed. This can be useful for consistency, but it also means the tape input is not the same as the executed symbol for instruments with different session structures or synthetic volume.
• Very quiet regimes can reduce signal contrast. Consider longer lengths or higher thresholds.
• Gap heavy periods can change stop and target behavior.
• If both stop and target are inside the same bar range, fills follow standard candle assumptions.
Legal
Education and research only. Not investment advice. You are responsible for your decisions. Test on historical data and in simulation before any live use. Use realistic costs.
Pine Script® ストラテジー
Liquidity Swings SOL V10.2 - 3CommasHere's a publish-ready description:
Liquidity Swings — Smart Money Sweep Strategy
Automated futures strategy that identifies and trades institutional liquidity sweeps on SOLUSDT 30-minute charts.
How it works:
Price tends to sweep above/below key swing levels where stop losses cluster — these are liquidity zones. Smart money grabs this liquidity, then reverses. This strategy detects those sweeps and enters on the reversal.
Features:
Liquidity zone detection using pivot-based swing highs/lows
Multi-layer trend filtering (HTF EMA + local EMA cross + price action)
Breakout detection with volume confirmation
Zone-based & ATR-adaptive stop losses with safety cap
Trailing stop with activation threshold
Cascading partial take profits at opposing zones
Optimized for SOL's volatility profile
Designed for:
SOLUSDT Perpetual Futures (Bybit)
30-minute timeframe
5x leverage, cross margin
Compatible with 3Commas / WunderTrading webhook automation
Risk management built-in: Every trade has a hard stop loss, safety cap, and optional trailing stop. No open-ended positions.
⚠️ Invite-only. DM for access.
Pine Script® ストラテジー
Tribute To Peter LynchTribute To Peter Lynch - Fund Manager Simulator
"Know what you own, and know why you own it." - Peter Lynch
WHO WAS PETER LYNCH?
Peter Lynch is one of the greatest investors who ever lived. From 1977 to 1990, he managed the Fidelity Magellan Fund and turned it from $18 million into $14 billion in assets. He averaged a 29.2% annual return for 13 straight years, making Magellan the best-performing mutual fund in the world.
What made Lynch different? He believed regular people could beat Wall Street. He bought stocks in companies he understood - he'd ask minivan owners at movie theaters what they thought of their Chrysler, he'd notice the local factory hiring more people, he'd pay attention to which donut shop had the longest line. He called this your "investor's edge" - the things you already know from your daily life that Wall Street analysts sitting in their offices can't see.
Lynch famously said: "If you can tell your stock story to a fifth grader and they understand it, you've got a good one. The more complicated the story, the more likely it is to fall apart."
He also had the stomach for downturns. During his 13 years at Magellan, the market dropped 10% or more NINE times, and Magellan fell right along with it every single time. But he never panicked. He knew that behind every stock is a company, and if the company is doing well, the stock will eventually follow.
WHAT THIS SCRIPT DOES
This is a fund manager simulator built entirely around Peter Lynch's investing philosophy. It's not a technical indicator. There are no moving averages, no RSI, no MACD. Lynch was a fundamental investor - he cared about what a company earns, how fast it's growing, how much debt it has, and whether the story makes sense.
The script classifies any stock into one of Lynch's 6 categories, scores it on a 0-100 Lynch Score, evaluates the fundamental story, and generates buy/sell signals based purely on the same criteria Lynch used at Magellan.
THE 6 STOCK CATEGORIES
Lynch believed you can't treat all stocks the same. A 50% gain on a Slow Grower is fantastic and probably time to sell. The same 50% on a Fast Grower could be just the beginning of a 10-bagger. He broke every stock into 6 categories:
1. FAST GROWERS (20%+ earnings growth)
Companies growing earnings fast, typically small to mid-sized. These are the potential 10-baggers. Lynch looked for PEG ratios below 1.0 and used his "baseball inning" concept - you want to buy these in innings 2-5, when the formula is proven but there's still a long runway ahead. Think of Walmart when it only had a few hundred stores, or Microsoft 3 years after its IPO.
2. SLOW GROWERS (3-8% earnings growth)
Large, mature companies that grow about as fast as the overall economy. You buy these for the dividend. Lynch looked for steady, rising dividends with a low payout ratio (so the dividend is safe). If the dividend yield drops or the payout ratio gets too high, it's time to move on.
3. STALWARTS (10-14% earnings growth)
Big, solid companies that aren't going to disappear but aren't going to triple overnight either. Lynch's rule: take your 30-50% gain and rotate the money into another Stalwart. These are your portfolio's defense - they hold up in recessions and won't go bankrupt.
4. CYCLICALS (tied to the economic cycle)
Companies in industries like autos, airlines, steel, and chemicals that boom and bust with the economy. Here's Lynch's counterintuitive trick: buy cyclicals when the PE is HIGH (that means earnings are at the trough and about to recover) and sell when the PE is LOW (earnings have peaked and are about to fall). This is the opposite of how PE works for every other category.
5. TURNAROUNDS (beaten down, potential recovery)
Companies in deep trouble that might recover. Lynch always checked: does this company have enough cash to survive? Is there a real plan (new management, cost cutting, selling bad divisions)? He said don't buy on hope - wait for actual evidence the turnaround is working. But when they work, the upside can be enormous.
6. ASSET PLAYS (hidden value)
Companies sitting on assets the market doesn't see or doesn't value - real estate, patents, brand names, cash on the balance sheet. Lynch's example: Disney after it opened Epcot. Growth slowed, but the company was sitting on the Disney name, all that Florida land, and a library of characters worth billions that were carried on the books for nothing.
BAR REPLAY - WHERE THIS SCRIPT REALLY SHINES
This script was built with TradingView's Bar Replay feature in mind. Bar Replay is what transforms this from a backtest into a fund manager simulator.
HOW TO USE BAR REPLAY:
1. Add the script to your chart
2. Pick any stock and classify it (Fast Grower, Stalwart, etc.)
3. Set your fundamental inputs if using Manual mode, or let Auto mode pull TradingView financial data
4. Click the Bar Replay button on your toolbar (the clock icon with a rewind arrow)
5. Pick a starting date - maybe go back 5 years, or 10, or start right before a crash
6. Press Play and watch the simulation unfold bar by bar
WHAT YOU'LL SEE IN BAR REPLAY:
- The Lynch Score updates in real time as fundamentals change each quarter
- The Story Status shifts: "Growth Accelerating" might become "Growth Slowing" as the company matures
- Buy and sell signals fire when Lynch's criteria are met
- The P&L tracker shows your position gain in real time
- The Peter Lynch portrait in the corner changes color based on how your portfolio is doing:
-- Equity rising: Lynch appears in bright GREEN against a deep BLUE background, getting more vivid as gains grow
-- Heavy drawdown: Lynch turns CRIMSON RED against a BLACK background
-- Stop loss hit: The portrait FLASHES RED as a warning
-- Neutral: Lynch appears in CYAN/TEAL against dark navy
- The daily Lynch wisdom quote rotates, keeping you in his mindset
BAR REPLAY SCENARIOS TO TRY:
- Start replay on Apple (AAPL) in 2003 as a Turnaround - watch it reclassify into a Fast Grower
- Replay Ford (F) through 2008-2012 as a Cyclical - see Lynch's high-PE-buy rule in action
- Run Coca-Cola (KO) from 1990 as a Stalwart - practice the 30-50% rotate rule
- Try any stock through the 2020 COVID crash - Lynch survived 9 crashes at Magellan, now you can experience one
SETTINGS GUIDE - EXPLAINED SIMPLY
Think of the settings like customizing a video game character before you play. Here's what each group does:
GROUP 1: STOCK TYPE
"What kind of company is this?"
Pick one of the 6 categories. This changes ALL the rules the script uses.
Baseball Inning: Where is this company in its life?
- Innings 1-3 = Young, lots of room to grow (like a kid)
- Innings 4-6 = Middle age, proving itself
- Innings 7-9 = Old, running out of gas
Early innings get a score bonus. Late innings get a penalty.
GROUP 2: FUNDAMENTAL DATA
"Where do the numbers come from?"
- Auto mode: TradingView pulls real financial data (EPS, revenue, debt) automatically. Best for stocks.
- Manual mode: You type in the numbers yourself. Use this for crypto, forex, or if Auto data looks wrong.
GROUP 3: PEG & VALUATION
"How do I know if a stock is cheap or expensive?"
PEG = Price-to-Earnings divided by Growth rate.
- PEG of 1.0 = fairly priced (PE matches growth rate)
- PEG below 1.0 = cheap (you're paying less than what the growth is worth)
- PEG above 2.0 = expensive
The Buy Threshold (default 1.0) means: "only buy if PEG is at or below this number."
The Sell Threshold (default 2.0) means: "sell if PEG goes above this number."
GROUP 4: BALANCE SHEET HEALTH
"Is this company in good financial shape?"
- Max Debt/Equity: How much debt is too much? Default 0.50 means total debt shouldn't be more than half of the company's net worth. Lynch always checked the balance sheet.
- Min Cash Ratio: Does the company have enough cash? Important for Turnarounds.
- Max Payout Ratio: Is the company paying out too much of its earnings as dividends? Above 80% means the dividend might get cut.
GROUP 5: CATEGORY RULES
"Special rules for each stock type."
These are the specific thresholds for each of the 6 categories. The defaults are based on Lynch's actual criteria from his books.
Examples:
- Fast Grower Min Growth 20%: Lynch said a Fast Grower needs at least 20% earnings growth
- Stalwart Rotate Target 40%: Lynch rotated Stalwarts after 30-50% gains
- Cyclical Trough PE 25: Buy cyclicals when PE is HIGH (counterintuitive!)
GROUP 6: STRATEGY SETTINGS
"Should the Lynch Score control the trades?"
- Score Gate OFF (default): The Lynch Score is just a meter showing conviction. Trades fire based on category rules alone.
- Score Gate ON: The Lynch Score must be above the entry threshold to buy and below the exit threshold to sell. This adds an extra filter.
GROUP 7: RISK MANAGEMENT
"How much can I lose on one trade?"
- Stop Loss: If the stock drops this % from your entry price, sell automatically. Default 15%.
- Take Profit: If the stock rises this % from your entry price, sell automatically. Default 100% (a double).
GROUP 8: DISPLAY
"What do I see on the chart?"
- Show/hide the Lynch portrait, the dashboard panel, and buy/sell signals
- Customize your bull/bear/neutral colors
THE DASHBOARD
The top-right panel shows everything Lynch would want to see at a glance:
- LYNCH SCORE: A 0-100 conviction meter with a visual bar. Built from 5 sub-scores:
-- PEG Score (0-25): Is the stock cheap relative to its growth?
-- Earnings Score (0-25): Is earnings growth meeting the target for this category?
-- Balance Sheet Score (0-20): How healthy is the financial structure?
-- Margin Score (0-15): Are profit margins good and expanding?
-- Dividend Score (0-15): Is the dividend policy appropriate for this category?
- STORY STATUS: The current fundamental narrative in plain English
-- "Growth Accelerating", "Trough - Buy Zone", "Turnaround Succeeding", etc.
- SIGNAL: The specific reason behind the current buy or sell signal
- P&L: When in a trade, shows your unrealized gain/loss and warns Stalwart holders when approaching the rotate target
- VALUATION: PEG ratio, PE ratio, and fair value comparison
- EARNINGS: EPS, EPS growth rate, and revenue growth vs. category targets
- BALANCE SHEET: Debt/equity ratio and net cash per share
- MARGINS: Profit margin trend (expanding or contracting)
- DIVIDENDS: Yield, payout ratio, and sustainability assessment
- DAILY WISDOM: A rotating quote from Peter Lynch to keep you grounded
RESEARCH & SOURCES
This script was built using the following primary sources, all studied extensively:
1. "One Up On Wall Street" by Peter Lynch with John Rothchild (1989)
share.google
Lynch's first book laying out his complete investment philosophy - the 6 categories, PEG ratio, the "story" framework, and the idea that everyday investors have edges over professionals.
2. "Beating the Street" by Peter Lynch with John Rothchild (1993)
share.google
Lynch's second book where he walks through his actual portfolio decisions at Magellan, explains his mutual fund strategy, and shows step-by-step how he picks stocks. 328 pages of real-world application.
3. "The Peter Lynch Playbook" compiled by Mayur Jain (@mjbaldbard)
share.google
A comprehensive set of notes summarizing both Lynch books plus interview snippets. Covers portfolio allocation percentages, category-specific checklists, the 2-minute drill for each stock type, risk/reward profiles, and sell criteria. This document was instrumental in translating Lynch's qualitative approach into quantifiable rules.
4. Peter Lynch's "Stock Shop" Video Consultation (Fidelity Archives)
youtu.be
A full-length video presentation where Lynch personally explains his approach to categorizing stocks, building stories, understanding PE ratios, evaluating balance sheets, and managing risk. Key quotes transcribed and used to calibrate the scoring engine and story status logic.
IMPORTANT NOTES
- This is a STRATEGY script, not an indicator. It generates actual backtestable trades.
- The script is purely fundamental. No technical analysis. Lynch didn't use charts to make decisions.
- Auto mode requires stocks with TradingView financial data. For other instruments, use Manual mode.
- The Lynch Score is a CONVICTION METER by default, not a trade gate. Enable Score Gate in settings if you want it to filter trades.
- All portrait coloring is non-repainting. Colors only update on confirmed (closed) bars.
- Start with Bar Replay. That's where the magic happens. Watch the story unfold bar by bar, just like Lynch did at his desk at Fidelity every morning.
"The key organ is the stomach, not the brain." - Peter Lynch
Pine Script® ストラテジー
LBR with HM Gartley 1935 on Log Returns Momentum Vol TargetOverview
Linda Bradford Raschke's Momentum-based strategy, made by conclusions from the book Profits in the Stock Market by H.M. Gartley in 1935, and uses log returns for directional bias as well as dynamic volatility targeting to maintain consistent risk exposure. Sizes positions inversely to realized volatility (from log returns std dev) for better compounding in trending markets like gold (XAUUSD).
Key Features
Log returns calculation: ln(close / close ) for time-additive momentum.
Directional signals: Enter long when momentum > 0, short when < 0 (configurable strict crossover mode).
Volatility scaling: Targets user-defined annual vol (default 20%) → reduces size in high-vol periods.
Exits: Percentage TP/SL + explicit close on opposite signals for reliable backtests.
Debug visuals: Momentum plot, signal shapes, real-time table (vol, size factor, qty, signal state).
How to Use
Best on Daily or higher timeframes for meaningful log momentum (e.g., XAUUSD, BTCUSD, stocks).
Adjust Momentum Lookback (default 50 bars), Target Vol %, TP/SL %.
Backtest with commissions/slippage enabled for realism.
Use on log-scale chart for % perspective.
Limitations & Notes
No guarantees of profitability; markets involve risk.
Designed for educational/quant purposes; test thoroughly.
Not financial advice.
Open-source for community learning.
Credits
Built on standard quant finance principles (log returns for normality/additivity, vol targeting for risk control). Inspired by discussions on compounding and GARCH-like vol estimation from Linda Bradford Raschke's conclusions from the book Profits in the Stock Market by H.M. Gartley in 1935.
Pine Script® ストラテジー
Swing Strategy Feature Set V [theEccentricTrader]█ OVERVIEW
This swing strategy is part of a broader research and exploration framework designed to encourage users to experiment with a variety of technical concepts and evaluate the comparative effectiveness of different strategy configurations. For example, users can first configure a core strategy as a benchmark, then iteratively test a range of feature configurations as additional entry conditions and compare their performance against one another and against the core strategy.
Feature Set V includes concepts beginning with the letter "V" and forms part of a larger swing strategy suite that covers a wide range of technical concepts. The objective of the suite is not curve-fitting, but rather structured experimentation, exploration and statistical validation (or invalidation) of technical concepts.
Concepts exclusive to the feature set are as follows:
Vertical Horizontal Filter
Volume
Positive Volume Index
Negative Volume Index
On-Balance Volume
Price Volume Trend
Volume Weighted Average Price
Volume Zone Oscillator
Vortex Indicator
█ OPERATIONAL
Initial Capital
The initial capital is defined as a monetary value denominated in a given base currency.
The default initial capital is set to 100,000.
The default base currency is set to the selected symbol's default base currency.
Users can adjust the initial capital and select an alternative base currency via strategy Settings/Properties.
Risk as Percentage of Equity
The equity is defined as the sum of initial capital, net profit and open profit.
The risk is defined as a percentage of equity per-trade. As a result, net profit outcomes are subject to compounding effects over time.
The default risk is set to 1% of equity.
Users can adjust the strategy's per-trade risk via strategy Settings/Inputs/STRATEGY.
For further information on how the risk is applied in practice, refer to the position sizing section below.
Unit of Value
The unit of value is defined as a decimal precision factor that converts user-defined point or pip distances into actual price units used by the selected symbol.
Different symbols express price movement using different conventions. For example, some symbols are quoted directly in whole price points, while others use pips or fractional point increments. The unit of value provides a normalisation layer that allows all distance-based logic in the strategy to operate consistently across symbols.
Examples:
A unit of value of 1 corresponds to a price increment of 1.0.
A unit of value of 10 corresponds to a price increment of 0.1.
A unit of value of 100 corresponds to a price increment of 0.01.
A unit of value of 1000 corresponds to a price increment of 0.001.
A unit of value of 10000 corresponds to a price increment of 0.0001.
Users should consult their broker’s published symbol specifications to confirm how price movement is defined for the symbols they intend to backtest. Incorrect configuration of the unit of value may result in misaligned stop distances, targets and/or risk calculations.
The default unit of value is set to 1.
Users can adjust the unit of value via strategy Settings/Inputs/STRATEGY.
Stop Buffer
The stop buffer is defined as the number of points or pips beyond a stop loss level required for the level to be considered clearly breached.
The default stop buffer is set to 0 points/pips.
Users can adjust the stop buffer via strategy Settings/Inputs/STRATEGY.
Risk Range
The risk range is defined as the difference between the entry price and the stop loss price (inclusive of the stop buffer) for any given trade.
Position Sizing
Position sizing determines the quantity of contracts, shares or units opened for each trade based on the user-defined risk and the selected symbol’s pricing structure.
"syminfo.pointvalue" is a built-in Pine Script variable that defines the number of underlying units contained within a single contract for any given symbol, and is critical for accurate position size calculations.
The position size is calculated as follows:
The risk range is multiplied by the syminfo.pointvalue to convert the price movement into its monetary equivalent.
The user-defined risk amount (expressed as a percentage of equity) is divided by this monetary risk per unit to determine the position size.
This ensures that each trade risks a consistent proportion of account equity regardless of point or pip based quoting conventions, symbol price scale or contract specifications.
While the strategy targets a fixed percentage of equity risk per-trade, the exact risk applied cannot always be matched precisely due to symbol-specific constraints such as contract sizing and margin requirements. In these cases, the strategy opens the largest permissible position that does not violate operational constraints, resulting in a realised risk that is as close as possible to the user-defined risk without exceeding it.
For further information on the syminfo.pointvalue variable, please refer to:
www.tradingview.com
Margin
The margin is defined as the minimum percentage of a position’s notional value that must be covered by the strategy’s available equity in order for TradingView's strategy tester to simulate opening and maintaining that position. For example, a margin setting of 25% means the simulated account must hold equity equal to at least 25% of the position’s notional value in order to enter or maintain that trade, the remaining 75% is considered provided by the simulated broker.
A lower margin percentage allows the account to open larger positions relative to its equity, because the required equity portion is smaller. Conversely, a higher margin percentage demands more of the account's equity be committed to any given position.
When the account’s equity falls below the required margin, the strategy tester emulates a margin call event, in which the broker emulator forcibly closes or reduces positions so that remaining positions no longer exceed available equity relative to the margin requirement. This behaviour is documented as part of TradingView’s margin/leverage feature for strategies.
Margin settings in a strategy are used solely for simulation purposes and do not automatically match any broker’s real-world margin requirements (which can vary by broker, asset class and symbol). Users should consult their broker’s published specifications for further details.
The default margin is set to 25% for both long and short positions.
Users can adjust the margin for long and short positions independently via strategy Settings/Properties/MARGIN.
For further information on the strategy tester's margin functionality, please refer to:
www.tradingview.com
www.tradingview.com
Pyramiding
The pyramiding count is defined as the maximum number of open positions permitted at any one time. TradingView's strategy tester does not facilitate hedging, as such, long entries will close any open short positions and short entries will close any open long positions.
The default pyramiding count is set to 100.
Users can adjust the pyramiding count via strategy Settings/Properties.
For further information on TradingView's strategy tester and broker emulator, please refer to:
www.tradingview.com
Spread
The spread is defined as the difference between a given symbol's bid (buy) price and ask (sell) price.
Typical spreads vary by broker and symbol. Some brokers offer fixed spreads on certain symbols, while others offer variable spreads that fluctuate with market conditions. Users should consult their broker's published specifications for further details.
Commission
The commission is defined as a transaction cost applied by a broker and may be expressed as a percentage of position size, a per-contract fee or a fixed fee per-transaction.
Commission structures vary by broker and symbol. Some brokers charge no explicit commission and instead generate revenue through the spread or other indirect sources, while others will typically apply one of the three aforementioned commission types, depending on the product offered. Users should consult their broker's published specifications for further details.
The default commission is set to 0.005% of position size.
Users can select and adjust the commission type via strategy Settings/Properties/COST SIMULATION.
█ CORE STRATEGY
Green and Red Candles
A green candle is defined as a candle that closes at or above its open price and a red candle is defined as a candle that closes below its open price.
Swing Highs and Swing Lows
A swing high is defined as a green candle, or a series of consecutive green candles, followed by a single red candle that completes the swing and forms the peak.
A swing low is defined as a red candle, or a series of consecutive red candles, followed by a single green candle that completes the swing and forms the trough.
Peak and Trough Prices
The peak price of a complete swing high is either the high of the red candle that completes the swing high or the high of the preceding green candle, depending on which is higher.
The trough price of a complete swing low is either the low of the green candle that completes the swing low or the low of the preceding red candle, depending on which is lower.
Fixed Reward-to-Risk
Fixed reward-to-risk is defined as a user-defined reward multiple for a given unit of risk.
Variable Reward-to-Risk
Variable reward-to-risk is defined as a path-dependent reward multiple for a given unit of risk.
Swing High Swing Low (SHSL) Strategy
The SHSL strategy uses swing lows for core long entry conditions and swing highs for core short entry conditions. The strategy is designed for standard OHLC candlestick charts only and will not behave as intended on other chart types.
All entries are processed at candle close and use the candle close price for the entry price.
Long stop losses are anchored to the most recent trough and short stop losses are anchored to the most recent peak.
Users can choose between long-only and short-only configurations, or alternatively simulate trades in both directions (long-short). However, when the "Both" option is selected, long entries will close any open short positions and short entries will close any open long positions (as mentioned in the pyramiding sub-section above). This can and will result in variable reward-to-risk outcomes.
The default direction is set to "Long" for a long-only configuration.
The default exit type is set to "Target" for a fixed reward-to-risk configuration.
Long targets are determined by adding a user-defined multiple of the risk range to the entry price and short targets are determined by subtracting a user-defined multiple of the risk range from the entry price.
Even when using a fixed reward-to-risk configuration, realised reward-to-risk outcomes may vary due to market gaps, particularly when positions are held across session boundaries or market closures. Gaps can cause stop losses or exits to be executed at prices materially different from those implied by the strategy’s static distance calculations. Users who wish to minimise gap-related variability may consider applying the close at end of session filter (see core filters section below), accepting that this introduces its own form of reward-to-risk variability.
The default reward-to-risk is set to 1.
Users can adjust strategy parameters via strategy Settings/Inputs/STRATEGY. Selecting a non-target exit type removes profit targets and renders the reward-to-risk input inactive.
Trailing Stop Loss
A trailing stop loss is defined as an exit type that dynamically moves a stop loss level in a favourable direction when a predefined condition is met. For example, a predefined point move or the formation of a higher trough or lower peak.
Risk Range Trailing Stop Loss
The risk range trailing stop loss is defined as a trailing stop mechanism that activates once price has moved favourably by one full risk range. Upon activation, the stop loss is moved to breakeven and subsequently trails favourable price movement by the risk range into profit.
Users can apply this exit type by selecting "Trail" via strategy Settings/Inputs/STRATEGY.
Trend Trailing Stop Loss
The trend trailing stop loss is defined as a trailing stop mechanism that dynamically moves a stop loss level to newly formed higher troughs (for longs) or lower peaks (for shorts).
Users can apply this exit type by selecting "Trend Trail" via strategy Settings/Inputs/STRATEGY.
Candle Trailing Stop Loss
The candle trailing stop loss is defined as a trailing stop mechanism that dynamically moves a stop loss level to newly formed higher candle lows (for longs) or lower candle highs (for shorts).
Users can apply this exit type by selecting "Candle Trail" via strategy Settings/Inputs/STRATEGY.
Opposing Candle Colour Close
The opposing candle colour close exit type is defined as an exit condition that closes any long positions when a new red candle forms and closes any short positions when a new green candle forms.
Users can apply this exit type by selecting "Opposing Candle" via strategy Settings/Inputs/STRATEGY.
█ CORE FILTERS
Minimum Risk Range Filter
The minimum risk range filter is defined as an entry filter that invalidates trade signals with a risk range below a user-defined threshold.
The default minimum risk range is set to 4 points/pips.
Users can adjust the minimum risk range via strategy Settings/Inputs/RISK RANGE FILTER.
It is recommended that users set the minimum risk range at least 1–2 points/pips above the selected symbol’s spread to invalidate trades that would be completely impractical under realistic trading conditions.
Time Zone
The time zone is defined using either an IANA region identifier (e.g. Europe/London, America/New_York) or a fixed UTC/GMT offset (e.g. UTC+1, GMT-05:30). Fixed offsets do not account for daylight saving time.
The default time zone is set to Europe/London.
Users can change the time zone via strategy Settings/Inputs/TIME ZONE.
For further information on time zone configuration, please refer to:
data.iana.org
en.wikipedia.org
Session Filter
The session filter is defined as an entry filter that invalidates trade signals that fall outside a user-defined intraday trading session, with session start and end times bound to the strategy time zone.
TradingView candle timestamps represent the candle open time, not the candle close time. As a result, session boundaries are evaluated based on when a candle opens, even though entries and exits are processed at candle close.
To avoid trades being entered or held beyond the intended session end, users should configure the session end time at least one full timeframe period earlier than the desired practical session close. For example, on a 5-minute chart with a desired session end at 22:00, the session should typically be configured to end at 21:55. This ensures that no new trades are taken at the final session close and that any session-dependent exit logic is applied before the session ends in practice.
When using custom or non-standard timeframes where the desired session end does not align cleanly with candle boundaries, it is recommended that users set the session end two full timeframe periods earlier than the desired session end. This provides an additional safety buffer, ensuring the strategy avoids taking trades near the session boundary.
By default, the session filter is set to false and the default session is set to "2300-2155".
Users can apply the session filter and adjust session boundaries via strategy Settings/Inputs/SESSION FILTER.
Close At End of Session Filter
The close at end of session filter is defined as an exit filter that closes all open positions when the active trading session ends, provided that the session filter is appropriately configured and applied.
When enabled, the strategy monitors the session filter state and detects the transition from an active session to an inactive session. All open trades are closed on the first candle that falls outside the defined session window. This ensures that no positions are carried beyond the user-defined trading session.
The close at end of session filter operates independently of entry conditions and other exit types. When enabled, it will force the closure of all open positions at session end regardless of the selected exit configuration.
Enabling the close at end of session filter can result in variable reward-to-risk outcomes. Because positions are forcibly closed at session end regardless of stop loss or target placement, exits may occur at prices that differ from those implied by the fixed reward-to-risk configuration. This behaviour is intentional and reflects a design trade-off between enforcing strict session boundaries and allowing trades to reach their predefined directional objectives, regardless of how severely distorted the realised reward-to-risk outcomes could be in the event of price gaps.
By default, the close at end of session filter is set to false.
Users can apply the close at end of session filter via strategy Settings/Inputs/CLOSE AT END OF SESSION FILTER.
Users should also ensure that the session filter is applied and that session boundaries are configured appropriately with respect to candle timestamp behaviour, as described in the session filter section above.
Sample Period Filter
The sample period filter is defined as an entry filter that invalidates trade signals that fall outside a user-defined date-time range, with start and end date-times bound to the strategy time zone.
TradingView candle timestamps represent the candle open time, not the candle close time. As a result, sample period boundaries are evaluated based on when a candle opens, even though entries and exits are processed at candle close.
To avoid trades being entered beyond the intended sample period end, users should configure the sample period end date-time at least one full timeframe period earlier than the desired practical sample period end date-time. For example, on a 5-minute chart with a desired end date-time of 01/01/2026 22:00, the end date-time should typically be configured to 01/01/2026 21:55.
The default sample period start and end date-times are set to 01/01/1900 00:00 and 01/01/3000 00:00, respectively.
Users can adjust the sample period via strategy Settings/Inputs/SAMPLE PERIOD FILTER.
█ GENERIC FILTERS
Generic Filter Behaviour
Unless otherwise stated:
"None" inputs return true.
Filters return true only when their selected condition is satisfied.
Close Above-Equal/Below Filter
The close price above-equal/below filter is defined as an entry filter that evaluates the most recent candle close price relative to a given time-series value and invalidates trade signals that do not satisfy a user-defined directional condition.
"Above-Equal" returns true when the most recent candle close price is greater than or equal to any given time-series value.
"Below" returns true when the most recent candle close price is less than any given time-series value.
Minimum and Maximum Boundary Filters
Minimum and maximum boundary filters are defined as entry filters used to constrain time-series values to predefined minimum and/or maximum thresholds, invalidating trade signals that do not satisfy a user-defined threshold criteria. The filters consist of two independent threshold components, minimum (above-equal) and maximum (below-equal), which may be applied individually or together.
When both components are applied simultaneously the filters act as a value range constraint, invalidating trade signals that fall outside of the specified bounds.
"Above-Equal" returns true when the evaluated value is greater than or equal to the user-defined minimum boundary.
"Below-Equal" returns true when the evaluated value is less than or equal to the user-defined maximum boundary.
Minimum Percentage Change Positive-Flat/Negative Filter
The minimum percentage change filter is an entry filter that measures the relative change of a time-series value over a configurable historical window and applies a directional threshold condition, invalidating trade signals that do not meet the directional threshold criteria.
The filter compares the current value to its value n bars ago and computes the percentage difference. A signal returns true only if this percentage change satisfies both:
The selected directional requirement.
The user-defined minimum percentage change magnitude.
"Positive-Flat" direction logic:
Accepts values that have increased or remained unchanged, provided the percentage change is greater than or equal to the minimum threshold.
"Negative" direction logic:
Accepts values that have decreased, provided the magnitude of the decrease meets or exceeds the minimum threshold.
When the minimum threshold is set to 0%, the filter behaves as a pure directional check:
"Positive-Flat" accepts ≥ 0% changes.
"Negative" accepts < 0% changes only.
Basic and Exclusive Rejection Filters
The basic rejection filter is defined as an entry filter that evaluates swing-based wick or body rejections of a given price level and invalidates trade signals that do not satisfy the rejection criteria.
For long trades, "Rejection" returns true when all three of the following conditions are met:
The previous candle open is above a given rejection price.
The trough price is less than or equal to a given rejection price.
The green candle that completes the swing closes above a given rejection price.
For short trades, "Rejection" returns true when all three of the following conditions are met:
The previous candle open is below a given rejection price.
The peak price is greater than or equal to a given rejection price.
The red candle that completes the swing closes below a given rejection price.
The exclusive rejection filter is defined as an entry filter that meets basic rejection filter criteria for only one user-defined price level from a set of given price levels. If the rejection criteria is met for more than one of the given price levels the filter will return false.
Basic and Multi-Part Trend Filters
Basic and multi-part trend filters are defined as entry filters that evaluate changes in time-series values from one period to the next and invalidate trade signals that do not satisfy a user-defined trend condition.
Basic trends operate independently of prior trend state, whereas multi-part trends are defined by the presence or absence of preceding trend sequences. The multi-part trend states are distinguished numerically and the conditions are bound to a user-defined trend count.
"Basic Uptrend" returns true when a time-series value is greater than the preceding value. For example, a basic volume uptrend filter returns true if the most recent candle's volume is greater than the preceding candle's volume.
"Basic Downtrend" returns true when a time-series value is less than the preceding value. For example, a basic volume downtrend filter returns true if the most recent candle's volume is less than the preceding candle's volume.
"Uptrend" returns true while a multi-part uptrend state is valid. The uptrend state begins when a new basic uptrend forms following a basic downtrend and remains valid until a new basic downtrend forms. The user-defined trend count will determine which multi-part trend condition is selected. For example, if the user-defined trend count is set to 3, then only 3-part uptrend conditions will return true.
"Downtrend" returns true while a multi-part downtrend state is valid. The downtrend state begins when a new basic downtrend forms following a basic uptrend and remains valid until a new basic uptrend forms. The user-defined trend count will determine which multi-part trend condition is selected. For example, if the user-defined trend count is set to 3, then only 3-part downtrend conditions will return true.
█ FEATURE SET V SPECIFIC FILTERS
All feature set specific indicators use the same calculations as the built-in TradingView indicators unless otherwise stated in the relevant filter sub-section. While users do not need to apply the indicators for the strategy to function, they can of course apply the relevant indicators as visual aids if they so desire.
For further information on how to apply built-in TradingView indicators, please refer to:
www.tradingview.com
As there are no built-in TradingView indicators for the VHF, VWAP and VZO values used in this script, code samples are provided in the relevant sections so that users can build their own Pine Script indicators.
For further information on how to build Pine Script indicators, please refer to:
www.tradingview.com
www.tradingview.com
Vertical Horizontal Filter (VHF) Filters
As there is no built-in indicator for the VHF value used in this script, users can build their own VHF indicator in Pine Script by copying the following code and pasting it into a new indicator:
//@version=6
indicator(title = "Vertical Horizontal Filter", shorttitle = "VHF", overlay = false)
import TradingView/ta/12 as ta
vhf_source = input.source(defval = close, title = 'VHF Source', group = 'Vertical Horizontal Filter (VHF)')
vhf_length = input.int(defval = 28, minval = 1, title = 'VHF Length', group = 'Vertical Horizontal Filter (VHF)')
vhf = ta.vhf(vhf_source, vhf_length)
plot(vhf, color = color.blue)
The VHF defaults are as follows:
Source is set to "Close".
Length is set to 28.
Users can adjust the VHF inputs via strategy Settings/Inputs/VERTICAL HORIZONTAL FILTER (VHF).
The VHF minimum and maximum boundary filter (see generic filters section above) defaults are as follows:
Apply VHF above-equal is set to false.
VHF above-equal threshold is set to 0.0.
Apply VHF below-equal is set to false.
VHF below-equal threshold is set to 1.0.
The VHF minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The VHF trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the VHF filters and adjust filter parameters via strategy Settings/Inputs/VHF FILTERS.
Volume Filters
The Volume minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The Volume trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the Volume filters and adjust filter parameters via strategy Settings/Inputs/VOLUME FILTERS.
Positive Volume Index (PVI) Filters
The PVI minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The PVI trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the PVI filters and adjust filter parameters via strategy Settings/Inputs/POSITIVE VOLUME INDEX (PVI) FILTERS.
Negative Volume Index (NVI) Filters
The NVI minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The NVI trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the NVI filters and adjust filter parameters via strategy Settings/Inputs/NEGATIVE VOLUME INDEX (NVI) FILTERS.
On-Balance Volume (OBV) Filters
The OBV minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The OBV trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the OBV filters and adjust filter parameters via strategy Settings/Inputs/ON-BALANCE VOLUME (OBV) FILTERS.
Price Volume Trend (PVT) Filters
The PVT minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The PVT trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the PVT filters and adjust filter parameters via strategy Settings/Inputs/PRICE VOLUME TREND (PVT) FILTERS.
Volume Weighted Average Price (VWAP) Filters
Although there is a built-in VWAP indicator, its output may differ from the calculation used in this script. As such, it is recommended that users build their own VWAP indicator in Pine Script by copying the following code and pasting it into a new indicator:
//@version=6
indicator(title = "Volume Weighted Average Price", shorttitle = "VWAP", overlay = false)
vwap_source = input.source(title = 'VWAP Source', defval = hlc3, group = 'Volume Weighted Average Price (VWAP)')
vwap_anchor = input.bool(title = 'VWAP Anchor', defval = true, group = 'Volume Weighted Average Price (VWAP)')
vwap = ta.vwap(vwap_source, vwap_anchor)
plot(vwap, color = color.blue)
The VWAP indicator defaults are as follows:
Source is set to "HLC3".
Anchor is set to true.
Users can adjust the VWAP inputs via strategy Settings/Inputs/VOLUME WEIGHTED AVERAGE PRICE (VWAP).
The default mode for the close above-equal/below VWAP filter (see generic filters section above) is set to "None".
The default mode for the VWAP rejection filter (see generic filters section above) is set to "None".
Users can apply the VWAP filters and adjust filter parameters via strategy Settings/Inputs/VWAP FILTERS.
Volume Zone Oscillator (VZO) Filters
As there is no built-in indicator for the VZO value used in this script, users can build their own VZO indicator in Pine Script by copying the following code and pasting it into a new indicator:
//@version=6
indicator(title = "Volume Zone Oscillator", shorttitle = "VZO", overlay = false)
import TradingView/ta/12 as ta
vzo_length = input.int(defval = 14, minval = 1, title = 'VZO Length', group = 'Volume Zone Oscillator (VZO)')
vzo = ta.vzo(vzo_length)
plot(vzo, color = color.blue)
The default length for the VZO is set to 14.
Users can adjust the VZO length via strategy Settings/Inputs/VOLUME ZONE OSCILLATOR (VZO).
The VZO minimum and maximum boundary filter (see generic filters section above) defaults are as follows:
Apply VZO above-equal is set to false.
VZO above-equal threshold is set to -100.
Apply VZO below-equal is set to false.
VZO below-equal threshold is set to 100.
The VZO minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The VZO trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the VZO filters and adjust filter parameters via strategy Settings/Inputs/VZO FILTERS.
Vortex Indicator (VI) Filters
The default length for the VI is set to 14.
Users can adjust the VI length via strategy Settings/Inputs/VORTEX INDICATOR (VI).
The VI above-equal/below VI signal filter is defined as an entry filter that evaluates the relative positioning of the VI value and its signal line and invalidates trade signals that do not satisfy a user-defined directional condition.
The default mode for the VI above-equal/below VI signal filter is set to "None".
The VI bandwidth increasing/decreasing filter is defined as an entry filter that evaluates whether the distance between the VI line and VI signal line is expanding or contracting over a configurable lookback period.
The default VI bandwidth increasing/decreasing filter mode is set to "None".
The default VI bandwidth increasing/decreasing lookback is set to 3.
The VI minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The VI signal minimum percent change positive-flat/negative filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Minimum percent change is set to 0.
Lookback is set to 3.
The VI trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
The VI signal trend filter (see generic filters section above) defaults are as follows:
Mode is set to "None".
Trend count is set to 3.
Users can apply the VI filters and adjust filter parameters via strategy Settings/Inputs/VI FILTERS.
█ ALERTS
Users can set alerts for any given strategy configuration via the alerts dialogue box.
Users must first ensure that the correct condition (the strategy title) is selected from the first drop-down list in the alert dialogue box's condition field.
Default alert messages have been configured for both entries and exits so that users can more effectively distinguish between long and short entries and exits while using long-short configurations.
To get alerts for both entries and exits the user should change the value in the condition field's second drop-down list from "Order fills only and alert() function calls" to "Order fills only". When using "Order fills only" with long-short configurations, it is recommended that users define their alert via the alert name field and use only the default {{strategy.order.alert_message}} call in the alert message field.
Alert conditions generated by "Order fills only" are evaluated after entry conditions have been satisfied and operational constraints (risk, position size and margin requirements) have been applied. As such, trade signals that would result in position sizes exceeding the simulated account's margin constraints will not generate alerts.
To get alerts for entries only the user should change the value in the condition field's second drop-down list from "Order fills only and alert() function calls" to "alert() function calls only".
The default alert messages generated by "Order fills only" are as follows:
"long entry".
"long exit".
"short entry".
"short exit".
The default alert messages generated by "alert() function calls only" are as follows:
"long entry".
"short entry".
Alert conditions generated by "alert() function calls only" are operational-constraint-agnostic and will generate alerts whenever entry conditions are satisfied, regardless of the simulated account's margin constraints.
For further information on setting and managing alerts, please refer to:
www.tradingview.com
www.tradingview.com
www.tradingview.com
█ LIMITATIONS AND CONSIDERATIONS
Backtesting
Backtest results should always be interpreted cautiously. Strategy performance can vary significantly across time periods and sample sets. While strong historical performance does not guarantee future results, poor historical performance reliably indicates a weak strategy when sample sizes are statistically meaningful.
Statistical Significance and Path-Dependent Outcomes (Overfitting)
In statistical practice, sample sizes of 100 observations are sometimes cited as a rough lower bound for certain forms of basic significance testing. In the context of trading strategy evaluation, such sample sizes are rarely sufficient to produce results that are meaningfully reliable or replicable. Based on practical experience, sample sizes closer to 1,000 observations or more are generally required before performance characteristics begin to stabilise. As a general rule, larger sample sizes increase the reliability and replicability of observed results.
Path dependence refers to situations in which outcomes are determined not only by initial conditions, but by the specific and unique sequence of price movements over a given time period.
Even with large sample sizes, favourable net profit outcomes should be interpreted with caution when they are primarily driven by either variable reward-to-risk configurations or fixed reward-to-risk configurations that employ unrealistically high reward multiples. In both cases, performance is often strongly influenced by path-dependent effects, making such outcomes less reliable and less replicable.
Fixed reward-to-risk configurations are generally less susceptible to path dependence when the reward multiple is kept within reasonable bounds. However, empirical studies and practitioner research suggest that reward multiples above approximately 3:1 increasingly exhibit the same path-dependent characteristics observed in variable reward-to-risk strategies.
Bar Magnifier
Due to the limitations of OHLC data, intra-bar price movement cannot be precisely determined.
When both stop loss and target levels are reached within the same candle, assumptions are made by the strategy tester.
Pine Script's bar magnifier partially mitigates this limitation by evaluating lower-timeframe data. However, this feature is available only to TradingView Premium users and remains inherently limited.
For further information on the bar magnifier functionality, please refer to:
www.tradingview.com
www.tradingview.com
TradingView Premium users can enable bar magnifier via strategy Settings/Properties/FILL ORDERS.
Processing Orders at Candle Close
Backtests cannot accurately account for slippage between signal generation and trade execution.
A practical mitigation is to use fixed-distance stop losses and targets rather than absolute price levels, a feature supported by many brokers and APIs.
Empirical Probabilities
Empirical probabilities are derived directly from observed outcomes rather than from theoretical models or assumed distributions. In the context of trading, they are calculated by measuring the relative frequency of events (such as wins and losses) across a large sample of historical trades.
Unlike conditional or model-based probabilities, empirical probabilities make no assumptions. Their validity relies primarily on sample size and the consistency of the rules used to generate observations, making them particularly relevant for trading systems evaluated under the law of large numbers.
Empirical probabilities are most useful for comparative analysis, such as assessing how different configurations, filters or exit mechanisms alter the statistical behaviour of a strategy under identical conditions. They are not intended to represent true predictive probabilities or to imply stable future performance.
To study empirical probabilities for comparative purposes, it is recommended that users set commission and both long and short margin values to 0% in order to maximise sample size. However, users should not interpret any resulting profits as realistic. Setting commission and margin (in particular) to 0% produces highly distorted outcomes that are not representative of realistic live trading conditions.
█ DISCLAIMER
This Pine Script strategy is provided for educational purposes only and does not constitute financial advice in any form.
Pine Script® ストラテジー
LBR Quant Finance Regime StrategyLinda Braodford Raschke Quant Finance Regime Strategy
This strategy implements a regime-based trading framework that adapts between trend-following and mean-reversion logic depending on current market conditions.
It is designed for research and educational purposes and does not guarantee performance.
Core Concept
Markets alternate between:
• Expansion phases (trending)
• Contraction phases (ranging)
This strategy attempts to detect regime shifts using:
ADX for trend strength
Bollinger Band width for volatility expansion
EMA(200) for structural trend bias
When volatility and directional strength expand, the strategy uses trend-following entries.
When volatility contracts, it shifts to mean-reversion logic.
Entry Logic
Trend Regime
Conditions:
ADX above threshold
Bollinger width above average
Supertrend alignment
EMA trend confirmation
MACD momentum confirmation
Range Regime
Conditions:
ADX below threshold
Bollinger width contracting
RSI extreme levels
Price at outer Bollinger bands
Risk Management
Position sizing:
8% of equity per trade (default)
No pyramiding
Exits:
ATR-based stop loss
ATR-based take profit
ATR-activated trailing stop
Global controls:
Max strategy drawdown filter (default 25%)
Daily equity loss guardrail (default 5%)
If limits are exceeded, new trades are disabled.
Default Strategy Properties
Initial Capital: 100,000
Order Size: 8% of equity
Commission: 0.06%
Slippage: 2 ticks
Pyramiding: 0
Orders processed on close
These settings are used in the published version.
Backtesting Guidance
• Use on liquid instruments
• Test over long historical periods
• Ensure sufficient trade sample size (100+ trades recommended)
• Adjust regime thresholds carefully
No future-looking data is used.
Results will vary by asset and timeframe.
Chart Notes
The background color shows regime detection:
Green tint → trending
Blue tint → ranging
EMA line shows structural bias.
No additional scripts are required.
Important
Past performance does not predict future results.
Pine Script® ストラテジー






















