Quality-Controlled Trend Strategy v2 (Expectancy Focused)This script focuses on quality control rather than curve-fitting.
No repainting, no intrabar tricks, no fake equity curves.
It uses confirmed-bar entries, ATR-based risk, and clean trend logic so backtests reflect what could actually be traded live.
If you publish scripts, this is the minimum structure worth sharing.
Why this script exists
TradingView’s public scripts are flooded with:
repainting indicators
no stop-loss logic
curve-fit entries that collapse live
strategies that look good only in hindsight
This script is intentionally boring but honest.
No repainting.
No intrabar tricks.
No fake equity curves
The goal is quality control, not hype.
What this strategy enforces
✔ Confirmed bars only
✔ Single source of truth for indicators
✔ Fixed risk structure
✔ No signal repainting
✔ Clean exits with unique IDs
✔ Works on any liquid market
Trading Logic (simple & auditable)
Trend filter
EMA 50 vs EMA 200
Entry
Pullback to EMA 50
RSI confirms momentum (not oversold/overbought)
Risk
ATR-based stop
Fixed R:R
One position at a time
This is the minimum bar for a strategy to be considered publish-worthy.
Why this helps TradingView quality
Most low-value scripts fail because they:
hide repainting logic
skip exits entirely
use inconsistent calculations
rely on hindsight candles
This strategy forces discipline:
every signal is confirmed
every trade has defined risk
behavior is repeatable across symbols & timeframes
If more scripts followed this baseline, TradingView’s public library would be far more usable.
Strategy!
To Capture Indian Option Buying By VJha Can be automated)Specially meant for Indian market Option buying capitalising on morning momentum through algo trading. Works best on 1 min timeframe. Key highlights are:
(1) In setting set timing of your session preferably 09:15 to 11:30, entry only during this duration, running trade forced closed at end of set session.
(2) Choose fresh or continuation: if continuation is chosen, if yesterday's condition prevails during open entry will be made. If fresh is chosen, entry will be made only if fresh set up is formed
(3) You can set this indicator either on index or directly on call or put. If set on Index then buy means buy for call, sell means exit of call. Sell means buy entry for Put and buy means exit for put. However, if directly on call or put, it is straight.
(4) Choice of pivot bar number as 1 gives more trades with smaller profit. Choice of 2 lesser trades with running profit.
Backtest Pro - The TradingView Backtesting EngineBacktest your indicators — no strategy code required. Backtest Pro is the next-generation backtesting engine for smarter testing. Simply link your signals, set your stops, and start testing.
With its upgraded UI/UX and fundamentally improved stop system, Backtest Pro replaces the legacy PSE (Practical Strategy Engine) and sets a new standard for TradingView backtesting. It delivers more accurate intrabar trailing stops, flexible stop types (Points, ATR Multiplier, %), and a smoother workflow for greater precision and control.
Once loaded on your chart, Backtest Pro appears as BT Pro as the script title and in the Strategy Tester, alerts, and chart labels.
Beyond the core stop and pyramiding logic, Backtest Pro also introduces:
A clearer Data Window for reviewing trade details.
Improved signal labels in the Strategy Tester’s List of Trades for easier log analysis.
Updated chart labels that align better with TradingView’s native style and make signals easy to interpret. Together, these improvements make Backtest Pro the most practical and user-friendly way to backtest indicator-based trading signals in TradingView.
Copyright © 2025 CoinOperator
________________________________________________________________________________
🚀 Why Traders Choose Backtest Pro
Answer in minutes what used to take days of manual testing.
Backtest Pro is a drop-in, ready-to-use backtesting engine that links to your indicator with just a few simple connection lines. It provides more accurate intrabar trailing stops, multiple stop types (Points, ATR Multiplier, %), and a smoother workflow for greater precision and control.
Whether you’re running a quick test or fine-tuning complex strategies, Backtest Pro helps you reach clearer insights faster.
________________________________________________________________________________
👤 Who Backtest Pro Is For
Backtest Pro is designed for traders who already have a trading methodology or entry/exit logic and want professional-grade validation and risk analysis.
Backtest Pro is not a signal service and does not provide discretionary trade recommendations. All entries and exits — including alerts used for automation — are generated solely from user-defined logic.
You bring the logic — Backtest Pro provides the structure, metrics, and discipline.
Backtest Pro helps swing traders, day traders, and strategy developers streamline the backtesting process without sacrificing depth or accuracy. It offers flexible stop management, enhanced Data Window metrics, refined Strategy Tester labeling, and clean on-chart visuals to support consistent evaluation.
Backtest Pro supports trading and backtesting on futures (continuous contracts), forex, crypto, stocks, ETFs, and commodity/index CFDs (tradable if offered by your broker).
________________________________________________________________________________
⚡ Quick Start
Add Backtest Pro to your chart. It appears as BT Pro as the script title and in the Strategy Tester, alerts, and chart labels.
Add a few connector lines to your indicator, then link your custom entry and exit signals.
Adjust position sizing, stops, and pyramiding.
Run the TradingView Strategy Tester for instant results.
________________________________________________________________________________
🔄 From PSE to Backtest Pro
Backtest Pro builds on the foundation of the PSE (Practical Strategy Engine), evolving it into a more refined tool. While PSE introduced flexible stop handling, Backtest Pro enhances the experience with:
More accurate intrabar trailing stops
Expanded stop type options (Points, ATR Multiplier, %)
Upgraded Data Window for easier review
Clearer trade signals in the Strategy Tester
Cleaner, more consistent chart labels
Wash Sale Prevention is Now Optional. If enabled, it only applies to assets of types stock and fund.
🛠 INPUTS TAB SETTING
📅 Trading Window
Enable Trading Window to define the date/time when trading is allowed. Disable to trade the entire market data.
Partition the time when trading is allowed to see if your indicator settings work well across the different ranges. Your resulting metrics should be acceptable across all four (4) ranges: entire range, 1st half, IQR, and 2nd half.
Show Trading Window Lines – Enable to draw vertical lines at the start and end of the trading window for clear visual definition of when trading is allowed.
💰 Position Sizing (Money Management)
Separating the equity risk into initial position and pyramid position allows for greater ability to maximize profits within your acceptable drawdown.
Note : Position sizing is determined on the anticipated fill price which is affected by the maximum of slippage and selected price gap (discussed in the Execution Rules section). Max Equity per Position (%) : This setting applies to each position within a trade group . Limits the position size and will not exceed this amount. Set as desired. Default is 20% for non-leverage trading. For leveraged trading, adjust accordingly. Example: for 3× leverage, enter 300 (3 × 100 = 300).
Max Equity Drawdown Warning (%) : Triggers an alert if the strategy’s equity drawdown exceeds this threshold. Select the method to use for this warning. If BT Pro, then it is based on peak equity at bar-close. If TradingView, then it is based on the built-in variable strategy.max_drawdown_percent. Helps you manage strategy-level risk tolerance.
Scaled Pyramiding : Adjusts position size incrementally for each pyramid entry—either decreasing or increasing exposure relative to the prior entry.
Start Position: The entry number at which scaling begins. For example, 3 means scaling starts on the 2nd pyramid (the 3rd entry overall).
Chg(%): The percentage change applied to each subsequent pyramid entry.
Max(%): The maximum cumulative reduction allowed when scaling downward. Ignored for upward scaling because increases are already capped by Max Equity per Position (%).
⚖️ Execution Rules
Trade Direction : Select either Both , Long Only, or Short Only.
Alert Failed to Trade – Enable to alert you when a trade did not happen due to low equity or low order size. Applicable only for the first position of a trade group.
Cooldown Period : Controls how long the engine waits after an exit before allowing a new trade group. Backtest Pro also applies a small built-in safeguard to prevent unrealistic same-bar flips: ● 1 bar minimum for same-direction entries
● 2 bars minimum for direction changes
Prevent Wash Sales : Enable if you want the Backtest Pro to enforce a minimum cooldown period of 30 days for trade groups that result in a loss. Only applies to assets of types stock and fund.
Pyramid Conditions with Price Gaps : Dwn Gap and Up Gap refer to price gaps. A price gap is the difference between the closing price of the previous candle and the opening price of the current candle, and their value is shown in the Data Window. Selection options include: disabled (the default), median, avg, p80 (for 80th percentile), and p90 (for 90th percentile). The values reflect ~500 most recent bars from the cursor position. Disabled sets the Dwn Gap and Up Gap to zero in the below logic. Pyramids require a tailing stop loss, TSL. The price gaps are used in conditions for pyramids:
To ensure the previous position is protected when opening a pyramid position. A new pyramid position will not open until its trailing stop loss protects the prior position.
To prevent a pyramid position from becoming a loss when too close to a take profit level, TP (if enabled), due to commission cost.
The logic for #1 and #2 is as follows:
For a Long Pyramid: TSL: Stop Price - max(DwnGap, slippage) > LastEntryPrice
TP (if enabled): Long take profit > close + max(UpGap, slippage) AND gain > commission cost
For a Short Pyramid:
TSL: Stop Price + max(UpGap, slippage) < LastEntryPrice
TP (if enabled): Short take profit < close - max(DwnGap, slippage) AND gain > commission cost
Show All Gap Stats in Data Window
Enable to show all price gap statistics in the Data Window to review market conditions.
Disable for the Backtest Pro to run most efficiently.
Note: Statistics selected in Dwn Gap and Up Gap settings are always shown, regardless of this option.
🛑 Exit Strategy (Risk Management)
Backtest Pro supports multiple stop loss styles, giving traders the tools to backtest strategies in TradingView with precision:
The Exit Strategy applies a common protective stop across the entire trade group.
Pyramids require a trailing stop loss. A new pyramid position will not open until its trailing stop loss protects the prior position.
Plot Stop Level : You can plot the stop level either as of bar close (the default) or as of bar open. This only affects the visual plot. The underlying logic does not change. The trades will be the same regardless of the setting.
ATR Length : The ATR Length is used with the ATR multiplier and is common to stop loss, SL, trailing stop loss, TSL, take profit, TP, and the time-based exit option. It is the number of bars (periods) used in ATR calculation.
Price-Based Exits Stop Loss and Trailing Stop Loss options are Points, ATR Multiplier, and %.
The Trailing Stop Loss is activated from entry of the initial position of a trade group.
Take Profit options are Points, ATR Multiplier, %, and R-Multiple. How Trailing Stops Work in the Backtest Pro All trailing stop inputs (Points, ATR Multiplier, or %) are converted at the first entry into a fixed currency offset.
That offset is reactive intrabar and applied as the trailing distance from the most favorable price (highest for longs, lowest for shorts) since the first entry in the trade group.
Even if “%” is selected as the input method, the engine uses the fixed currency offset.
The trailing stop offset (points) is displayed in the Data Window for reference, allowing you to enter that offset directly at your broker if needed.
⚠️ Caution: Always enter a points-based trailing stop at your broker—never a percentage-based trailing stop. Volatility-Based Exit While in a trade, ATR values are accumulated each bar. The position exits once the total exceeds ATR Multiplier × ATR at entry if the Reward/Risk is below the set threshold.
Dividends are not included in reward (i.e., profit).
👉 These flexible stop types solve one of the biggest limitations of the legacy PSE and make Backtest Pro a true TradingView backtesting engine.
📑 Trade Signal Labels in Strategy Tester
Backtest Pro uses standardized trade labels in the Strategy Tester → List of Trades. These labels make it easy to understand the reason behind each entry or exit at a glance. Entry : Standard entry signal when conditions are met.
Stop : Stop-loss exit triggered at your defined stop level.
Pyr-Entry : Pyramid entry, adds to an existing position.
Trail-Stop : Trailing stop exit based on offset logic. Note : If the stop level has been adjusted to equal the trailing stop level, the Strategy Tester may display Stop instead of Trail-Stop. The exit displayed is the one Pine Script evaluates first, but the actual exit behavior remains correct.
Exit : Standard exit signal.
Delay-Exit : One-bar delayed exit, prevents immediate exit when position entry and exit signal occur on the same bar.
TP : Take Profit exit, closes position at your profit target.
RR-Exit : Reward/Risk exit — position closes when ATR accumulation exceeds the set threshold and R/R is below target.
📊 Performance Metrics & Reporting
Include Dividends in Profit
Adjusts ROI, CAGR, Reward/Risk, Avg Invest/Trade-Grp, and Equity.
Assumes dividends are taken as cash (not reinvested). They are applied to Equity on the ex-date instead of the payment date.
Only applies if the security issues dividends and the chart is 1D or lower timeframe; otherwise ignored.
Include Dividends in Profit Factor
Applies only when Include Dividends in Profit is enabled.
Adds dividend income to both gross profits and gross losses when calculating Profit Factor, so PF reflects total return (trading + dividends).
Affects Avg Trade-Grp Loss, Equity Loss from ECL, and Equity Loss from ECL (%).
Show Dividends
Displays the payout in currency/share, as well as the total amount based on the number of shares of the position(s) currently held by the trade group. For long positions you earned the dividends. For short positions you owe the dividends.
Show Metrics Table
The on-chart Metrics Table displays a compact set of key statistics for quick reference and mobile use. Full and expanded metrics are available in the Data Window on desktop or browser. Section groupings may differ between the table and Data Window to optimize readability and presentation in each context.
📊 Data Window
Note : Accessible via a button on the right-hand toolbar of the chart interface. Unlike the Metrics Table, Data Window values update dynamically as you move your cursor across bars. All metrics are based on trade groups.
Trade Information
Enter Price
Stop Price
Favorable Extreme : only shows if trailing stop loss is enabled on Inputs tab. The most favorable price (highest for longs, lowest for shorts) since the first entry in the trade group.
TSL Offset Points : only shows if trailing stop loss is enabled on Inputs tab.
Take Profit : only shows if take profit is enabled on Inputs tab.
Leverage information applies to trade groups.
Fail Pos / Margin (%) : Shows zero if the failed position size was <1, or the margin % that failed to meet the requirement in the Properties tab. A flag appears above the bar where a failed trade occurred. Only applies to the first position of a trade group. Hover over the flag to view the value in the Data Window.
Notional Value : total trade group position size x latest entry price x point value. The equity must be > notional value x margin requirement for a trade to occur.
Current Margin (%) : must be greater than margin requirement set on the Properties tab in order for a trade to occur.
Margin Call Price : when enabled on the Style tab is displayed on both the chart and the Data Window as shown below.
Performance Net Profit (%) : Will include dividends if 'Include Dividends in Profit' is enabled. Only shows in Data Window if 'Include Dividends in Profit' is enabled.
ROI (%) and CAGR (%) : Based on Avg Invest/Trade-Grp. Adjusted for dividends if enabled.
Reward/Risk (profit/risked, expectancy per amount risked): Adjusted for dividends if enabled. Color is green if above breakeven, red if below, and yellow if within ±0.1 tolerance.
Profit Factor (PF) : By default, dividends are not counted in win/loss classification.
Win % : Uses same coloring scheme as Reward/Risk except uses a ±2% tolerance for yellow. Breakeven point is the balance between Reward/Risk and Win %, showing whether the system can be profitable. For example, for a low Win % a high Reward/Risk is needed for the system to be potentially profitable. Equity & Growth
Equity : Your current equity.
Dividend Sum : The amount of total dividends accumulated since entering the market. Only shows in Data Window if 'Include Dividends in Profit' is enabled. Risk & Drawdown
Maximum Drawdown (MDD)
Measures the largest peak-to-trough decline in account equity over the entire backtest.
A new peak is recorded whenever equity reaches a new high; the system then tracks the lowest equity seen until a new peak forms.
This method uses bar-close equity including both realized and unrealized P&L. Therfore, it may not match TradingView’s displayed drawdown values which use a different method.
Maximum Drawdown %
Expresses MDD as a percentage of the equity peak from which the decline occurred.
This normalizes drawdown across different account sizes and assets, making strategy-to-strategy risk comparisons more meaningful.
Maximum Consecutive Losses applies to trade groups.
Equivalent Consecutive Losses (ECL) : Based on Win % and Nbr of Trade-Grp’s.
Simulates a realistic losing streak with intermittent small wins.
Lowered by increasing Win %.
Equity Loss from ECL : Equity drawdown estimated from ECL.
Equity Loss from ECL (%) : Same, expressed as a percentage.
Avg Trade-Grp Loss Trade Structure
Backtesting Years : The trading window in years.
Nbr of Trade-Grp’s : Count of trade groups.
Nbr of Positions : The count of positions shown on the chart.
The TV list of trades in the Strategy Tester may indicate more than what is actually shown on the chart.
Avg Invest/Trade-Grp : Avg money invested per trade group. Adjusted for dividends if enabled.
Avg Trade-Grp Days : The average number of days for trade groups.
Time in Market (%) : The percentage of time in a trade based on the trading window.
Cnt 1st EE Same-Bar is the count of first positions in a trade group that enter and exit on the same bar. Labels appear above for easy reference. Helps assess optimal stop-loss settings.
Cnt Pyr EE Same-Bar is the count of pyramid positions in a trade group that enter and exit on the same bar. Labels appear above for easy reference. Helps assess optimal stop-loss settings. Up Gaps / Dwn Gap (Ticks) ( Show All Gap Stats in Data Window enabled )
Median gap
Avg gap
80 percentile
90 percentile
Price Gap (Ticks) ( Show All Gap Stats in Data Window disabled )
Dwn Gap : Shows selected option if not disabled.
Up Gap : Shows selected option if not disabled.
Data Quality
Tick Resolution measures how many minimum price increments (ticks) fit into the current asset’s price. It is calculated as: Tick Resolution = Price / Minimum Tick Size. This value indicates the precision available for order placement and stop calculations.
Green – High resolution (>= 1000). The strategy’s stop and profit calculations will operate with normal accuracy.
Yellow – Moderate resolution (100-999). Stop levels are still functional but may exhibit minor rounding effects.
Red – Low resolution (< 100). This can distort trailing stops, stop losses, or take profits due to coarse rounding by TradingView’s broker emulator.
⚠️ Caution : When Tick Resolution is in the red zone, results from backtests may differ significantly from live trading because price precision is too low for reliable simulation.
💡 Tip : If low tick resolution is present at the beginning of the chart’s market data (often with very old price history), use the Trading Window to restrict backtesting to later periods where the asset price has risen and tick resolution is higher.
👁 Visualization
Highlight Traded Background
Trade groups are shown in background color of green for long positions and red for short positions. Set as desired.
Show Losing Trade Groups
Losing trade groups are indicated at the exit with label text in the color blue. Used to easily find consecutive losses affecting your strategy’s performance. The dividend payment, if any, is not considered in the calculation of a win or loss.
Show Position Values
Enable to show the currency value of each position in gold color.
Show Max Drawdown (Peak & Trough) Enable to show the peak and trough labels on the price chart. Based on equity at bar close. Use to easily identify the bar associated with the peak and trough of equity.
Select label size for your preference.
Alert on Expiring GTC Orders
Backtest Pro includes an optional alert that warns you when a Good-Til-Canceled (GTC) order is approaching expiration. This feature is designed as a safety net, helping you avoid unprotected trades caused by broker-imposed GTC expirations. This alert is sent a few days before a 60-day time period you’re if still in an open position.
By default, the alert is enabled, offering protection for traders who may not actively monitor order expiry rules.
Professional users who already track expirations can disable the feature in the settings to streamline alerts.
🔌 Signal Connection
Click the dropdown and select the entry and exit signal to establish a connection to your indicator.
Separate Entry and Exit Signal Connections.
Backtest Pro requires separate entry and exit signals. Indicators that already produce distinct events integrate cleanly and make strategies easier to read, debug, and maintain.
If your indicator currently uses a combined signal (e.g., buy = 1, sell = –1, flat = 0), that structure can create overlap or conflicts during backtesting.
Don’t worry — later in this manual, you’ll learn exactly how to adapt your indicator so it outputs clear entry and exit signals compatible with Backtest Pro.
🔌 Configure Your Indicator for Entry and Exit Signals
This section explains how to structure your indicator’s entry and exit signals so they can connect seamlessly with the Backtest Pro engine.
Define your own conditions for when to enter or exit positions using any technical logic you prefer. You can configure exits independently of entries or make them dependent on them—for example, exiting only when the opposite entry condition occurs.
Below are a few examples of how you might define Long and Short Entry Signals before connecting them to Backtest Pro.
________________________________________________________________________________
Examples of Long Entry Signals
ind_sig_long = oscillator > UpperLimit
ind_sig_long = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
ind_sig_long = MACD_hist > 0 Examples of Short Entry Signals
ind_sig_short = oscillator < LowerLimit
ind_sig_short = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
ind_sig_short = MACD_hist < 0 ________________________________________________________________________________
Combining and Refining Your Signals
If your indicator uses multiple internal conditions, you can combine them using logical operators or threshold rules before connecting to the Backtest Pro engine.
1. Combine multiple conditions
Use logical and / or to merge your conditions into one signal:
Entry_Long = ind_sig_long1 and ind_sig_long2 // both must be true
Entry_Short = ind_sig_short1 or ind_sig_short2 // either may be true ________________________________________________________________________________
2. Require a minimum number of confirming conditions
You can also define a threshold for how many entry conditions must be true before triggering a signal. This can help ensure stronger confirmation.
minNbr_Entries = input.int(defval=1, title='Min Number of Entry Conditions')
// Convert boolean signals to numeric form
longCount = (ind_sig_long1 ? 1 : 0) + (ind_sig_long2 ? 1 : 0)
shortCount = (ind_sig_short1 ? 1 : 0) + (ind_sig_short2 ? 1 : 0)
// Require at least minNbr_Entries to confirm signal
Entry_Long = longCount >= minNbr_Entries
Entry_Short = shortCount >= minNbr_Entries
Do likewise for your Exit conditions to ensure consistency in trade confirmation.
________________________________________________________________________________
Defining Exits
Independent of Entries
Exit_Long = ta.crossunder(ta.rsi(close, 14), 70)
Exit_Short = ta.crossover(ta.rsi(close, 14), 30) Dependent on Entries
Exit_Long = Entry_Short // exit longs when short entry triggers
Exit_Short = Entry_Long // exit shorts when long entry triggers ________________________________________________________________________________
Final Signals to Connect to Backtest Pro
entry_signal = Entry_Long ? 1 : Entry_Short ? -1 : 0
exit_signal = Exit_Long ? 1 : Exit_Short ? -1 : 0
plot(entry_signal, title="entry_signal", color = color.blue, display=display.data_window)
plot(exit_signal, title="exit_signal", color = color.red, display=display.data_window) ________________________________________________________________________________
Notes
You can easily expand this structure to handle three or more conditions by adding them to the count expression.
If your indicator already provides a single entry_signal, you can connect it directly to Backtest Pro without modification.
Always ensure your final Entry_Long, Entry_Short, Exit_Long, and Exit_Short variables are boolean (true / false).
🔒 Connecting Closed-Source Indicators
If your indicator is closed-source (meaning you cannot view or modify its internal code), you’ll need to work with the plotted values it provides.
Create a connection indicator that reads those plotted values and converts them into clear entry and exit signals using the logic described above.
This connection indicator acts as a bridge between the closed-source indicator and Backtest Pro, allowing you to translate its behavior into standardized signal logic that the engine can process.
⚙️ PROPERTIES TAB SETTING
Initial Capital : Set as desired.
Base Currency : Leave as Default. The Backtest Pro is designed to use the instrument’s native currency, so changing this is not necessary.
Order Size : Essentially disabled. Position sizing is handled in the Inputs tab and is based on a percentage of equity.
Pyramiding : Set as desired.
Commission : Enter as a percentage of position value. The Backtest Pro is designed to work only with commission expressed this way.
Verify Price for Limit Orders : Set as desired.
Slippage : Set as desired. See the Dwn/Up Gap values in Data Window to get an idea of possible values to use.
Margin (Leverage Trading):
The Backtest Pro supports both leveraged and non-leveraged trading (default is no leverage).
Note : The following two settings apply at the trade group level . For example, to trade with 5× leverage, enter 20 (1 ÷ 5 × 100 = 20).
Margin for Long Positions : Set as desired. Default is 100%.
Margin for Short Positions : Set as desired. Default is 100%.
Recalculate After Order Is Filled (default is enabled)
Enabling this allows the Backtest Pro to function correctly and to recalculate immediately after an order is filled , which makes it possible to:
Enter and exit on the same bar (because the strategy sees the fill instantly).
Trigger alerts immediately after the fill , instead of waiting for the next bar close.
You may see the following Caution! message in the TradingView Strategy Tester:
This warning occurs because the strategy parameter calc_on_order_fills = true . You can safely close the caution message and know the Backtest Pro will produce realistic backtest results.
Recalculate On every tick : Disable.
Fill Orders
Using Bar Magnifier : Recommended if your TradingView plan supports it. Improves intrabar accuracy, but the strategy can still run without it.
On Bar Close : Must remain disabled. Enabling this prevents the Backtest Pro from working as intended.
⚠️ Caution : Enabling On Bar Close forces all orders to be evaluated only at bar close. This disables intrabar logic, prevents same-bar entries and exits, and breaks trailing stop / pyramid behavior. For the Backtest Pro to work as intended, On Bar Close must remain disabled .
Using Standard OHLC : Recommended if running the strategy on Heikin Ashi charts. Otherwise, set as desired. The default is enabled.
📢 Using The Alert Dialog Box Message Field
When setting alerts, include alert() function calls with order fills to allow notifications for drawdown exceeded, Failed to Trade (if enabled), and to be warned of expiring GTC orders (if enabled).
Example Message for Order Fill Alerts
(This is just an example. Consult TV manual for possible placeholders to use.)
Position: Current = {{strategy.market_position}}, Previous = {{strategy.prev_market_position}}
{{strategy.order.action}} {{strategy.order.contracts}} shares at price = {{strategy.order.price}} on {{exchange}}:{{ticker}} (TF: {{interval}})
Equity_Multiplier = {{strategy.order.contracts}} x {{strategy.order.price}} ÷ {{plot("Equity")}}
{{strategy.order.alert_message}}
Note :
Use a known account equity multiplied by Equity_Multiplier to determine the total currency amount required for position sizing—especially when managing multiple accounts with different equity levels.
What {{strategy.order.alert_message}} Includes
This placeholder automatically inserts the additional information generated for each order fill alert (blank for exits):
Stop Price (on first entries is based on bar close prior to order fill bar)
TSL Offset (Pts) distance from Favorable Extreme (for pyramid entries)
TP (on first entries is based on bar close prior to order fill bar)
Price Gap (Pts) based on your gap selection and slippage entered
Example Message for Bot Trading Alerts
(You must consult your specific bot for configuring the alert message. This is just an example.)
"action": "{{strategy.order.action}}",
“price”: {{strategy.order.price}}
"amount": {{strategy.order.contracts}},
"botId": "1234"
Golden Vector Trend Orchestrator (GVTO)Golden Vector Trend Orchestrator (GVTO) is a composite trend-following strategy specifically engineered for XAUUSD (Gold) and volatile assets on H4 (4-Hour) and Daily timeframes.
This script aims to solve a common problem in trend trading: "Whipsaws in Sideways Markets." Instead of relying on a single indicator, GVTO employs a Multi-Factor Confluence System that filters out low-probability trades by requiring alignment across Trend Structure, Momentum, and Volatility.
🛠 Methodology & Logic
The strategy executes trades only when four distinct technical conditions overlap (Confluence). If any single condition is not met, the trade is filtered out to preserve capital.
1. Market Structure Filter (200 EMA)
Indicator: Exponential Moving Average (Length 200).
Logic: The 200 EMA acts as the baseline for the long-term trend regime.
Bullish Regime: Price must close above the 200 EMA.
Bearish Regime: Price must close below the 200 EMA.
Purpose: Prevents counter-trend trading against the macro direction.
2. Signal Trigger & Trailing Stop (Supertrend)
Indicator: Supertrend (ATR Length 14, Factor 3.5).
Logic: Uses Average True Range (ATR) to detect trend reversals while accounting for volatility.
Purpose: Provides the specific entry signal and acts as a dynamic trailing stop-loss to let profits run while cutting losses when the trend invalidates.
3. Volatility Gatekeeper (ADX Filter)
Indicator: Average Directional Index (Length 14).
Threshold: > 25.
Logic: A high ADX value indicates a strong trend presence, regardless of direction.
Purpose: This is the most critical filter. It prevents the strategy from entering trades during "choppy" or ranging markets (consolidation zones) where trend-following systems typically fail.
4. Momentum Confirmation (DMI)
Indicator: Directional Movement Index (DI+ and DI-).
Logic: Checks if the buying pressure (DI+) is physically stronger than selling pressure (DI-), or vice versa.
Purpose: Ensures that the price movement is backed by genuine momentum, not just a momentary price spike.
📋 How to Use This Strategy
🟢 LONG (BUY) Setup
A Buy signal is generated only when ALL of the following occur simultaneously:
Price Action: Price closes ABOVE the 200 EMA (Orange Line).
Trigger: Supertrend flips to GREEN (Bullish).
Strength: ADX is greater than 25 (Strong Trend).
Momentum: DI+ (Plus Directional Indicator) is greater than DI- (Minus).
🔴 SHORT (SELL) Setup
A Sell signal is generated only when ALL of the following occur simultaneously:
Price Action: Price closes BELOW the 200 EMA (Orange Line).
Trigger: Supertrend flips to RED (Bearish).
Strength: ADX is greater than 25 (Strong Trend).
Momentum: DI- (Minus Directional Indicator) is greater than DI+ (Plus).
🛡 Exit Strategy
Stop Loss / Take Profit: The strategy utilizes the Supertrend Line as a dynamic Trailing Stop.
Exit Long: When Supertrend turns Red.
Exit Short: When Supertrend turns Green.
Note: Traders can also use the real-time P/L Dashboard included in the script to manually secure profits based on their personal Risk:Reward ratio.
📊 Included Features
Real-Time P/L Dashboard: A table in the top-right corner displays the current trend status, ADX strength, and the Unrealized Profit/Loss % of the current active position.
Smart Labeling: Buy/Sell labels are coded to appear only on the initial entry trigger. They do not repaint and do not spam the chart if the trend continues (no pyramiding visualization).
Visual Aids: Background color changes (Green/Red) to visually represent the active trend based on the Supertrend status.
⚠️ Risk Warning & Best Practices
Asset Class: Optimized for XAUUSD (Gold) due to its high volatility nature. It also works well on Crypto (BTC, ETH) and Major Forex Pairs.
Timeframe: Highly recommended for H4 (4 Hours) or D1 (Daily). Using this on lower timeframes (M5, M15) may result in false signals due to market noise.
News Events: Automated strategies cannot predict economic news (CPI, NFP). Exercise caution or pause trading during high-impact economic releases.
Liquidity Retest Strategy (Apicode) - TP/SL Lines FixedTechnical Documentation:
1. Purpose and underlying concept
This strategy targets a common behavior in liquid markets: liquidity sweeps around meaningful support/resistance levels, followed by a retest and rejection (reversal) with confirmation.
The core thesis is that many initial “breaks” are not continuation moves, but rather stop-runs and order harvesting. After the sweep, price reclaims the level and closes back on the opposite side, offering a structured entry with defined risk.
The strategy includes:
Support/Resistance detection via pivots
Dynamic selection of the “working” level using an ATR-based proximity window
Rejection validation via candle structure (wick + close)
Optional filters: volume, VWAP-like bias, and EMA trend
Risk management with static TP/SL (ATR-based or %), plus trailing stop (ATR-based or %), with per-trade lines plotted
2. Main components
2.1. Volatility metric: ATR
atr = ta.atr(atrLength) is used in two essential places:
Level selection (proximity to S/R): prevents trading levels that are too far from current price.
Sweep validation (minimum wick size): requires the wick to extend beyond the level by a volatility-relative amount.
Optionally, ATR can also be used for:
Static TP/SL (when usePercent = false)
Trailing stop (when useTrailPercent = false)
2.2. Building S/R levels with pivots
Pivots are detected using:
pivotHigh = ta.pivothigh(pivotLookback, rightBars)
pivotLow = ta.pivotlow(pivotLookback, rightBars)
Each confirmed pivot is stored in arrays:
resistanceLevels for resistance
supportLevels for support
The array size is capped by maxLevels, which reduces noise and manages chart resource usage (lines).
2.3. Selecting the “best” level each bar
On each bar, a single support S and/or resistance R candidate is chosen:
Support: nearest level below price (L < price)
Resistance: nearest level above price (L > price)
Only levels within atr * maxDistATR are considered
This produces dynamic “working levels” that adapt to price location and volatility.
2.4. Rejection pattern (retest + sweep)
After selecting the working level:
Support rejection (long setup)
Conditions:
Low touches/crosses support: low <= S
Close reclaims above: close > S
Bullish candle: close > open
Sufficient wick below the level (liquidity sweep): (S - low) >= atr * minWickATR
This aims to capture a stop sweep below support followed by immediate recovery.
Resistance rejection (short setup)
Symmetric conditions:
High touches/crosses resistance: high >= R
Close rejects back below: close < R
Bearish candle: close < open
Sufficient wick above the level: (high - R) >= atr * minWickATR
2.5. Optional filters
Final signals are the rejection pattern AND enabled filters:
1.- Volume filter
High volume is defined as: volume > SMA(volume, 20) * volMult
When useVolFilter = true, setups require relatively elevated participation
2.- VWAP-like bias filter
A VWAP-like series is computed over vwapLength (typical price weighted by volume)
When useVWAPFilter = true:
- Longs only if close > vwap
- Shorts only if close < vwap
3.- EMA trend filter
Uptrend if EMA(fast) > EMA(slow)
When useTrendFilter = true:
- Longs only in uptrend
- Shorts only in downtrend
2.6. Backtest time window (time filter)
To keep testing focused and reduce long-history noise:
useMaxLookbackDays enables the filter
maxLookbackDays defines how many days back from timenow entries are allowed
Entries are permitted only when time >= startTime.
3. Entry rules and position control
3.1. Entries
strategy.entry('Long', strategy.long) when longSetup and no long position is open
strategy.entry('Short', strategy.short) when shortSetup and no short position is open
No pyramiding is allowed (pyramiding = 0). Position gating is handled by:
Long allowed if strategy.position_size <= 0
Short allowed if strategy.position_size >= 0
4. Risk management: TP/SL and trailing (with plotted lines)
4.1. Detecting entry/exit events
Events are identified via changes in strategy.position_size:
LongEntry: transition into a long
shortEntry: transition into a short
flatExit: transition back to flat
This drives per-trade line creation, updates, and cleanup of state variables.
4.2. Static TP/SL
On entry, entryPrice := strategy.position_avg_price is stored.
Percent mode (usePercent = true)
Long:
staticSL = entryPrice*(1 - slPerc/100)
staticTP = entryPrice*(1 + tpPerc/100)
Short:
staticSL = entryPrice*(1 + slPerc/100)
staticTP = entryPrice*(1 - tpPerc/100)
ATR mode (usePercent = false)
Long:
staticSL = entryPrice - atrAtEntry*slATR
staticTP = entryPrice + atrAtEntry*tpATR
Short:
staticSL = entryPrice + atrAtEntry*slATR
staticTP = entryPrice - atrAtEntry*tpATR
4.3. Trailing stop (custom)
While a position is open, the script tracks the most favorable excursion:
Long: hhSinceEntry = highest high since entry
Short: llSinceEntry = lowest low since entry
A trailing candidate is computed:
Percent trailing (useTrailPercent = true)
Long: trailCandidate = hhSinceEntry*(1 - trailPerc/100)
Short: trailCandidate = llSinceEntry*(1 + trailPerc/100)
ATR trailing (useTrailPercent = false)
Long: trailCandidate = hhSinceEntry - atr*trailATR
Short: trailCandidate = llSinceEntry + atr*trailATR
Then the effective stop is selected:
Long: slUsed = max(staticSL, trailCandidate) when useTrail is enabled
Short: slUsed = min(staticSL, trailCandidate) when useTrail is enabled
If useTrail is disabled, slUsed remains the static stop.
Take profit remains static:
tpUsed = staticTP
Exit orders are issued via:
strategy.exit(..., stop=slUsed, limit=tpUsed)
4.4. Per-trade TP/SL lines
On each entry, two lines are created (SL and TP) via f_createLines().
During the trade, the SL line updates when trailing moves the stop; TP remains fixed.
On exit (flatExit), both lines are finalized on the exit bar and left on the chart as historical references.
This makes it straightforward to visually audit each trade: entry context, intended TP, and trailing evolution until exit.
5. Visualization and debugging
BUY/SELL labels with configurable size (xsize)
Debug mode (showDebug) plots the chosen working support/resistance level each bar
Stored pivot levels are drawn using reusable line slots, projected a fixed 20 bars to the right to keep the chart readable and efficient
6. Parameter guidance and practical notes
pivotLookback / rightBars: controls pivot significance vs responsiveness. Lower rightBars confirms pivots earlier but can increase noise.
maxDistATR: too low may reject valid levels; too high may select distant, less relevant levels.
minWickATR: key quality gate for “real” sweeps. Higher values reduce frequency but often improve signal quality.
Filters:
Volume filter tends to help in ranges and active sessions.
VWAP bias is useful intraday to align trades with session positioning.
EMA trend filter is helpful in directional markets but may remove good mean-reversion setups.
Percent TP/SL: provides consistent behavior across assets with variable volatility, but is less adaptive to sudden regime shifts.
Percent trailing: can capture extensions well; calibrate trailPerc per asset/timeframe (too tight = premature exits).
7. Known limitations
Pivot-derived levels are a heuristic; in strong trends, valid retests may be limited.
The time filter uses timenow; behavior may vary depending on historical context and how the platform evaluates “current time.”
TP/SL and trailing are computed from bar OHLC; in live trading, intrabar sequencing and fills may differ from bar-close simulation.
Crandall CrossThe Crandall Cross indicator is an Exponential Moving Average (EMA) and Stop And Reverse (SAR) combination indicator. It uses the EMA200, EMA20, and a unique SAR Projection. Typically, SAR indicators are represented as dots, but this SAR is a line that projects Parabolic Strength based on 3 time-period groupings. The indicator essentially implements a simple EMA cross strategy while using an SAR Projection as confirmation.
How to Use
A Buy Signal will most likely appear when the EMA20 (pink) crosses over the EMA200 (yellow) and the price is above the SAR Projection (blue).
A Sell Signal will most likely appear when the EMA20 (pink) crosses under the EMA200 (yellow) and the price is below the SAR Projection (blue).
The Buy/Sell Signals can appear later because they require SAR confirmation.
Note This indicator neither gives financial advice nor does it guarantee investment success. Invest at your own discretion.
CryptoFlux Dynamo [JOAT]CryptoFlux Dynamo: Velocity Scalping Strategy
WHAT THIS STRATEGY IS
CryptoFlux Dynamo is an open-source Pine Script v6 strategy designed for momentum-based scalping on cryptocurrency perpetual futures. It combines multiple technical analysis methods into a unified system that adapts its behavior based on current market volatility conditions.
This script is published open-source so you can read, understand, and modify the complete logic. The description below explains everything the strategy does so that traders who cannot read Pine Script can fully understand how it works before using it.
HOW THIS STRATEGY IS ORIGINAL AND WHY THE INDICATORS ARE COMBINED
This strategy uses well-known indicators (MACD, EMA, RSI, MFI, Bollinger Bands, Keltner Channels, ATR). The originality is not in the individual indicators themselves, but in the specific way they are integrated into a regime-adaptive system. Here is the detailed justification for why these components are combined and how they work together:
The Problem Being Solved:
Standard indicator-based strategies use fixed thresholds. For example, a typical MACD strategy might enter when the histogram crosses above zero. However, in cryptocurrency markets, volatility changes dramatically throughout the day and week. A MACD crossover during a low-volatility consolidation period has very different implications than the same crossover during a high-volatility trending period. Using the same entry thresholds and stop distances in both conditions leads to either:
Too many false signals during consolidation (if thresholds are loose)
Missing valid opportunities during expansion (if thresholds are tight)
Stops that are too tight during volatility spikes (causing premature exits)
Stops that are too wide during compression (giving back profits)
The Solution Approach:
This strategy first classifies the current volatility regime using normalized ATR (ATR as a percentage of price), then dynamically adjusts ALL other parameters based on that classification. This creates a context-aware system rather than a static threshold comparison.
How Each Component Contributes to the System:
ATR-Based Regime Classification (The Foundation)
The strategy calculates ATR over 21 periods, smooths it with a 13-period EMA to reduce noise from wicks, then divides by price to get a normalized percentage. This ATR% is classified into three regimes:
- Compression (ATR% < 0.8%): Market is consolidating, breakouts are more likely but false signals are common
- Expansion (ATR% 0.8% - 1.6%): Normal trending conditions
- Velocity (ATR% > 1.6%): High volatility, larger moves but also larger adverse excursions
This regime classification then controls stop distances, profit targets, trailing stop offsets, and signal strength requirements. The regime acts as a "meta-parameter" that tunes the entire system.
EMA Ribbon (8/21/34) - Trend Structure Detection
The three EMAs establish trend direction and structure. When EMA 8 > EMA 21 > EMA 34, the trend structure is bullish. The slope of the middle EMA (21) is calculated over 8 bars and converted to degrees using arctangent. This slope measurement quantifies trend strength, not just direction.
Why these specific periods? The 8/21/34 sequence follows Fibonacci-like spacing and provides good separation on 5-minute cryptocurrency charts. The fast EMA (8) responds to immediate price action, the mid EMA (21) represents the short-term trend, and the slow EMA (34) acts as a trend filter.
The EMA ribbon works with the regime classification: during compression regimes, the strategy requires stronger ribbon alignment before entry because false breakouts are more common.
MACD (8/21/5) - Momentum Measurement
The MACD uses faster parameters (8/21/5) than the standard (12/26/9) because cryptocurrency markets move faster than traditional markets. The histogram is smoothed with a 5-period EMA to reduce noise.
The key innovation is the adaptive histogram baseline. Instead of using a fixed threshold, the strategy calculates a rolling baseline from the smoothed absolute histogram value, then multiplies by a sensitivity factor (1.15). This means the threshold for "significant momentum" automatically adjusts based on recent momentum levels.
The MACD works with the regime classification: during velocity regimes, the histogram baseline is effectively higher because recent momentum has been stronger, preventing entries on relatively weak momentum.
RSI (21 period) and MFI (21 period) - Independent Momentum Confirmation
RSI measures momentum using price changes only. MFI (Money Flow Index) measures momentum using price AND volume. By requiring both to confirm, the strategy filters out price moves that lack volume support.
The 21-period length is longer than typical (14) to reduce noise on 5-minute charts. The trigger threshold (55 for longs, 45 for shorts) is slightly offset from 50 to require momentum in the trade direction, not just neutral readings.
These indicators work together: a signal requires RSI > 55 AND MFI > 55 for longs. This dual confirmation reduces false signals from price manipulation or low-volume moves.
Bollinger Bands (1.5 mult) and Keltner Channels (1.8 mult) - Squeeze Detection
When Bollinger Bands contract inside Keltner Channels, volatility is compressing and a breakout is likely. This is the "squeeze" condition. When the bands expand back outside the channels, the squeeze "releases."
The strategy uses a 1.5 multiplier for Bollinger Bands (tighter than standard 2.0) and 1.8 for Keltner Channels. These values were chosen to identify meaningful squeezes on 5-minute cryptocurrency charts without triggering too frequently.
The squeeze detection works with the regime classification: squeeze releases during compression regimes receive additional signal strength points because breakouts from consolidation are more significant.
Volume Impulse Detection - Institutional Participation Filter
The strategy calculates a volume baseline (34-period SMA) and standard deviation. A "volume impulse" is detected when current volume exceeds the baseline by 1.15x OR when the volume z-score exceeds 0.5.
This filter ensures entries occur when there is meaningful market participation, not during low-volume periods where price moves are less reliable.
Volume impulse is required for all entries and adds points to the composite signal strength score.
Cycle Oscillator - Trend Alignment Filter
The strategy calculates a 55-period EMA as a cycle basis, then measures price deviation from this basis as a percentage. When price is more than 0.15% above the cycle basis, the cycle is bullish. When more than 0.15% below, the cycle is bearish.
This filter prevents counter-trend entries. Long signals require bullish cycle alignment; short signals require bearish cycle alignment.
BTC Dominance Filter (Optional) - Market Regime Filter
The strategy can optionally use BTC.D (Bitcoin Dominance) as a market regime filter. When BTC dominance is rising (slope > 0.12), the market is in "risk-off" mode and long entries on altcoins are filtered. When dominance is falling (slope < -0.12), short entries are filtered.
This filter is optional because the BTC.D data feed may lag during low-liquidity periods.
How The Components Work Together (The Mashup Justification):
The strategy uses a composite scoring system where each signal pathway contributes points:
Trend Break pathway (30 points): Requires EMA ribbon alignment + positive slope + price breaks above recent structure high
Momentum Surge pathway (30 points): Requires MACD histogram > adaptive baseline + MACD line > signal + RSI > 55 + MFI > 55 + volume impulse
Squeeze Release pathway (25 points): Requires BB inside KC (squeeze) then release + momentum bias + histogram confirmation
Micro Pullback pathway (15 points): Requires shallow retracement to fast EMA within established trend + histogram confirmation + volume impulse
Additional modifiers:
+5 points if volume impulse is present, -5 if absent
+5 points in velocity regime, -2 in compression regime
+5 points if cycle is aligned, -5 if counter-trend
A trade only executes when the composite score reaches the minimum threshold (default 55) AND all filters agree (session, cycle bias, BTC dominance if enabled).
This scoring system is the core innovation: instead of requiring ALL conditions to be true (which would generate very few signals) or ANY condition to be true (which would generate too many false signals), the strategy requires ENOUGH conditions to be true, with different conditions contributing different weights based on their reliability.
HOW THE STRATEGY CALCULATES ENTRIES AND EXITS
Entry Logic:
1. Calculate current volatility regime from ATR%
2. Calculate all indicator values (MACD, EMA, RSI, MFI, squeeze, volume)
3. Evaluate each signal pathway and sum points
4. Check all filters (session, cycle, dominance, kill switch)
5. If composite score >= 55 AND all filters pass, generate entry signal
6. Calculate position size based on risk per trade and regime-adjusted stop distance
7. Execute entry with regime name as comment
Position Sizing Formula:
RiskCapital = Equity * (0.65 / 100)
StopDistance = ATR * StopMultiplier(regime)
RawQuantity = RiskCapital / StopDistance
MaxQuantity = Equity * (12 / 100) / Price
Quantity = min(RawQuantity, MaxQuantity)
Quantity = round(Quantity / 0.001) * 0.001
This ensures each trade risks approximately 0.65% of equity regardless of volatility, while capping total exposure at 12% of equity.
Stop Loss Calculation:
Stop distance is ATR multiplied by a regime-specific multiplier:
Compression regime: 1.05x ATR (tighter stops because moves are smaller)
Expansion regime: 1.55x ATR (standard stops)
Velocity regime: 2.1x ATR (wider stops to avoid premature exits during volatility)
Take Profit Calculation:
Target distance is ATR multiplied by regime-specific multiplier and base risk/reward:
Compression regime: 1.6x ATR * 1.8 base R:R * 0.9 regime bonus = approximately 2.6x ATR
Expansion regime: 2.05x ATR * 1.8 base R:R * 1.0 regime bonus = approximately 3.7x ATR
Velocity regime: 2.8x ATR * 1.8 base R:R * 1.15 regime bonus = approximately 5.8x ATR
Trailing Stop Logic:
When adaptive trailing is enabled, the strategy calculates a trailing offset based on ATR and regime:
Compression regime: 1.1x base offset (looser trailing to avoid noise)
Expansion regime: 1.0x base offset (standard)
Velocity regime: 0.8x base offset (tighter trailing to lock in profits during fast moves)
The trailing stop only activates when it would be tighter than the initial stop.
Momentum Fail-Safe Exits:
The strategy closes positions early if momentum reverses:
Long positions close if MACD histogram turns negative OR EMA ribbon structure breaks (fast EMA crosses below mid EMA)
Short positions close if MACD histogram turns positive OR EMA ribbon structure breaks
This prevents holding through momentum reversals even if stop loss hasn't been hit.
Kill Switch:
If maximum drawdown exceeds 6.5%, the strategy disables new entries until manually reset. This prevents continued trading during adverse conditions.
HOW TO USE THIS STRATEGY
Step 1: Apply to Chart
Use a 5-minute chart of a high-liquidity cryptocurrency perpetual (BTC/USDT, ETH/USDT recommended)
Ensure at least 200 bars of history are loaded for indicator stabilization
Use standard candlestick charts only (not Heikin Ashi, Renko, or other non-standard types)
Step 2: Understand the Visual Elements
EMA Ribbon: Three lines (8/21/34 periods) showing trend structure. Bullish when stacked upward, bearish when stacked downward.
Background Color: Shows current volatility regime
- Indigo/dark blue = Compression (low volatility)
- Purple = Expansion (normal volatility)
- Magenta/pink = Velocity (high volatility)
Bar Colors: Reflect signal strength divergence. Brighter colors indicate stronger directional bias.
Triangle Markers: Entry signals. Up triangles below bars = long entry. Down triangles above bars = short entry.
Dashboard (top-right): Real-time display of regime, ATR%, signal strengths, position status, stops, targets, and risk metrics.
Step 3: Interpret the Dashboard
Regime: Current volatility classification (Compression/Expansion/Velocity)
ATR%: Normalized volatility as percentage of price
Long/Short Strength: Current composite signal scores (0-100)
Cycle Osc: Price deviation from 55-period EMA as percentage
Dominance: BTC.D slope and filter status
Position: Current position direction or "Flat"
Stop/Target: Current stop loss and take profit levels
Kill Switch: Status of drawdown protection
Volume Z: Current volume z-score
Impulse: Whether volume impulse condition is met
Step 4: Adjust Parameters for Your Needs
For more conservative trading: Increase "Minimum Composite Signal Strength" to 65 or higher
For more aggressive trading: Decrease to 50 (but expect more false signals)
For higher timeframes (15m+): Increase "Structure Break Window" to 12-15, increase "RSI Momentum Trigger" to 58
For lower liquidity pairs: Increase "Volume Impulse Multiplier" to 1.3, increase slippage in strategy properties
To disable short selling: Uncheck "Enable Short Structure"
To disable BTC dominance filter: Uncheck "BTC Dominance Confirmation"
STRATEGY PROPERTIES (BACKTEST SETTINGS)
These are the exact settings used in the strategy's Properties dialog box. You must use these same settings when evaluating the backtest results shown in the publication:
Initial Capital: $100,000
Justification: This amount is higher than typical retail accounts. I chose this value to demonstrate percentage-based returns that scale proportionally. The strategy uses percentage-based position sizing (0.65% risk per trade), so a $10,000 account would see the same percentage returns with 10x smaller position sizes. The absolute dollar amounts in the backtest should be interpreted as percentages of capital.
Commission: 0.04% (commission_value = 0.04)
Justification: This reflects typical perpetual futures exchange fees. Major exchanges charge between 0.02% (maker) and 0.075% (taker). The 0.04% value is a reasonable middle estimate. If your exchange charges different fees, adjust this value accordingly. Higher fees will reduce net profitability.
Slippage: 1 tick
Justification: This is conservative for liquid pairs like BTC/USDT on major exchanges during normal conditions. For less liquid altcoins or during high volatility, actual slippage may be higher. If you trade less liquid pairs, increase this value to 2-3 ticks for more realistic results.
Pyramiding: 1
Justification: No position stacking. The strategy holds only one position at a time. This simplifies risk management and prevents overexposure.
calc_on_every_tick: true
Justification: The strategy evaluates on every price update, not just bar close. This is necessary for scalping timeframes where waiting for bar close would miss opportunities. Note that this setting means backtest results may differ slightly from bar-close-only evaluation.
calc_on_order_fills: true
Justification: The strategy recalculates immediately after order fills for faster response to position changes.
RISK PER TRADE JUSTIFICATION
The default risk per trade is 0.65% of equity. This is well within the TradingView guideline that "risking more than 5-10% on a trade is not typically considered viable."
With the 12% maximum exposure cap, even if the strategy takes multiple consecutive losses, the total risk remains manageable. The kill switch at 6.5% drawdown provides additional protection by halting new entries during adverse conditions.
The position sizing formula ensures that stop distance (which varies by regime) is accounted for, so actual risk per trade remains approximately 0.65% regardless of volatility conditions.
SAMPLE SIZE CONSIDERATIONS
For statistically meaningful backtest results, you should select a dataset that generates at least 100 trades. On 5-minute BTC/USDT charts, this typically requires:
2-3 months of data during normal market conditions
1-2 months during high-volatility periods
3-4 months during low-volatility consolidation periods
The strategy's selectivity (requiring 55+ composite score plus all filters) means it generates fewer signals than less filtered approaches. If your backtest shows fewer than 100 trades, extend the date range or reduce the minimum signal strength threshold.
Fewer than 100 trades produces statistically unreliable results. Win rate, profit factor, and other metrics can vary significantly with small sample sizes.
STRATEGY DESIGN COMPROMISES AND LIMITATIONS
Every strategy involves trade-offs. Here are the compromises made in this design and the limitations you should understand:
Selectivity vs. Opportunity Trade-off
The 55-point minimum threshold filters many potential trades. This reduces false signals but also misses valid setups that don't meet all criteria. Lowering the threshold increases trade frequency but decreases win rate. There is no "correct" threshold; it depends on your preference for fewer higher-quality signals vs. more signals with lower individual quality.
Regime Classification Lag
The ATR-based regime detection uses historical data (21 periods + 13-period smoothing). It cannot predict sudden volatility spikes. During flash crashes or black swan events, the strategy may be classified in the wrong regime for several bars before the classification updates. This is an inherent limitation of any lagging indicator.
Indicator Parameter Sensitivity
The default parameters (MACD 8/21/5, EMA 8/21/34, RSI 21, etc.) are tuned for BTC/ETH perpetuals on 5-minute charts during 2024 market conditions. Different assets, timeframes, or market regimes may require different parameters. There is no guarantee that parameters optimized on historical data will perform similarly in the future.
BTC Dominance Filter Limitations
The CRYPTOCAP:BTC.D data feed may lag during low-liquidity periods or weekends. The dominance slope calculation uses a 5-bar SMA, adding additional delay. If you notice the filter behaving unexpectedly, consider disabling it.
Backtest vs. Live Execution Differences
TradingView backtesting does not replicate actual broker execution. Key differences:
Backtests assume perfect fills at calculated prices; real execution involves order book depth, latency, and partial fills
The calc_on_every_tick setting improves backtest realism but still cannot capture sub-bar price action or order book dynamics
Commission and slippage settings are estimates; actual costs vary by exchange, time of day, and market conditions
Funding rates on perpetual futures are not modeled in backtests and can significantly impact profitability over time
Exchange-specific limitations (position limits, liquidation mechanics, order types) are not modeled
Market Condition Dependencies
This strategy is designed for trending and breakout conditions. During extended sideways consolidation with no clear direction, the strategy may generate few signals or experience whipsaws. No strategy performs well in all market conditions.
Cryptocurrency-Specific Risks
Cryptocurrency markets operate 24/7 without session boundaries. This means:
No natural "overnight" risk reduction
Volatility can spike at any time
Liquidity varies significantly by time of day
Exchange outages or issues can occur at any time
WHAT THIS STRATEGY DOES NOT DO
To be straightforward about limitations:
This strategy does not guarantee profits. Past backtest performance does not indicate future results.
This strategy does not predict the future. It reacts to current conditions based on historical patterns.
This strategy does not account for funding rates, which can significantly impact perpetual futures profitability.
This strategy does not model exchange-specific execution issues (partial fills, requotes, outages).
This strategy does not adapt to fundamental news events or black swan scenarios.
This strategy is not optimized for all market conditions. It may underperform during extended consolidation.
IMPORTANT RISK WARNINGS
Past performance does not guarantee future results. The backtest results shown reflect specific historical market conditions and parameter settings. Markets change constantly, and strategies that performed well historically may underperform or lose money in the future. A single backtest run does not constitute proof of future profitability.
Trading involves substantial risk of loss. Cryptocurrency derivatives are highly volatile instruments. You can lose your entire investment. Only trade with capital you can afford to lose completely.
This is not financial advice. This strategy is provided for educational and informational purposes only. It does not constitute investment advice, trading recommendations, or any form of financial guidance. The author is not a licensed financial advisor.
You are responsible for your own decisions. Before using this strategy with real capital:
Thoroughly understand the code and logic by reading the open-source implementation
Forward test with paper trading or very small positions for an extended period
Verify that commission, slippage, and execution assumptions match your actual trading environment
Understand that live results will differ from backtest results
Consider consulting with a qualified financial advisor
No guarantees or warranties. This strategy is provided "as is" without any guarantees of profitability, accuracy, or suitability for any purpose. The author is not responsible for any losses incurred from using this strategy.
OPEN-SOURCE CODE STRUCTURE
The strategy code is organized into these sections for readability:
Configuration Architecture: Input parameters organized into logical groups (Core Controls, Optimization Constants, Regime Intelligence, Signal Pathways, Risk Architecture, Visualization)
Helper Functions: calcQty() for position sizing, clamp01() and normalize() for value normalization, calcMFI() for Money Flow Index calculation
Core Indicator Engine: EMA ribbon, ATR and regime classification, MACD with adaptive baseline, RSI, MFI, volume analytics, cycle oscillator, BTC dominance filter, squeeze detection
Signal Pathway Logic: Trend break, momentum surge, squeeze release, micro pullback pathways with composite scoring
Entry/Exit Orchestration: Signal filtering, position sizing, entry execution, stop/target calculation, trailing stop logic, momentum fail-safe exits
Visualization Layer: EMA plots, regime background, bar coloring, signal labels, dashboard table
You can read and modify any part of the code. Understanding the logic before deployment is strongly recommended.
- Made with passion by officialjackofalltrades
V-Max L3: Battle Director (Resonance & Execution Engine)Overview The V-Max L3 Battle Director is an institutional-grade "Commander Dashboard" designed to synchronize market dynamics across six distinct timeframes. It integrates a sophisticated volatility-burst detection system and a real-time risk-management engine, providing traders with a unified decision-making hub for high-conviction execution.
Technical Methodology & Originality L3 justifies its invite-only status through a multi-layered quantitative architecture:
Macro-to-Micro Resonance Matrix: The engine continuously scans Weekly, Daily, 4H, 1H, 15m, and 3m timeframes. It calculates a "Final Power" score ($final\_p$) by assigning specific weights (Weekly/Daily for structural bias, 4H/1H for execution context) to ensure every signal is validated by multi-cycle alignment.
A++ Diamond Execution Logic: This proprietary signal identifies high-intensity institutional flow. It only triggers when three objective physical conditions converge:
Volume Spike: Exceeding 50% of the 480-bar high.
Volatility Burst: ATR value > 1.3x the rolling SMA.
Momentum Confirmation: MACD divergence alignment.
Tactical RSI Cooling & Reset System: To prevent emotional over-trading, the system features a momentum-reset logic. After a signal fires, the engine enters a "Cooling" state and only re-arms once the RSI crosses back through the neutral 50-line, ensuring each new trade begins from a fresh momentum cycle.
ntegrated 5-Line Risk Engine: The script renders a real-time risk-management overlay. It projects Entry, Stop Loss (SL), TP1 (Partial Reduction), and Final TP levels based on either Fibonacci ratios or fixed Risk:Reward (RR) configurations.
How to Use
Resonance Score: Focus on execution when the dashboard resonance score exceeds ±70%.
A++ Signals: These represent areas of extreme institutional participation and volatility expansion.
Dashboard Matrix: Utilize the sidebar to monitor the directional health and trend synchronization of all 6 timeframes simultaneously.
產品概述 V-Max L3 戰域總監是一款機構級「交易指揮中心」。它同步監測六個不同時區的市場動態,並整合了複雜的波動率爆發偵測系統與實時風險管理引擎,為交易者提供高勝率執行所需的統一決策核心。
技術邏輯與功能 本腳本作為進階邀請指標,其核心價值在於多層次的量化架構:
多維權重共振矩陣: 系統同步監控從週線到 3 分鐘線的 6 個時區。透過計算「綜合決策分 ($final\_p$)」,將週線/日線的趨勢定錨與 4H/1H 的執行背景相結合,確保訊號具備多週期共振的技術基礎。
A++ 鑽石級執行邏輯: 專為識別機構資金流向設計。此訊號僅在三個物理條件收斂時觸發:成交量突破(480 根 K 線新高 50% 以上)、波動率爆發(ATR > 1.3x SMA)以及 MACD 動能確認。
戰術性 RSI 冷卻重置機制: 為防止過度交易,系統內建動能重置邏輯。訊號發射後即進入冷卻期,直到 RSI 回歸 50 中性水平後才會重新裝彈,確保每筆交易都始於全新的動能週期。
整合型五線譜風控引擎: 在圖表上實時投影進場、止損、TP1(減倉)與最終止盈線,並根據帳戶設定自動計算建議下單數量。
Access & Authorization This is an Invite-Only script. Please refer to my TradingView Profile Signature for instructions on how to request access and authorization.
Disclaimer: This script is for advanced technical analysis and educational purposes only. Trading involves risk.
Max Pain Options [QuantLabs] v5 (Balanced)Institutional Grade Options Analysis: Max Pain, Gamma & Pin Risk
For years, TradingView users have been flying blind without access to Options Chain data. QuantLabs: Max Pain & Gamma Exposure changes that. This is not just a support/resistance indicator—it is a sophisticated, algorithmic model that reverse-engineers the incentives of Market Makers using synthetic Black-Scholes logic.
This tool visualizes the "invisible hand" of the market: the hedging requirements of large dealers who are forced to buy or sell to keep their books neutral.
CORE FEATURES:
🔴 Max Pain Gravity Model The bright red line represents the "Max Pain" strike—the price level where the maximum amount of Options Open Interest (Calls + Puts) expires worthless.
Theory: As OpEx (Expiration) approaches, Market Makers maximize profits by pinning the price to this level.
Strategy: Use this as a mean-reversion target. If price is far away, look for a snap-back to the red line.
🟣 Gamma Exposure Profiles (The Purple Lines) These neon histograms show you the estimated "Gamma Walls."
Long Gamma: Dealers trade against the trend (stabilizing price).
Short Gamma: Dealers trade with the trend (accelerating volatility).
Visual: The larger the purple bar, the harder it will be for price to break through that level.
📦 Algorithmic "Pin Risk" Zones The dashed red box highlights the "Kill Zone." When price enters this area near expiration, volatility often dies as dealers pin the asset to kill retail premiums.
Warning: Do not expect breakouts while inside the Pin Zone.
📊 Institutional HUD A clean, non-intrusive dashboard provides real-time Greeks and risk analysis:
Pin Risk: High/Medium/Low probability of a pinned close.
Exp Mode: Detects if the market is in "Short Gamma" (Squeeze territory) or "Long Gamma" (Chop territory).
HOW IT WORKS (The Math): Since live options data is not available via Pine Script, this engine uses a proprietary Synthetic OI Distribution Model. It inputs Volume, Volatility (IV), and Time-to-Expiry into a modified Black-Scholes equation to probability-map where the heavy open interest likely sits.
SETTINGS & CUSTOMIZATION:
Responsiveness: Tuned for the "Goldilocks Zone" (Spread: 12, Decay: 22) to catch local liquidity walls without over-fitting.
Visuals: Designed for Dark Mode. High-contrast Neon aesthetics for maximum readability.
SuperRSI: Enhanced MomentumSuperRSI is a next-generation momentum indicator designed to overcome the lag and noise found in the traditional Relative Strength Index (RSI). Unlike standard RSI which only looks at close prices, SuperRSI utilizes a unique "Titan Engine" logic that incorporates the full Price Range (Highs and Lows) to calculate momentum. This results in a smoother, more responsive oscillator that detects trend shifts earlier.
Key Features:
🚀 Range-Based Calculation: Factors in the expansion and contraction of price ranges, not just closing prices.
🎨 Dynamic Visuals: Beautiful gradient coloring that adapts to the trend (Bullish/Bearish) and visualizes Overbought/Oversold zones clearly.
⚡ Dual Signal System:
Slow Signal (Default): For reliable trend following.
Fast Signal (Optional): Can be enabled in settings for aggressive entries and scalping.
🔔 Comprehensive Alerts: Built-in alerts for RSI crossovers with Fast/Slow lines and Signal crossovers (Golden/Death Cross).
🛡️ Pine Script v6: Built on the latest version for maximum performance and stability.
How to Use:
Trend Confirmation: When the line is green and above 50, the trend is bullish. When red and below 50, the trend is bearish.
Overbought/Oversold: Look for reversals when the indicator exits the dotted zones (>80 or <20).
Signal Crossovers: Enable the "Fast Signal" in settings to trade the crossovers between the Fast and Slow signal lines (similar to MACD mechanics).
Settings:
Fully customizable colors and lengths.
Option to toggle the "Fast Signal" on or off (Hidden by default to keep the chart clean).
SuperBandsThis script combines two of the most powerful trading tools into a single indicator: Supertrend for trend following and Bollinger Bands for volatility analysis. This combo allows you to save your limited indicator slots on TradingView while keeping your chart clean.
Liquidity Maxing [JOAT]Liquidity Maxing - Institutional Liquidity Matrix
Introduction
Liquidity Maxing is an open-source strategy for TradingView built around institutional market structure concepts. It identifies structural shifts, evaluates trades through multi-factor confluence, and implements layered risk controls.
The strategy is designed for swing trading on 4-hour timeframes, focusing on how institutional order flow manifests in price action through structure breaks, inducements, and liquidity sweeps.
Core Functionality
Liquidity Maxing performs three primary functions:
Tracks market structure to identify when control shifts between buyers and sellers
Scores potential trades using an eight-factor confluence system
Manages position sizing and risk exposure dynamically based on volatility and user-defined limits
The goal is selective trading when multiple conditions align, rather than frequent entries.
Market Structure Engine
The structure engine tracks three key events:
Break of Structure (BOS): Price pushes beyond a prior pivot in the direction of trend
Change of Character (CHoCH): Control flips from bullish to bearish or vice versa
Inducement Sweeps (IDM): Market briefly runs stops against trend before moving in the real direction
The structure module continuously updates strong highs and lows, labeling structural shifts visually. IDM markers are optional and disabled by default to maintain chart clarity.
The trade engine requires valid structure alignment before considering entries. No structure, no trade.
Eight-Factor Confluence System
Instead of relying on a single indicator, Liquidity Maxing uses an eight-factor scoring system:
Structure alignment with current trend
RSI within healthy bands (different ranges for up and down trends)
MACD momentum agreement with direction
Volume above adaptive baseline
Price relative to main trend EMA
Session and weekend filter (configurable)
Volatility expansion/contraction via ATR shifts
Higher-timeframe EMA confirmation
Each factor contributes one point to the confluence score. The default minimum confluence threshold is 6 out of 8, but you can adjust this from 1-8 based on your preference for trade frequency versus selectivity.
Only when structure and confluence agree does the strategy proceed to risk evaluation.
Dynamic Risk Management
Risk controls are implemented in multiple layers:
ATR-based stops and targets with configurable risk-to-reward ratio (default 2:1)
Volatility-adjusted position sizing to maintain consistent risk per trade as ranges expand or compress
Daily and weekly risk budgets that halt new entries once thresholds are reached
Correlation cooldown to prevent clustered trades in the same direction
Global circuit breaker with maximum drawdown limit and emergency kill switch
If any guardrail is breached, the strategy will not open new positions. The dashboard clearly displays risk state for transparency.
Market Presets
The strategy includes configuration presets optimized for different market types:
Crypto (BTC/ETH): RSI bands 70/30, volume multiplier 1.2, enhanced ATR scaling
Forex Majors: RSI bands 75/25, volume multiplier 1.5
Indices (SPY/QQQ): RSI bands 70/30, volume multiplier 1.3
Custom: Default values for user customization
For crypto assets, the strategy automatically applies ATR volatility scaling to account for higher volatility characteristics.
Monitoring and Dashboards
The strategy includes optional monitoring layers:
Risk Operations Dashboard (top-right):
Trend state
Confluence score
ATR value
Current position size percentage
Global drawdown
Daily and weekly risk consumption
Correlation guard state
Alert mode status
Performance Console (top-left):
Net profit
Current equity
Win rate percentage
Average trade value
Sharpe-style ratio (rolling 50-bar window)
Profit factor
Open trade count
Optional risk tint on chart background provides visual indication of "safe to trade" versus "halted" state.
All visualization elements can be toggled on/off from the inputs for clean chart viewing or full telemetry during parameter tuning.
Alerts and Automation
The strategy supports alert integration with two formats:
Standard alerts: Human-readable messages for long, short, and risk-halt conditions
Webhook format: JSON-formatted payloads ready for external execution systems (optional)
Alert messages are predictable and unambiguous, suitable for manual review or automated forwarding to execution engines.
Built-in Validation Suite
The strategy includes an optional validation layer that can be enabled from inputs. It checks:
Internal consistency of structure and confluence metrics
Sanity and ordering of risk parameters
Position sizing compliance with user-defined floors and caps
This validation is optional and not required for trading, but provides transparency into system operation during development or troubleshooting.
Strategy Parameters
Market Presets:
Configuration Preset: Choose between Crypto (BTC/ETH), Forex Majors, Indices (SPY/QQQ), or Custom
Market Structure Architecture:
Pivot Length: Default 5 bars
Filter by Inducement (IDM): Default enabled
Visualize Structure: Default enabled
Structure Lookback: Default 50 bars
Risk & Capital Preservation:
Risk:Reward Ratio: Default 2.0
ATR Period: Default 14
ATR Multiplier (Stop): Default 2.0
Max Drawdown Circuit Breaker: Default 10%
Risk per Trade (% Equity): Default 1.5%
Daily Risk Limit: Default 6%
Weekly Risk Limit: Default 12%
Min Position Size (% Equity): Default 0.25%
Max Position Size (% Equity): Default 5%
Correlation Cooldown (bars): Default 3
Emergency Kill Switch: Default disabled
Signal Confluence:
RSI Length: Default 14
Trend EMA: Default 200
HTF Confirmation TF: Default Daily
Allow Weekend Trading: Default enabled
Minimum Confluence Score (0-8): Default 6
Backtesting Considerations
When backtesting this strategy, consider the following:
Commission: Default 0.05% (adjustable in strategy settings)
Initial Capital: Default $100,000 (adjustable)
Position Sizing: Uses percentage of equity (default 2% per trade)
Timeframe: Optimized for 4-hour charts, though can be tested on other timeframes
Results will vary significantly based on:
Market conditions and volatility regimes
Parameter settings, especially confluence threshold
Risk limit configuration
Symbol characteristics (crypto vs forex vs equities)
Past performance does not guarantee future results. Win rate, profit factor, and other metrics should be evaluated in context of drawdown periods, trade frequency, and market conditions.
How to Use This Strategy
This is a framework that requires understanding and parameter tuning, not a one-size-fits-all solution.
Recommended workflow:
Start on 4-hour timeframe with default parameters and appropriate market preset
Run backtests and study performance console metrics: focus on drawdown behavior, win rate, profit factor, and trade frequency
Adjust confluence threshold to match your risk appetite—higher thresholds mean fewer but more selective trades
Set realistic daily and weekly risk budgets appropriate for your account size and risk tolerance
Consider ATR multiplier adjustments based on market volatility characteristics
Only connect alerts or automation after thorough testing and parameter validation
Treat this as a risk framework with an integrated entry engine, not merely an entry signal generator. The risk controls are as important as the trade signals.
Strategy Limitations
Designed for swing trading timeframes; may not perform optimally on very short timeframes
Requires sufficient market structure to identify pivots; may struggle in choppy or low-volatility environments
Crypto markets require different parameter tuning than traditional markets
Risk limits may prevent entries during favorable setups if daily/weekly budgets are exhausted
Correlation cooldown may delay entries that would otherwise be valid
Backtesting results depend on data quality and may not reflect live trading with slippage
Design Philosophy
Many indicators tell you when price crossed a moving average or RSI left oversold. This strategy addresses questions institutional traders ask:
Who is in control of the market right now?
Is this move structurally significant or just noise?
Do I want to add more risk given what I've already done today/week?
If I'm wrong, exactly how painful can this be?
The strategy provides disciplined, repeatable answers to these questions through systematic structure analysis, confluence filtering, and multi-layer risk management.
Technical Implementation
The strategy uses Pine Script v6 with:
Custom types for structure, confluence, and risk state management
Functional programming approach for reusable calculations
State management through persistent variables
Optional visual elements that can be toggled independently
The code is open-source and can be modified to suit individual needs. All important logic is visible in the source code.
Disclaimer
This script is provided for educational and informational purposes only. It is not intended as financial, investment, trading, or any other type of advice or recommendation. Trading involves substantial risk of loss and is not suitable for all investors. Past performance, whether real or indicated by historical tests of strategies, is not indicative of future results.
No representation is being made that any account will or is likely to achieve profits or losses similar to those shown. In fact, there are frequently sharp differences between backtested results and actual results subsequently achieved by any particular trading strategy.
The user should be aware of the risks involved in trading and should trade only with risk capital. The authors and publishers of this script are not responsible for any losses or damages, including without limitation, any loss of profit, which may arise directly or indirectly from use of or reliance on this script.
This strategy uses technical analysis methods and indicators that are not guaranteed to be accurate or profitable. Market conditions change, and strategies that worked in the past may not work in the future. Users should thoroughly test any strategy in a paper trading environment before risking real capital.
Commission and slippage settings in backtests may not accurately reflect live trading conditions. Real trading results will vary based on execution quality, market liquidity, and other factors not captured in backtesting.
The user assumes full responsibility for all trading decisions made using this script. Always consult with a qualified financial advisor before making investment decisions.
Enjoy - officialjackofalltrades
Infinity Algo Backtest█ OVERVIEW
Infinity Algo Backtest is a strategy testing system with 5 entry modes, 6 take-profit levels, and optional Auto-Tune optimization (historical simulation).
Switch between trend-following, contrarian, and sniper entries within one strategy. Auto-Tune runs historical simulations across hundreds of parameter combinations and selects the best-scoring configuration based on your chosen metric (not predictive AI).
Includes trailing stop-loss options, optional add-on entries (pyramiding), and structured alert messages for automation.
█ KEY FEATURES
✅ 5 Entry Modes: Normal, Smart, AI, HL Sniper, AI Sniper
✅ 3 Exit Modes: Percentage targets, Signal step-outs, Opposite signal flip
✅ 6 Take-Profit Levels with customizable partial position sizing
✅ Trailing Stop-Loss (None / Breakeven / Moving Target)
✅ Auto-Tune Optimization (Walk-Forward or Static)
✅ Optional add-on entries (pyramiding)
✅ Structured alert messages for webhook automation
✅ Designed for crypto, forex, stocks, indices, and commodities
█ WHAT MAKES THIS STRATEGY DIFFERENT
🧠 Auto-Tune Engine
Unlike static strategies, this system tests 500+ parameter combinations — varying sensitivity (5-28), thresholds, and trigger configs — then selects the best-scoring settings from historical simulations.
Choose from 12 scoring metrics: Sharpe Ratio, Sortino Ratio, Calmar Ratio, SQN, Martin Ratio, GPR, Win Rate, Total Profit, Average Profit, Profit Factor, Sortino + Calmar Composite, and Robust Score.
Note: Auto-Tune is systematic parameter optimization on historical data — not predictive AI. Past performance does not guarantee future results.
🎯 Multi-Mode Entry System
Switch between trend-following, contrarian, and sniper modes — all within one strategy. No need to maintain multiple scripts.
🛡️ Adaptive Risk Management
Trailing SL modes that respond to your TP hits:
Breakeven: Locks in safety after your chosen TP is reached
Moving Target: Ratchets your stop to the previous TP level as profit grows
📊 Reproducible Results
Full transparency on strategy properties so you can replicate exact backtest conditions.
█ ENTRY ENGINES
Normal + Smart (Default)
Normal: Contrarian entries — momentum cross against the trend filter for reversal plays
Smart: Trend-following entries — momentum cross with the trend filter for continuation plays
Auto-Tune Mode
Tests 500+ parameter combinations against historical data
Simulates trades internally using your TP/SL configuration
Scores by your chosen metric (Sharpe, Sortino, Calmar, Win Rate, etc.)
Walk-Forward: Re-optimizes every N bars to adapt to regime changes
Static: Locks in best-scoring settings from full available history
HL Sniper
Trend-trigger mode for more selective entries
Fewer signals, but more selective setups
Auto-Tune Sniper
Optimizes RSI period, smoothing factor, and trigger sensitivity
Adapts sniper configuration based on historical performance
█ EXIT MODES
1) Percentage Targets
Up to 6 TP levels (TP1…TP6) with customizable partial exits
Configure both price distance (%) and position size (%) for each level
Designed for scaling out rather than all-in/all-out
2) Signal Step-Outs
Momentum-shift condition triggers partial exits
Optional higher-timeframe confirmation
"New TP Must Beat Last" prevents weak consecutive exits
3) Opposite Signal
Closes/flips position when the next opposite entry signal appears
Best for trend-following systems
█ USE CASES
📈 Trending Markets
Use "Smart" signals + Percentage TPs. Stay aligned with momentum while scaling out at multiple targets. Enable Moving Target trailing to lock in profits.
📉 Ranging / Choppy Markets
Use "Normal" signals (contrarian mode). Catch reversals at range boundaries. Tighter TP targets work better here.
⚡ High Volatility / News Events
Use "HL Sniper" for selective entries. Fewer signals, more selective. Wider SL to accommodate volatility.
🤖 Automation & Bots
Structured alert payloads work with popular bot platforms and custom webhooks. Entry + 6 TPs + SL in one alert.
█ HOW TO USE
Apply to your chart (any timeframe, any market)
Start with Entry Signals = "Normal + Smart", Exit Mode = "Percentage"
Pick your direction (Long / Short / Both)
Adjust signal thresholds and trend filter length to match your style
Configure TP% levels and Qty% — total should sum to 100%
Enable Stop-Loss and choose a trailing mode
Set commission and slippage in Strategy Properties for realistic results
Optional: Enable Auto-Tune for adaptive optimization
█ STRATEGY PROPERTIES
Default settings for reproducible backtests:
Initial capital: 10,000 USD
Order size type: Cash
Default order size: 10,000
Process orders on close: Enabled
Pyramiding: Controlled by "Allow Add-On Entries"
For realistic results, set commission and slippage in Strategy Properties to match your broker/exchange.
█ ALERTS & AUTOMATION
The strategy outputs structured alert payloads compatible with:
Popular bot platforms and webhook receivers
Custom automation systems (JSON format)
Setup: Create alert → Select "Order fills and alert() function calls" → Use {{strategy.order.alert_message}} placeholder
█ WORKS ON
Crypto
Forex
Stocks
Indices
Commodities
█ REALISTIC EXPECTATIONS
No strategy wins 100% of the time — this is no exception
Auto-Tune optimizes on past data — it cannot predict the future
Backtest results ≠ live results (fees, slippage, and emotions matter)
Always validate with out-of-sample data before going live
Use proper position sizing and risk management
█ LIMITATIONS
Backtests are simulations — results depend on market conditions, fees, slippage, and parameters
Auto-Tune can overfit if used without out-of-sample validation
Multi-timeframe exit logic confirms on higher-TF bar closes (slight delay expected)
Use standard candles/bars for strategy testing (avoid Heikin Ashi, Renko)
█ DISCLAIMER
This strategy is provided for educational and informational purposes only and does not constitute financial advice. Past performance is not indicative of future results. Trading involves substantial risk of loss, and you are solely responsible for your own trading decisions.
V3 Valentini Pro Scalper [Dashboard]Gemini 3.0 pro's take on Fabio Valentini's world #1 strategy scalp 12/19/2025
ML Adaptive SuperTrend Strategy [trade_crush]# ML Adaptive SuperTrend Strategy - User Guide
## Introduction
The **ML Adaptive SuperTrend Strategy** is a sophisticated trading tool that combines traditional trend-following logic with **Machine Learning (K-Means Clustering)** to dynamically adapt to market volatility. Unlike standard SuperTrend indicators that use a fixed ATR, this strategy analyzes historical volatility to categorize the current market into distinct clusters, providing more precise entries and exits.
>
> **Special Thanks:** This strategy is based on the innovative work of **AlgoAlpha**. You can explore their extensive library of high-quality indicators and strategies on TradingView: (www.tradingview.com).
---
## Machine Learning Engine (K-Means)
The core of this strategy is its ability to "learn" from recent market behavior.
- **K-Means Clustering**: The script takes the last $N$ bars of ATR data and runs an iterative clustering algorithm to find three "centroids" representing **High**, **Medium**, and **Low** volatility.
- **Adaptive ATR**: Based on the current volatility, the strategy selects the nearest centroid to use as the ATR value for the SuperTrend calculation. This ensures the trailing stop tightens during low volatility and widens during high volatility to avoid "noise".
---
## Key Features
### 1. Non-Repainting Signals
- **Confirm Signals**: When enabled, signals are only triggered after a bar closes. This ensures that the arrows and entries you see on the chart are permanent and reliable for backtesting.
### 2. Intelligent Risk Management
- **Multiple SL/TP Types**: Choose between **Percentage** based stops or **ATR** based stops for both Stop Loss and Take Profit.
- **Trailing Stop Loss (TSL)**:
- Supports both Percentage and ATR modes.
- **Activation Offset**: Only activates the trailing mechanism after the price has moved a certain percentage in your favor, protecting early-stage trades.
### 3. Risk-Based Position Sizing
- **Dynamic Quantity**: If enabled, the strategy automatically calculates the trade size based on your **Risk % Per Trade** and the distance to your **Stop Loss**. This ensures you never lose more than your defined risk on a single trade.
---
## User Input Guide
### SuperTrend & ML Settings
- **ATR Length**: The window used to calculate market volatility.
- **SuperTrend Factor**: The multiplier that determines the distance of the trailing stop from the price.
- **Use ML Adaptive ATR**: Toggle between the ML-enhanced logic and standard ATR.
- **Training Data Length**: How many historical bars the ML engine analyzes to find clusters.
### Risk Management
- **Stop Loss Type**: Set to Percentage, ATR, or None.
- **TS Activation Offset**: The profit buffer required before the trailing stop starts following the price.
- **Use Risk-Based Sizing**: Toggle this to let the script manage your position size automatically.
---
## How to Trade with This Strategy
1. **Monitor the Dashboard**: Check the top-right table to see which volatility cluster the market is currently in.
2. **Observe the Fills**: The adaptive fills (green/red) visualize the "breathing room" the strategy is giving the price.
3. **Execution**: The strategy enters on "ML Bullish" (Triangle Up) and "ML Bearish" (Triangle Down) signals.
4. **Exits**: The script will automatically exit based on your SL, TP, or Trailing Stop settings.
---
## Credits
Original Concept: **AlgoAlpha**
Strategy Conversion & Enhancements: **Antigravity AI**
Signal Algo - Elephant Edge Strategy🔶 Strategy Overview:
This strategy is designed for intraday trading and focuses on taking trades near important price reference areas instead of random market locations.
This strategy is designed to:
Take trades only near important price levels
Avoid random mid-market entries
Validate every trade using multiple confirmation filters
It combines the following core concepts:
Elephant Edge zones based on previous session volatility
Index & F&O strike price levels (psychological and liquidity-based levels)
Previous Day OHLC levels (important institutional reference prices)
The goal of this strategy is to allow trades only when price behavior is meaningful and occurs near key market reference areas, while filtering out low-quality signals. All filters are optional, allowing traders to customize the strategy according to their trading style, risk preference, and market conditions.
🔶 How to Use: Elephant Edge Support–Resistance
This strategy is based on the Elephant Edge Support–Resistance concept, where trades are taken only near important price zones instead of random market areas.
The image above shows how the strategy identifies Support Zones, Resistance Zones, and how trade entries and exits are generated.
🟩 Support Zones:
Shown as green areas. These are considered potential Buy zones.
A positive price reaction from these zones is required before a Buy entry is generated.
🟥 Resistance Zones:
Shown as red areas. These are considered potential Sell zones.
Price rejection from these zones is required before a Sell entry is generated.
Important:
The strategy does not blindly buy or sell at the zone. Entries are generated only after additional confirmation, such as: Candle structure validation, Directional filters, Optional, volume and time filters (if enabled)
Trade entries are generated only when price touches a Support or Resistance zone.
These zones represent areas where price is more likely to react, helping to avoid low-quality trades during sideways or random market movement.
Final Understanding:
This strategy is not about predicting the market. It is about reacting to price behavior at important levels and trading only when conditions are meaningful.
🔶 How to Use: Index Strike Price Support–Resistance
This concept is based on *Index & F&O Strike Price levels*, where trades are taken near important *round-number strike prices* (for example: every 50 or 100 points), instead of random price locations.
The image above shows how *strike prices act as natural Support and Resistance levels** in index trading.
🟩 Strike Price Support:
Strike levels below the current price act as potential Support zones. Price reaction from these levels is required before a Buy entry is generated.
🟥 Strike Price Resistance:
Strike levels above the current price act as potential Resistance zones. Price rejection from these levels is required before a Sell entry is generated.
Trade entries are generated only when price touches or reacts near a strike price level.
These levels represent *psychological and liquidity-based areas*, where price is more likely to pause, reverse, or react.
🔶 How to Use: Previous Day OHLC Levels
This concept is based on *Previous Day Open, High, Low, and Close (OHLC)* levels, which are widely used as *important market reference prices* by traders and institutions.
The image above shows how price reacts around Previous Day OHLC levels and how they act as natural *Support and Resistance areas** during intraday trading.
🟩 Previous Day Support Levels:
Previous Day Open, Low, or Close levels below the current price act as potential Support zones.
A positive price reaction from these levels is required before a Buy entry is generated.
🟥 Previous Day Resistance Levels:
Previous Day Open, High, or Close levels above the current price act as potential Resistance zones. Price rejection from these levels is required before a Sell entry is generated.
Trade entries are generated only when price touches or reacts near a Previous Day OHLC level.
These levels represent *high-interest price areas* where price is more likely to pause, reverse, or show strong reactions.
🔵 Strategy Setting Features Overview :
Trade Direction Controls : -
Buy Only When enabled: The strategy will generate only Buy trades All Sell signals are ignored Sell Only When enabled: The strategy will generate only Sell trades All Buy signals are ignored
Important Note If both Buy Only and Sell Only are enabled: The strategy can generate both Buy and Sell trades
Candle Direction & Color Filter : -
Available Options:
Both - Candle color is ignored Trades depend only on strategy logic
Trend - Buy → Green candles only. Sell → Red candles only
O-Trend - Buy → Red candles only. Sell → Green candles only
Continuous Buy / Sell Check : -
When enabled: Prevents repeated trades in the same direction Reduces over-trading during sideways markets Example: After a Buy trade, another Buy trade will not be taken immediately unless conditions reset.
Elephant Edge Percentile Levels : -
When enabled: Buy trades are allowed only near lower percentile levels Sell trades are allowed only near upper percentile levels
Why this matters: Percentile levels act as dynamic intraday support and resistance based on historical price movement.
Strike Price Level Filters : -
When enabled: Buy trades require price to touch lower strike zones Sell trades require price to touch upper strike zones
Why strike levels are important: Strike prices often act as psychological and liquidity zones, especially in index trading.
Previous Day OHLC Levels : -
When enabled: Draws Previous Day Open, High, Low, and Close on the chart Trades are allowed only when price touches any of these levels
Why Previous Day levels matter: These levels are widely watched by traders and institutions Price often reacts strongly near them Helps filter out low-probability trades
Stoploss Settings : -
Candle Touch: Stoploss triggers immediately when price touches the level
Candle Close: Stoploss triggers only after candle closes beyond the level
Stoploss Type Choose how stoploss distance is calculated:
Candle High / Low
Fixed Points
Percentage based
Trailing Stoploss : -
Trailing stoploss helps protect profits as price moves favorably. Trailing Mode
Points
Percentage
Trailing Activation Defines how much profit is required before trailing starts.
Candle Structure Filters : -
Candle Size : Filter Avoids trades on: Very small candles (low momentum) Extremely large candles (high risk)
Candle Body : Filter Ensures trades are taken only on candles with sufficient body strength.
Wick Filter : Filters out candles with unusually long wicks, which often indicate fake breakouts.
Hammer Candle Detection : -
Enable Hammer Pattern Detects hammer-type candles using wick-to-body ratios.
Useful for: Reversal-based setups near key levels
Entry & Stop Buffers : -
Buffers add small offsets to: Entry price Stoploss price
Purpose: Helps avoid false triggers caused by small price spikes or noise.
Volume-Based Validation : -
Use Volume Alert Validity Trades are allowed only after a high-volume candle appears.
Why volume matters: High volume confirms participation and interest.
Time & Trade Limits : -
Entry / Exit Time Restricts trades to specific market hours. Trade Count Limits Controls the maximum number of trades per session to avoid over-trading.
Quantity Calculation: -
Investment Amount Automatically calculates trade quantity based on capital amount.
Benefit: Helps maintain consistent risk across different instruments.
JSON Alert Output: -
Used for: Automation Broker integration This does not affect strategy logic.
⚠️ Disclaimer This strategy is provided for educational and research purposes only. Past performance does not guarantee future results. Users should test and manage risk independently.
Antigravity OCC Strategy (MA 5 + Delayed TSL)# OCC Strategy Optimized (MA 5 + Delayed TSL) - User Guide
## Introduction
The **OCC Strategy Optimized** is an enhanced version of the classic **Open Close Cross (OCC)** strategy. This strategy is designed for high-precision trend following, utilizing the crossover logic of Open and Close moving averages to identify market shifts. This optimized version incorporates advanced risk management, multi-timeframe analysis, and a variety of moving average types to provide a robust trading solution for modern markets.
>
> **Special Thanks:** This strategy is based on the original work of **JustUncleL**, a renowned Pine Script developer. You can find their work and profile on TradingView here: (in.tradingview.com).
---
## Key Features
### 1. Optimized Core Logic
- **MA Period (Default: 5):** The strategy is tuned with a shorter MA length to reduce lag and capture trends earlier.
- **Crossing Logic:** Signals are generated when the Moving Average of the **Close** crosses the Moving Average of the **Open**.
### 2. Multi-Timeframe (MTF) Analysis
- **Alternate Resolution:** Use a higher timeframe (Resolution Multiplier) to filter out noise. By default, it uses $3 \times$ your current chart timeframe to confirm the trend.
- **Non-Repainting:** Includes an optional delay offset to ensure signals are confirmed and do not disappear (repaint) after the bar closes.
### 3. Advanced Risk Management
This script features a hierarchical exit system to protect your capital and lock in profits:
- **Fixed Stop Loss (Initial):** Protects against sudden market reversals immediately after entry.
- **Delayed Trailing Stop Loss (TSL):**
- **Activation Delay:** The TSL only activates after the trade reaches a specific profit threshold (e.g., 1%). This prevents being stopped out too early in the trade's development.
- **Ratchet Trail:** Once activated, the stop loss "ratchets" up/down, never moving backward, ensuring you lock in profits as the trend continues.
- **Take Profit (TP):** A fixed percentage target to exit the trade at a pre-defined profit level.
### 4. Versatility
- **12 MA Types:** Choose from SMA, EMA, DEMA, TEMA, WMA, VWMA, SMMA, HullMA, LSMA, ALMA, SSMA, and TMA.
- **Trade Direction:** Toggle between Long-only, Short-only, or Both.
- **Visuals:** Optional bar coloring to visualize the trend directly on the candlesticks.
---
## User Input Guide
### Core Settings
- **Use Alternate Resolution?:** Enable this to use the MTF logic.
- **Multiplier for Alternate Resolution:** How many charts higher the "filter" timeframe should be.
- **MA Type:** Select your preferred moving average smoothing method.
- **MA Period:** The length of the Open/Close averages.
- **Delay Open/Close MA:** Use `1` or higher to force non-repainting behavior.
### Risk Management Settings
- **Use Trailing Stop Loss?:** Enables the TSL system.
- **Trailing Stop %:** The distance the stop follows behind the price.
- **TSL Activation % (Delay):** The profit % required before the TSL starts moving.
- **Initial Fixed Stop Loss %:** Your hard stop if the trade immediately goes against you.
- **Take Profit %:** Your ultimate profit target for the trade.
---
## How to Trade with This Strategy
1. **Identify the Trend:** Look for the Moving Average lines (Close vs Open) to cross.
2. **Wait for Confirmation:** If using MTF, ensure the higher timeframe also shows a trend change.
3. **Manage the Trade:** Let the TSL work. Once the trade hits the activation threshold, the TSL will take over, protecting your runner.
4. **Position Sizing:** Adjust the `Properties` tab in the script settings to match your desired capital allocation (Default is 10% of equity).
---
## Credits
Original Strategy by: **JustUncleL**
Optimized and Enhanced by: **Antigravity AI**
Standard Deviation Vidya Moving Average | QuantLapseStandard Deviation Vidya MA by QuantLapse
Overview
The Standard Deviation Vidya MA indicator by QuantLapse is an dynamic and unique trend-following tool that leverages Variable Index Dynamic Average (VIDYA) along with a statistical measure of standard deviation to assess trend strength, direction and volatility. By utilizing adaptive smoothing and volatility adjustment this indicator provides a more responsive and robust signal framework for traders.
______
Technical Composition, Calculation, Key Components & Features
📌 VIDYA (Variable Index Dynamic Average)
An adaptive moving average that automatically adjusts its sensitivity based on prevailing market volatility.
Employs a volatility-weighted smoothing constant derived from standard deviation ratios, allowing the average to respond faster during high-momentum phases and slow down during consolidation.
Reduces lag during trend expansion while suppressing noise in low-volatility environments.
Provides clearer trend structure and regime awareness compared to fixed-length moving averages.
Serves as a dynamic baseline for volatility envelopes and trend-state classification within the system.
📌 Volatility Adjustment – Standard Deviation
The system constructs a volatility-adaptive envelope around the VIDYA baseline using standard deviation, allowing band width to expand and contract dynamically with changing market conditions.
VIDYA’s smoothing factor is adjusted by comparing short-term and longer-term standard deviation, increasing responsiveness during volatility expansion and dampening noise during compression.
Upper and lower bands are calculated by applying a configurable standard deviation multiplier to the VIDYA value, creating a proportional volatility boundary rather than a fixed offset.
Price movement beyond these bands confirms volatility-supported momentum, while price contained within the bands signals consolidation or transitional phases.
📌 Trend Signal Calculation
A bullish trend state is triggered when price closes above the upper standard deviation band, indicating sustained upward momentum with volatility confirmation.
A bearish trend state is triggered when price closes below the lower band, confirming downside momentum under expanding volatility.
Once established, the trend state persists until an opposing volatility break occurs, reducing whipsaw and improving regime stability.
Trend direction is visually reinforced through dynamic color-coding of the VIDYA line and its envelope, providing immediate directional context at a glance.
______
How It Works in Trading
✅ Trend Strength Detection – Evaluates cumulative price movement over a defined window to assess directional conviction.
✅ Noise Reduction – Applies adaptive smoothing techniques to minimize whipsaws during choppy conditions.
✅ Dynamic Thresholding – Utilizes volatility-aware bands to define customizable trend continuation and invalidation levels.
✅ Color-Coded Visualization – Enhances chart readability by clearly distinguishing bullish, bearish, and neutral states.
______
Visual Representation
Trend Signals on Moving Average and Background Color:
🟢 Green/Teal Moving Average – Strong Uptrend
🔴 Red/Pink Candles – Strong Downtrend
✅ Long & Short Labels can be turned on or off for trade signal clarity.
📊 Display of entry & exit points based on entry and exit criteria's.
📊 Display of Indicators equity and buy and hold equity to compare performance.
______
Features and User Inputs
The Standard Deviation Vidya MA framework incorporates a flexible set of user-defined inputs designed to balance adaptability, clarity, and analytical control.
VIDYA Configuration – Customize the Variable Index Dynamic Average length and price source to control trend responsiveness based on volatility-adjusted smoothing.
Volatility & Deviation Controls – Adjust standard deviation lookback periods and multipliers to fine-tune adaptive upper and lower thresholds used for trend qualification.
Backtesting & Date Filters – Define a start date for historical evaluation and enable range filtering to analyze performance during specific market periods.
Display & Visualization Options – Toggle labels, equity curves, and visual overlays to tailor the chart presentation to personal trading preferences.
Color Customization – Fully configurable buy/sell colors for both trend signals and equity curves, allowing intuitive visual differentiation between bullish and bearish phases.
______
Practical Applications
The Standard Deviation VIDYA MA is designed for traders seeking an adaptive trend-following framework that dynamically responds to changing market volatility. By combining VIDYA’s volatility-sensitive smoothing with standard deviation–based thresholds, the indicator offers a robust approach to directional analysis across multiple market conditions.
Key applications include:
Adaptive Trend Identification – Detect sustained bullish and bearish trends using a volatility-adjusted moving average that automatically accelerates or slows based on market activity.
Volatility-Aware Entry & Exit Signals – Utilize standard deviation bands to define dynamic breakout and invalidation zones, helping reduce false signals during low-volatility consolidation phases.
Noise-Filtered Trend Participation – Avoid whipsaws by requiring price expansion beyond adaptive deviation thresholds before confirming trend direction.
Systematic Backtesting & Evaluation – Analyze historical trend performance using built-in equity curves and date filters to assess effectiveness across different market regimes.
Visual Trend Confirmation – Leverage color-coded VIDYA lines, deviation zones, and optional labels to clearly interpret trend state and momentum strength in real time.
This framework bridges volatility analysis with adaptive trend logic, providing a disciplined and data-driven method for trend participation while maintaining clarity and interpretability in live trading environments.
______
Conclusion
The Standard Deviation VIDYA MA by QuantLapse represents a modern evolution of adaptive trend analysis, blending volatility-weighted smoothing with statistically driven deviation thresholds. By integrating VIDYA’s responsiveness with standard deviation-based confirmation, the system delivers clearer trend structure, reduced noise, and more reliable directional context across varying market regimes.
This indicator is particularly well-suited for traders who value adaptability, clarity, and rule-based decision-making over static moving average techniques.
🔹 Who should use Standard Deviation VIDYA MA:
📊 Trend-Following Traders – Identify and stay aligned with sustained directional moves while avoiding premature reversals.
⚡ Momentum Traders – Capture volatility-supported expansions when price breaks beyond adaptive deviation bands.
🤖 Systematic & Algorithmic Traders – Ideal as a volatility-aware trend filter for rule-based entries, exits, and portfolio frameworks.
🔹 Disclaimer: Past performance does not guarantee future results. All trading involves risk, and no indicator or methodology can ensure profitability.
🔹 Strategic Advice: Always backtest thoroughly, optimize parameters responsibly, and align settings with your personal risk tolerance, timeframe, and market conditions before deploying the indicator in live trading.
Trend Core Strategy v1.0 - GUMROADLog Regression Channel Pro Strategy
This is a trend-following pullback strategy built for TradingView (Pine Script v6).
It uses logarithmic regression channels to define the market’s primary trend, and looks for low-risk pullback entries within strong trending conditions.
Momentum and trend strength filters are applied to avoid ranging or weak markets.
This strategy is designed to be used when the market is clearly trending, not during choppy or sideways price action.
Best Used When
Strong uptrend or downtrend is present
Price is pulling back toward the regression channel
Volatility is sufficient (ADX confirms trend strength)
Suitable for 1H / 4H timeframes
Commonly used on BTC, ETH, and major crypto pairs
Key Characteristics
Non-repainting logic
Volatility-based risk management (ATR)
Designed for realistic backtesting
No martingale, no grid, no over-optimization
Gumroad Disclaimer (3 Lines)
This strategy is provided for educational purposes only and is not financial advice.
Trading involves risk, and losses may occur.
You are fully responsible for your own trading decisions.
Ace Algo [Anson5129]🏆 Exclusive Indicator: Ace Algo
📈 Works for stocks, forex, crypto, indices
📈 Easy to use, real-time alerts, no repaint
📈 No grid, no martingale, no hedging
📈 One position at a time
----------------------------------------------------------------------------------------
Ace Algo
A trend-following TradingView strategy using a confluence of technical indicators and time-based rules for structured long/short entries and exits:
----------------------------------------------------------------------------------------
Parameters Explanation
Moving Average Length
Indicates the number of historical data points used for the average price calculation.
Shorter = volatile (short-term trends); longer = smoother (long-term trends, less noise).
Default: 20
Entry delay in bars
After a trade is closed, delay the next entry in bars. The lower the number, the more trades you will get.
Default: 4
Take Profit delay in bars
After a trade is opened, delay the take profit in bars. The lower the number, the more trades you will get.
Default: 3
Enable ADX Filter
No order will be placed when ADX < 20
Default: Uncheck
Block Period
Set a block period during which no trading will take place.
----------------------------------------------------------------------------------------
Entry Condition:
Only Long when the price is above the moving average (Orange line).
Only Short when the price is below the moving average (Orange line).
* Also, with some hidden parameter that I set in the backend.
Exit Condition:
When getting profit:
Trailing Stop Activates after a position has been open for a set number of bars (to avoid premature exits).
When losing money:
In a long position, when the price falls below the moving average, and the conditions for a short position are met, the long position will be closed, and the short position will be opened.
In a short position, when the price rises above the moving average, and the conditions for a long position are met, the short position will be closed, and the long position will be opened.
----------------------------------------------------------------------------------------
How to get access to the strategy
Read the author's instructions on the right to learn how to get access to the strategy.
Selected Days Indicator V3-TrDoes the stock drop every Wednesday? Do March months always move similarly? Does the 1st week of the month behave differently?
Do you ever say "it always makes this move in these months"? Don't you want to see more clearly whether it actually makes this move or not? Don't you want to see and test periodically repeating price patterns?
Hisse her Çarşamba düşüyor mu? Mart ayları hep benzer mi hareket ediyor? Ayın 1. haftası farklı mı davranıyor?
Bazen "bu aylarda hep bu hareketi yapıyor" dediğiniz oluyor mu? Gerçekten de bu hareketi yapıp yapmadığını daha net görmek istemez misiniz? Periyodik tekrarlayan fiyat kalıplarını görmek ve test etmek istemiyor musunuz?
1. Problem
Some stocks or crypto assets exhibit systematic behaviors on certain days, weeks, or months. But it's hard to see - everything is mixed together on the chart. This indicator isolates the days/weeks/months you want and shows only them. Hides everything else.
2. How It Works
Three-layer filter: Day (Monday, Tuesday...), Week (1st, 2nd, 3rd week of the month), Month (January, February...). Select what you want, let the rest disappear. Example: Show only Thursdays of March-June-September. Or compare every 1st week of the month. View as candlestick, line, or column chart.
3. What's It Good For?
Test "end-of-month effect". Find "day-of-the-week anomaly". Analyze crypto volatility by days. See seasonality in commodities. Discover patterns specific to your own strategy. Past data doesn't guarantee the future but provides statistical advantage.
Momentum Quality Index Strategyfiles.fm
Welcome to the Momentum Quality Index Strategy!
This is a fairly conservative strategy with a sharp criteria for entries and taking profits. This strategy has been tested amongst the top 50 stocks with volatility over 2%, and the verdict was that the profitability was often times over 85% profitability, often times reaching over 90% profitability. This strategy thrives in more volatile environments, often times beating the buying and holding strategy YTD performance by large margins.
This strategy is highly optimized for the 30 minute chart, giving insights into shorter term movements. It is based on cash trades of $1,000 per position, with a maximum of 4 trades being placed at once.
This strategy is optimized for common stock trading in more liquid markets, and not yet optimized for options trading (however I plan on developing highly profitable strategies for this purpose soon). The take profit is customizable.
I would refer to the image link I have posted at the top of this article for the strategy's effectiveness. The strategy report on this article isn't accurate, as this strategy is based on trading $1,000 per trade, therefore over longer term periods of time will not be as successful due to the fact that there is no compounding. However, over the course of smaller time frames (such as one year), it beats buying and holding of many assets.
This strategy is meant for day trading and short term swing trading, and is not meant to beat buying and holding of successful assets over the course of long periods of time.
Volatility Targeting: Single Asset [BackQuant]Volatility Targeting: Single Asset
An educational example that demonstrates how volatility targeting can scale exposure up or down on one symbol, then applies a simple EMA cross for long or short direction and a higher timeframe style regime filter to gate risk. It builds a synthetic equity curve and compares it to buy and hold and a benchmark.
Important disclaimer
This script is a concept and education example only . It is not a complete trading system and it is not meant for live execution. It does not model many real world constraints, and its equity curve is only a simplified simulation. If you want to trade any idea like this, you need a proper strategy() implementation, realistic execution assumptions, and robust backtesting with out of sample validation.
Single asset vs the full portfolio concept
This indicator is the single asset, long short version of the broader volatility targeted momentum portfolio concept. The original multi asset concept and full portfolio implementation is here:
That portfolio script is about allocating across multiple assets with a portfolio view. This script is intentionally simpler and focuses on one symbol so you can clearly see how volatility targeting behaves, how the scaling interacts with trend direction, and what an equity curve comparison looks like.
What this indicator is trying to demonstrate
Volatility targeting is a risk scaling framework. The core idea is simple:
If realized volatility is low relative to a target, you can scale position size up so the strategy behaves like it has a stable risk budget.
If realized volatility is high relative to a target, you scale down to avoid getting blown around by the market.
Instead of always being 1x long or 1x short, exposure becomes dynamic. This is often used in risk parity style systems, trend following overlays, and volatility controlled products.
This script combines that risk scaling with a simple trend direction model:
Fast and slow EMA cross determines whether the strategy is long or short.
A second, longer EMA cross acts as a regime filter that decides whether the system is ACTIVE or effectively in CASH.
An equity curve is built from the scaled returns so you can visualize how the framework behaves across regimes.
How the logic works step by step
1) Returns and simple momentum
The script uses log returns for the base return stream:
ret = log(price / price )
It also computes a simple momentum value:
mom = price / price - 1
In this version, momentum is mainly informational since the directional signal is the EMA cross. The lookback input is shared with volatility estimation to keep the concept compact.
2) Realized volatility estimation
Realized volatility is estimated as the standard deviation of returns over the lookback window, then annualized:
vol = stdev(ret, lookback) * sqrt(tradingdays)
The Trading Days/Year input controls annualization:
252 is typical for traditional markets.
365 is typical for crypto since it trades daily.
3) Volatility targeting multiplier
Once realized vol is estimated, the script computes a scaling factor that tries to push realized volatility toward the target:
volMult = targetVol / vol
This is then clamped into a reasonable range:
Minimum 0.1 so exposure never goes to zero just because vol spikes.
Maximum 5.0 so exposure is not allowed to lever infinitely during ultra low volatility periods.
This clamp is one of the most important “sanity rails” in any volatility targeted system. Without it, very low volatility regimes can create unrealistic leverage.
4) Scaled return stream
The per bar return used for the equity curve is the raw return multiplied by the volatility multiplier:
sr = ret * volMult
Think of this as the return you would have earned if you scaled exposure to match the volatility budget.
5) Long short direction via EMA cross
Direction is determined by a fast and slow EMA cross on price:
If fast EMA is above slow EMA, direction is long.
If fast EMA is below slow EMA, direction is short.
This produces dir as either +1 or -1. The scaled return stream is then signed by direction:
avgRet = dir * sr
So the strategy return is volatility targeted and directionally flipped depending on trend.
6) Regime filter: ACTIVE vs CASH
A second EMA pair acts as a top level regime filter:
If fast regime EMA is above slow regime EMA, the system is ACTIVE.
If fast regime EMA is below slow regime EMA, the system is considered CASH, meaning it does not compound equity.
This is designed to reduce participation in long bear phases or low quality environments, depending on how you set the regime lengths. By default it is a classic 50 and 200 EMA cross structure.
Important detail, the script applies regime_filter when compounding equity, meaning it uses the prior bar regime state to avoid ambiguous same bar updates.
7) Equity curve construction
The script builds a synthetic equity curve starting from Initial Capital after Start Date . Each bar:
If regime was ACTIVE on the previous bar, equity compounds by (1 + netRet).
If regime was CASH, equity stays flat.
Fees are modeled very simply as a per bar penalty on returns:
netRet = avgRet - (fee_rate * avgRet)
This is not realistic execution modeling, it is just a simple turnover penalty knob to show how friction can reduce compounded performance. Real backtesting should model trade based costs, spreads, funding, and slippage.
Benchmark and buy and hold comparison
The script pulls a benchmark symbol via request.security and builds a buy and hold equity curve starting from the same date and initial capital. The buy and hold curve is based on benchmark price appreciation, not the strategy’s asset price, so you can compare:
Strategy equity on the chart symbol.
Buy and hold equity for the selected benchmark instrument.
By default the benchmark is TVC:SPX, but you can set it to anything, for crypto you might set it to BTC, or a sector index, or a dominance proxy depending on your study.
What it plots
If enabled, the indicator plots:
Strategy Equity as a line, colored by recent direction of equity change, using Positive Equity Color and Negative Equity Color .
Buy and Hold Equity for the chosen benchmark as a line.
Optional labels that tag each curve on the right side of the chart.
This makes it easy to visually see when volatility targeting and regime gating change the shape of the equity curve relative to a simple passive hold.
Metrics table explained
If Show Metrics Table is enabled, a table is built and populated with common performance statistics based on the simulated daily returns of the strategy equity curve after the start date. These include:
Net Profit (%) total return relative to initial capital.
Max DD (%) maximum drawdown computed from equity peaks, stored over time.
Win Rate percent of positive return bars.
Annual Mean Returns (% p/y) mean daily return annualized.
Annual Stdev Returns (% p/y) volatility of daily returns annualized.
Variance of annualized returns.
Sortino Ratio annualized return divided by downside deviation, using negative return stdev.
Sharpe Ratio risk adjusted return using the risk free rate input.
Omega Ratio positive return sum divided by negative return sum.
Gain to Pain total return sum divided by absolute loss sum.
CAGR (% p/y) compounded annual growth rate based on time since start date.
Portfolio Alpha (% p/y) alpha versus benchmark using beta and the benchmark mean.
Portfolio Beta covariance of strategy returns with benchmark returns divided by benchmark variance.
Skewness of Returns actually the script computes a conditional value based on the lower 5 percent tail of returns, so it behaves more like a simple CVaR style tail loss estimate than classic skewness.
Important note, these are calculated from the synthetic equity stream in an indicator context. They are useful for concept exploration, but they are not a substitute for professional backtesting where trade timing, fills, funding, and leverage constraints are accurately represented.
How to interpret the system conceptually
Vol targeting effect
When volatility rises, volMult falls, so the strategy de risks and the equity curve typically becomes smoother. When volatility compresses, volMult rises, so the system takes more exposure and tries to maintain a stable risk budget.
This is why volatility targeting is often used as a “risk equalizer”, it can reduce the “biggest drawdowns happen only because vol expanded” problem, at the cost of potentially under participating in explosive upside if volatility rises during a trend.
Long short directional effect
Because direction is an EMA cross:
In strong trends, the direction stays stable and the scaled return stream compounds in that trend direction.
In choppy ranges, the EMA cross can flip and create whipsaws, which is where fees and regime filtering matter most.
Regime filter effect
The 50 and 200 style filter tries to:
Keep the system active in sustained up regimes.
Reduce exposure during long down regimes or extended weakness.
It will always be late at turning points, by design. It is a slow filter meant to reduce deep participation, not to catch bottoms.
Common applications
This script is mainly for understanding and research, but conceptually, volatility targeting overlays are used for:
Risk budgeting normalize risk so your exposure is not accidentally huge in high vol regimes.
System comparison see how a simple trend model behaves with and without vol scaling.
Parameter exploration test how target volatility, lookback length, and regime lengths change the shape of equity and drawdowns.
Framework building as a reference blueprint before implementing a proper strategy() version with trade based execution logic.
Tuning guidance
Lookback lower values react faster to vol shifts but can create unstable scaling, higher values smooth scaling but react slower to regime changes.
Target volatility higher targets increase exposure and drawdown potential, lower targets reduce exposure and usually lower drawdowns, but can under perform in strong trends.
Signal EMAs tighter EMAs increase trade frequency, wider EMAs reduce churn but react slower.
Regime EMAs slower regime filters reduce false toggles but will miss early trend transitions.
Fees if you crank this up you will see how sensitive higher turnover parameter sets are to friction.
Final note
This is a compact educational demonstration of a volatility targeted, long short single asset framework with a regime gate and a synthetic equity curve. If you want a production ready implementation, the correct next step is to convert this concept into a strategy() script, add realistic execution and cost modeling, test across multiple timeframes and market regimes, and validate out of sample before making any decision based on the results.






















