My Price Curtain by @magasine - v20251217**My Price Curtain by @magasine - v20251217**
This is a highly visual and practical TradingView overlay indicator designed to help traders quickly assess price position relative to a reference average (either a dynamic Simple Moving Average or a user-defined fixed price, such as a personal average entry cost).
### Key Features & Value for Traders:
- **Dynamic Price Curtain Background**
The entire chart background is lightly tinted green when price is above the average, red when below, or gray when at parity. This instant color feedback provides an immediate sense of bullish/bearish bias without needing to interpret lines or oscillators.
- **Deviation Zones (Optional)**
When enabled, semi-transparent horizontal bands appear above (green) and below (red) the average price, sized according to a user-defined percentage deviation (default 5%). These zones act as visual "fair value" corridors, highlighting over-extension or potential mean-reversion areas.
- **Persistent Horizontal Reference Lines**
- Solid blue line: the current average price (SMA or fixed)
- Dotted lines: upper and lower deviation zone boundaries
- Thin trailing line (when using SMA): connects previous SMA values for smoother trend visualization
- **Real-Time Information Panel**
A clean table in the bottom-right corner displays:
- Current average price and type (SMA(length) or FIXED)
- Latest close price
- Percentage distance from the average
- Total candles above/below the average (with percentages)
- Current position status (ABOVE/BELOW/AT AVERAGE) with color-coded highlighting
- **Additional Visual Cues**
- Small triangle markers on crossovers/crossunders of the average price
- Floating label on the last bar showing the average and current % deviation
- **Optional Cross Alerts**
Configurable alerts fire when price crosses above or below the reference average, including price, average, and deviation details.
### Why Traders Love It:
- Perfect for position traders monitoring performance relative to their average cost
- Great for mean-reversion or range-bound strategies using the deviation zones
- Excellent contextual awareness tool on any timeframe or asset
- Clean, non-cluttered design that enhances rather than overwhelms price action
In short, My Price Curtain transforms a simple moving average into a powerful, intuitive "price sentiment dashboard" that delivers instant visual context and actionable information at a glance.
Donations: linktr.ee
Portfolio management
QuantLabs The MTF Nasdaq 30 Scanner [Capital Flow and Pressure]Trading the QQQ (Nasdaq) without knowing what the Generals (Apple, Nvidia, Microsoft) are doing is like driving at night with your headlights off. You might see the road right in front of you, but you'll miss the turn coming up.
The QuantLabs MTF Nasdaq 30 Scanner is not just a trend indicator, it is a professional-grade Market Dashboard that visualizes the heartbeat of the entire Nasdaq 100.
Why You Need This
Standard indicators lag. They tell you what happened after the move. This Heatmap tracks the Real-Time Capital Flow of the Top 30 companies that actually move the index ($Trillions in Market Cap).
Key Features
1. The "Spectacular" Precision Heatmap
Organized by Market Cap Size (AAPL/NVDA first).
Instantly spot divergent behavior. Is the market rallying, or is it just Nvidia holding everything up? The Heatmap reveals the truth instantly.
Colors: Neon Cyan (Bullish) vs Hot Pink (Bearish).
2. Triple Spectrum Technology (3-in-1 Timeframes) Why look at one timeframe when you can see three? Every cell in the dashboard displays the trend distance for:
8h (Fast): For scalping entries.
16h (Mid): For swing trends.
24h (Slow): For the major "Big Picture" bias.
Values denote % distance from the Flux Ribbon.
3. The "Net Pressure" Gauge (The Speedometer) A predictive summary footer that calculates the Weighted Pressure of the entire market.
HEAVY (> 0.5%): Strong Trend / Breakout Mode.
MODERATE (0.2% - 0.5%): Healthy, sustained move.
FLAT: Chop / Noise. Stay out.
It also shows exactly how much Capital ($Trillions) is sitting Bullish vs Bearish.
How to Trade with It
Check the "Net Pressure": If it says MODERATE BULLISH, you are looking for Longs only.
Scan the Top Row: Are the "Big 5" (AAPL, NVDA, MSFT...) aligned with the pressure?
Wait for Alignment: If the 8h, 16h, and 24h metrics all turn Cyan, that is a "Quantum Lock"—a high probability breakout signal.
Simple. Powerful. Neon. Add it to your chart and stop guessing the direction.
Credits: Built with 💜 by David James @ QuantLabs
Market Internal Overlay - Skew and Put/Call RatioTracks both the CBOE:SKEW and INDEX:CPC and will highlight when certain thresholds are met.
Blue candle = skew is below 125 (low relative levels of hedging occurring)
Gray candle = skew is above 150 (higher relative levels of hedging occurring)
Red candle = 10 DMA of the put/call ratio is above 1.0 (signaling potential overbought territory)
Green candle = 10 DMA of the put/call ratio is below 0.80 (signaling potential oversold territory)
Purple candle = Both signals are occurring (in either direction)
To view the candle overlay, either switch the price data off, or change the colors to be darker and more transparent.
Live Position Duration TrackerDescription:
This indicator is designed to track the precise duration of your trades, helping traders manage their psychology by monitoring how long a position has been in profit or loss. It supports up to 3 entries (Initial + 2 Scale-ins) and automatically calculates the weighted average cost.
Key Features:
Real-time Duration Tracking: Displays total time in profit vs. loss and the current consecutive streak.
Max Loss Duration: Tracks the longest time the position has stayed in a losing state during the trade.
Multi-Entry Support: Input up to 3 entry prices and times to automatically update your average cost line on the chart.
Customizable UI: Toggle between English and Traditional Chinese. You can also choose the table's position.
Advanced Alerts: Get notified when total profit/loss time or consecutive loss duration exceeds your pre-set limits.
How to Use:
Set your initial entry price and time (use the chart-click confirmation).
Add scale-in details (Price 2 & 3) if necessary.
Monitor the dashboard for time-based risk management.
Lot Size CalculatorSimple indicator that calculating how many shares you can buy based on your deposit.
RunRox - Pairs Screener📊 Pairs Screener is part of our premium suite for pair trading.
This indicator is designed to scan and rank the most profitable and optimal pairs for the Pairs Strategy. The screener can backtest multiple metrics on deep historical data and display results for many pairs against one base asset at the same time.
This allows you to quickly detect market inefficiencies and select the most promising pairs for live trading.
HOW DOES THIS STRATEGY WORK⁉️
The core idea of the strategy is described in detail in our main indicator Pairs Strategy from the same product line.
There you can find a full explanation of the concept, the math behind pair trading, and the internal logic of the engine.
The Pairs Screener is built on top of the same core technology as the main indicator and uses the same internal logic and calculations.
It is designed as a key companion tool to the main strategy: it helps you find tradeable pairs, evaluate current deviations, sort and filter lists of candidates, and much more. All of these features will be described in this post.
✅ KEY FEATURES
More than 400+ assets available for scanning
Forex assets
Crypto assets
Lower Timeframe Backtester Strategy support
Invert signals mode
Hedge Coefficient (position size balancing between both legs)
6 hedge modes
Stop Loss support
Take Profit support
Whitelist with your own custom asset list
Blacklist to exclude unwanted assets
Custom filters
12 tracking metrics for pair evaluation
Customizable alerts
And many other tools for fine-tuning your search
The screener runs backtests simultaneously across a large number of assets and calculates metrics automatically.
This helps you very quickly find pairs with strong structural relationships or current inefficiencies that can be used as the basis for your pair trading strategies.
⚙️ MAIN SETTINGS
The first section controls the core parameters of the screener: Score, correlation, asset groups for scanning, and other base settings. All major crypto and forex symbols are embedded directly into the screener.
Since there are more than 400 assets, it is technically impossible to analyze everything at once, so we grouped them into batches of 40 assets per group.
The workflow is simple:
Open the chart of the asset you want to use as the base ticker.
In the screener settings choose the market (Crypto or Forex).
Select a Group (for example, Group 1) and the indicator will scan all assets inside that group against your base ticker.
Then you switch to Group 2, Group 3, etc., and repeat the scan.
Embedded universe:
400+ assets total
350+ Crypto – split into 10 groups
70+ Forex – split into 3 groups
Below is a description of each setting.
🔸 Exclude Dates
Allows you to specify a period that should be excluded from analysis.
Useful for removing abnormal spikes, news events, or any non-typical segments that distort the statistics for your pairs.
🔸 Market
Defines which universe will be used to build pairs with the current main asset:
Crypto – 350+ crypto symbols
Forex – 70+ FX symbols
Whitelist – your own custom list of assets
🔸 Group
Selects the asset group to scan.
As mentioned above, assets are split into groups of about 40 instruments:
350+ Crypto → 10 groups
70+ Forex → 3 groups
The screener will calculate all metrics only for the group you select.
🔸 Lower Timeframe
This option enables deep history analysis.
Each TradingView plan has a limit on the number of visible bars (for example, 5,000 bars on the basic plan). In standard mode you would only get statistics for the last 5,000 bars of your current timeframe.
If you want a deeper backtest on a lower timeframe, you can do the following:
Suppose your target timeframe for analysis is 5 minutes.
Switch your chart to a 30-minute timeframe.
Enable Lower Timeframe in the indicator.
Select 5 minutes as the lower timeframe inside the screener.
In this mode the screener can reconstruct and analyze up to 99,000 bars of data for your assets. This allows you to evaluate pairs on a much deeper history and see whether the results are stable over a larger sample.
🔸 Method
Here you choose the deviation model:
preferred Z-Score or S-Score for your analysis,
plus you can enable Invert to search for negatively correlated pairs and calculate their profit correctly.
🔸 Period
This is the lookback period for Z/S Score.
It defines how many bars are used to calculate the deviation metric for each pair.
🔸 Correlation Period
This is the number of bars used to calculate correlation between the base asset and each candidate in the group.
The resulting correlation value is also displayed in the results table.
🔀 HEDGE COEFFICIENT
The next block of settings is related to the hedge coefficient.
This defines how much margin is allocated to each leg of the pair.
The classic approach in pair trading is to split the position equally between both assets.
For example, if you allocate 100 USD to a trade , the standard model would open 50 USD long on one asset and 50 USD short on the other.
This works well for pairs with similar volatility , such as BTCUSDT / ETHUSDT
However, if you use a pair like BTCUSDT / DOGEUSDT , the volatility of these assets is very different.
They can still be correlated, but their amplitude is not the same. While Bitcoin might move 2% , Dogecoin can move 10% over the same period.
Because of that, for pairs with strongly different volatility, we can use a hedge coefficient and, for example, enter with 30 USD on one leg and 70 USD on the other, taking the volatility difference into account.
This is the main idea behind the Hedge Coefficient section and its primary use.
The indicator includes 6 methods of calculating the coefficient:
Cumulative RMA
Beta OLS
Beta TLS
Beta EMA
RMA Range
RMA Delta
Each method uses a different formula to compute the hedge coefficient and to size the position based on different metrics of the assets.
We leave it to the trader to decide which algorithm works best for their specific pair and style.
Below are the settings inside this section:
🔹 Method
When Auto Hedge is enabled, you can select which method to use from the list above.
The chosen method will automatically calculate the hedge coefficient between the two legs.
🔹 Hedge Coefficient
This is the manual hedge ratio per trade when Auto Hedge is disabled.
By default it is set to 1, which means the position is opened 50/50 between the two assets.
🔹 Min Allowed Hedge Coef.
This is the minimum allowed hedge coefficient.
By default it is 0.2, which means the model will not go below a 20% / 80% split between the legs.
🔹 MA Length
For methods that use moving averages (for example Beta EMA), this parameter sets the period used to calculate the hedge coefficient.
💰 STRATEGY SETTINGS
This section defines the base backtesting settings for all assets in the screener.
Here you configure entries, exits, Stop Loss, and other parameters used to find the most optimal pairs for your strategy. 🔸 Commission %
In this field you set your broker’s fee percentage per trade.
The indicator automatically calculates the correct commission for each leg of every trade. You only need to input the real commission rate that your broker charges for volume. No additional manual calculations are required.
🔸 Qty $
The margin amount used for backtesting across all assets in the screener.
This margin is split between both legs of the pair either equally or according to the selected hedge coefficient.
🔸 Entry
The Z/S Score deviation level at which the backtest opens a trade for each pair.
🔸 Exit
The Z/S Score level at which the backtest closes trades for the tested assets.
🔸 Stop Loss
PnL threshold at which a trade is force-closed during the historical test.
🔸 Cooldown
Number of bars the strategy will wait after a Stop Loss before opening the next trade.
This block gives you flexible control over how your strategy is tested on 400+ assets, helping you standardize the rules and compare pairs under the exact same conditions.
🗒️ WHITELIST
In this section you can define your own custom list of assets for monitoring and backtesting.
This is useful if you want to work with symbols that are not included in the built-in lists, such as exotic crypto from smaller exchanges, specific stocks, or any custom universe 🔹 Exchange Prefix
Enter the exchange prefix used for your tickers.
Example: BINANCE, OANDA, etc.
🔹 Ticker Postfix
Enable this option if the tickers require a postfix.
Example 1: .P for Binance Futures perpetual contracts.
Example 2: USDT if you only provide the base asset in the ticker list.
🔹 Ticker List
Enter a comma-separated list of tickers to analyze.
Example 1: BTCUSDT, ETHUSDT, BNBUSDT (when the exchange prefix is set).
Example 2: BTC, ETH, BNB (when using postfix USDT).
Example 3: BINANCE:BTCUSDT.P, OANDA:EURUSD (when different exchanges are used and the prefix option is disabled).
This gives you full flexibility to build a screener universe that matches exactly the assets you trade.
⛔ BLACKLIST
In this section you can enable a blacklist of unwanted assets that should be skipped during analysis. Enter a comma-separated list of tickers to exclude from the screener:
Example 1: BTCUSDT, ETHUSDT
Example 2: BTC, ETH (all tickers that contain these symbols will be excluded)
This helps you quickly remove illiquid, noisy, or unwanted instruments from the results without changing your main groups or whitelist.
📈 DASHBOARD
This section controls the results dashboard: table position, style, and sorting logic.
Here is what you can configure:
Result Table – position of the results table on the chart.
Background / Text – colors and opacity for the table background and text.
Table Size – overall size of the results table (from 0 to 30).
Show Results – how many rows (pairs) to display in the table.
Sort by (stat) – which metric to use for sorting the results.
Available options: Profit Factor, Profit, Winrate, Correlation, Score.
This lets you quickly focus on the most interesting pairs according to the exact metric that matters most for your strategy.
📎 FILTER SETTINGS
This section lets you filter the results table by metric values.
For example, you can show only pairs with a minimum correlation of 0.8 to focus on more stable relationships. 🔸 Min Correlation
Minimum allowed correlation between the two assets over the selected lookback period.
🔸 Min Score
Minimum absolute Score (Z-Score or S-Score) required to include a pair in the results.
For example, 2.0 means only pairs with Score >= 2.0 or <= -2.0 will be displayed.
🔸 Min Winrate
Minimum win rate percentage for a pair to be included in the table.
🔸 Min Profit Factor
Minimum profit factor required for a pair to stay in the results. These filters help you quickly narrow the list down to pairs that meet your quality criteria and match your risk profile.
📌 COLUMN SELECTION
This section lets you fully customize which metrics are displayed in the results table.
You can enable or hide any column to focus only on the data you need to identify the best pairs for trading. The screener allows you to show up to 12 metrics at the same time, which gives a detailed view of pair quality. Available columns:
🔹 Exchange Prefix
Show the exchange prefix in the ticker.
🔹 Correlation
Correlation between the two assets’ prices over the lookback period.
🔹 Score
Current Score value (Z-Score or S-Score).
On lower timeframe research, Score is not displayed.
🔹 Spread
Shows spread as % change since entry.
Positive value = profit on the main position.
🔹 Unrealized PnL
Shows unrealized PnL as a $ value based on current prices.
🔹 Profit
Total profit from all trades: Gross Profit − Gross Loss.
🔹 Winrate
Percentage of profitable trades out of all executed trades.
🔹 Profit Factor
Gross Profit / Gross Loss.
🔹 Trades
Total number of trades.
🔹 Max Drawdown
Maximum observed loss from peak to trough before a new peak is made.
🔹 Max Loss
Largest loss recorded on a single trade.
🔹 Long/Short Profit
Separate profit/loss for long trades and short trades.
🔹 Avg. Trade Time
Average duration of trades.
All these metrics are designed to help you quickly identify the strongest pairs for your strategy.
You can change colors, opacity, and hide any columns that are not relevant to your workflow.
🔔 ALERT
The alert system in this screener works in a specific way.
Alerts are tied directly to the filters you set in the Filter Settings section:
Minimum Correlation
Minimum Score
Minimum Winrate
Minimum Profit Factor
You can configure alerts to trigger when a new pair appears that matches all your filter conditions. 💡 Example
You set:
Minimum Score = 3
Then you create an alert based on the screener.
When any pair reaches a Score greater than +3 or less than −3, you will receive a notification.
This is how alerts work in this screener.
The idea is to deliver the most relevant information about the current market situation without forcing you to watch the screener all the time.
Supported placeholders for alert messages: {{ticker_1}} – main ticker (the one on the chart).
{{ticker_2}} – the paired ticker listed in the table.
{{corr}} – correlation value.
{{score}} – Score value (Z-Score or S-Score).
{{time}} – bar open time (UTC).
{{timenow}} – alert trigger time (UTC). You can use these placeholders to build alert text or JSON payloads in any format required by your tools.
The screener is designed to significantly enhance your pair trading workflow: it helps you quickly identify working pairs and current market inefficiencies, and with the alert system you can react to opportunities without constantly sitting in front of the screen.
Always remember that past performance does not guarantee future results.
Use the screener data within a risk-controlled trading system and adjust position sizing according to your own risk management rules.
RunRox - Pairs Strategy🧬 Pairs Strategy is a new indicator by RunRox included in our premium subscription.
It is a specialized tool for trading pairs, built around working with two correlated instruments at the same time.
The indicator is designed specifically for pair trading logic: it helps track the relationship between two assets, identify statistical deviations, and generate signals for opening and managing long/short combinations on both legs of the pair.
Below in this description I will go through the core functions of the indicator and the main concepts behind the strategy so you can clearly understand how to apply it in your trading.
📌 CONCEPT
The core idea of pair trading is to find and trade correlated instruments that usually move in a similar way.
When these two assets temporarily diverge from each other, a trading opportunity appears.
In such moments, the relatively overvalued asset is sold (short leg), and the relatively undervalued asset is bought (long leg).
When the spread between them narrows and both instruments revert back toward their typical relationship (mean), the position is closed and the trader captures the profit from this convergence.
In practice, one leg of the pair can end up in a loss while the other generates a larger profit.
Due to the difference in performance between the two assets, the combined result of the pair trade can still be positive.
✅ KEY FEATURES:
2 deviation types (Z-Score and S-Score)
Invert signals mode
Hedge Coefficient (position size balancing between both legs)
6 hedge modes
Entries based on Score or RSI
Extra entries based on Score or Spread
Stop Loss
Take Profit
RSI Filter
RSI Pivot Mode
Built-in Backtester Strategy
Lower Timeframe Backtester Strategy
Live trade panel for current position
Equity curve chart
21 performance metrics in the backtester
2 alert types
*And many more fine-tuning options for pair trading
🔗 SCORE
Score is the core deviation metric between the two assets in the pair.
For example, if you are trading ETHUSDT/BTCUSDT, the indicator analyzes the relationship ETH/BTC, and when one leg temporarily diverges from the other, this difference is reflected in the Score value.
In other words, Score shows how much the current spread between the two instruments deviates from its typical state and is used as the main signal source for pair entries and exits.
In the screenshot above you can see how Score looks in our indicator.
Depending on how large the difference is between the two assets, the Score value can move in a range from −N to +N
When Score is in the −N zone, this is a 🟢 long zone for the first asset and a short zone for the second.
Using the ETH/BTC example: when Score is deeply negative, you open a long on ETH and a short on BTC at the same time, then close both legs when Score returns back to the 0 zone (balance between the two assets).
When Score is in the +N zone, this is a 🔴 short zone for the first asset and a long zone for the second.
In the same ETH/BTC example: when Score is strongly positive, you short ETH and long BTC, and again close both positions when Score comes back to the neutral 0 zone.
☯️ Z/S SCORE
Inside the indicator we added two different formulas for calculating the spread between the two legs of the pair: Z-Score and S-Score.
These approaches measure deviation in different ways and can produce slightly different signals depending on the chosen pair and its behavior.
This allows you to switch between Z-Score and S-Score and choose the method that gives more stable and cleaner signals for your specific instruments.
As you can see in the screenshot above, we used the same pair but applied different Score types to measure the spread and deviation from the norm.
🟣 Z-Score – generated 9 entry signals .
It reacts to price fluctuations more smoothly and usually stays within a range of approximately −8 to +8 .
🟠 S-Score – generated 5 entry signals .
It reacts to price changes more aggressively and produces wider deviations, often reaching −15 to +15 .
This gives traders the choice between a more sensitive but smoother model (Z-Score) and a more selective, stronger-deviation model (S-Score)
⁉️ HOW DOES THE STRATEGY WORK
Here is a basic example of how you can trade this pair trading strategy using our indicator and its signals.
In the classic approach the trade consists of one initial entry and several scale-ins (averaging) if the spread continues to move against the position.
The first entry is opened when Score reaches a standard deviation of −2 or +2.
If price does not revert to the mean and moves further against the position so that Score expands to −3 or +3, the strategy performs the first scale-in.
If Score extends to −4 or +4, a second scale-in is added.
If the spread grows even more and Score reaches −5 or +5, a third scale-in is executed.
In our indicator the number of averaging steps can be up to 4 scale-ins .
After that the position waits until Score returns back to the 0 level , where the whole pair position is closed.
This is the standard model of classical pair trading.
However there are many variations:
using Stop Loss and Take Profit,
exiting earlier or later than the 0 zone,
scaling in not by Score but by Spread, since Score is not linear while Spread is linear,
entering when RSI on both tickers shows opposite extremes, for example RSI 20 on one asset and RSI 80 on the other, and so on.
The number of possible trading styles for this strategy is very large.
We designed the indicator to cover as many of these variations as possible and added flexible tools so you can build your own pair trading logic on top of it.
Below is an example of a classic pair trade with two entries: one main entry and one extra entry (scale-in) .
The pair SUIUSDT / PENGUUSDT shows a high correlation, and on one of the trades the sequence looked like this:
A −2 Score deviation occurred into the long zone and triggered the Main Entry .
🔹 Main Entry
Long SUIUSDT – Margin: 5,000 USD, Entry price: 1.5708
Short PENGUUSDT – Margin: 5,000 USD, Entry price: 0.011793
Price then moved further against the position, Score went deeper into deviation, and the strategy added one extra entry.
🔸 Extra Entry
Long SUIUSDT – Margin: 5,000 USD, Entry price: 1.5938
Short PENGUUSDT – Margin: 5,000 USD, Entry price: 0.012173
The trade was closed when Score reverted back toward the 0 zone (mean reversion of the spread):
❎ Exit
SUIUSDT P&L: −403.34 USD, Exit price: 1.5184
PENGUUSDT P&L: +743.73 USD, Exit price: 0.011089
✅ Total P&L: +340.39 USD
With a total margin of 10,000 USD used per side (20,000 USD combined), this trade yielded around +1.7% on the deployed margin.
On different assets the size and speed of the spread movement will vary, but the principle remains the same.
This is just one example to illustrate how the strategy works in practice using simplified theoretical balances.
⚙️ MAIN SETTINGS
After explaining how the strategy works, we can move to the indicator settings and their logic.
The first block is Main Settings, which controls how the pair is built, how the spread is calculated, and how the backtest is performed.
The core idea of the indicator is to backtest historical data, generate entry signals, show open-position parameters, and provide all necessary metrics for both discretionary and algorithmic trading.
This is a complete framework for analyzing a pair of assets and building a trading system around them. Below I will go through the main parameters one by one.
🔹 Exclude Dates
Allows you to exclude abnormal periods in the pair’s history to remove outlier trades from the backtest.
This is useful when the market experienced extreme news events, listing spikes, or other non-typical situations that distort statistics.
🔹 Pair
Here you select the second asset for your pair.
For example, if your main chart is BTCUSDT, in this field you choose a correlated asset such as ETHUSDT, and the working pair becomes BTCUSDT / ETHUSDT.
The indicator then calculates spread, Score, and all related metrics based on this asset combination.
🔹 Lower Timeframe
This is a special mode for backtesting on a lower timeframe while using a higher timeframe chart to extend the history limit.
For example, if your TradingView plan provides only 5,000 bars of history on the current timeframe, you can switch your chart to a higher timeframe and select a lower timeframe in this setting.
The indicator will then reconstruct the pair logic using up to 99,000 bars of lower timeframe data for backtesting.
This allows you to test the pair on a much longer historical period and find more stable combinations of assets.
🔹 Method
Here you choose which deviation model you want to use: Z-Score or S-Score.
Both methods calculate spread deviation but use different formulas, which can give different signal behavior depending on the pair.
Examples of these two methods are shown earlier in this description.
🔹 Period
This parameter defines how many bars are used to calculate the average deviation for the pair.
If you set Period = 300, the indicator looks back 300 bars and calculates the typical spread deviation over that window.
For example, if the average deviation over 300 bars is around 1%, then a move to 2% or more will push Z/S Score closer to its boundary levels, since such a deviation is considered abnormal for that lookback period.
A larger Period means that only bigger deviations will be treated as anomalies.
A smaller Period makes the model more sensitive and treats smaller deviations as anomalies.
This allows you to tune how aggressive or conservative your pair trading signals should be.
🔹 Invert
This setting is used for negatively correlated pairs.
Some instruments have a positive correlation in the range from +0.8 to +1.0 (strong positive correlation), while others show a negative correlation from −0.8 to −1.0, meaning they usually move in opposite directions.
A classic example is the pair EURUSD and DXY.
As shown in the screenshot above, these instruments often have strong negative correlation due to macro factors and typically move in opposite directions: when EURUSD is rising, DXY is falling, and vice versa.
Such pairs can also be traded with our indicator.
To do this, we use the Invert option, which effectively flips one of the assets (as shown in the screenshot below). After inversion, both instruments are brought to a “same-direction” behavior from the model’s point of view.
From there, you trade the pair in the same way as a positively correlated one:
you open both legs in the same direction (both long or both short) depending on the spread and Score, and then wait for the spread between the inverted pair to converge back toward its mean.
🔀 HEDGE COEFFICIENT
The next block of settings is related to the hedge coefficient.
This defines how much margin is allocated to each leg of the pair.
The classic approach in pair trading is to split the position equally between both assets.
For example, if you allocate 100 USD to a trade , the standard model would open 50 USD long on one asset and 50 USD short on the other.
This works well for pairs with similar volatility , such as BTCUSDT / ETHUSDT
However, if you use a pair like BTCUSDT / DOGEUSDT , the volatility of these assets is very different.
They can still be correlated, but their amplitude is not the same. While Bitcoin might move 2% , Dogecoin can move 10% over the same period.
Because of that, for pairs with strongly different volatility, we can use a hedge coefficient and, for example, enter with 30 USD on one leg and 70 USD on the other, taking the volatility difference into account.
This is the main idea behind the Hedge Coefficient section and its primary use.
The indicator includes 6 methods of calculating the coefficient:
Cumulative RMA
Beta OLS
Beta TLS
Beta EMA
RMA Range
RMA Delta
Each method uses a different formula to compute the hedge coefficient and to size the position based on different metrics of the assets.
We leave it to the trader to decide which algorithm works best for their specific pair and style.
Below are the settings inside this section:
🔹 Method
When Auto Hedge is enabled, you can select which method to use from the list above.
The chosen method will automatically calculate the hedge coefficient between the two legs.
🔹 Hedge Coefficient
This is the manual hedge ratio per trade when Auto Hedge is disabled.
By default it is set to 1, which means the position is opened 50/50 between the two assets.
🔹 Min Allowed Hedge Coef.
This is the minimum allowed hedge coefficient.
By default it is 0.2, which means the model will not go below a 20% / 80% split between the legs.
🔹 MA Length
For methods that use moving averages (for example Beta EMA), this parameter sets the period used to calculate the hedge coefficient.
🛠️ STRATEGY SETTINGS
The next important block is Strategy Settings .
Here you define the core parameters used for backtesting: trading commission, position size, entry / exit logic, Stop Loss, Take Profit, and other rules that describe how you want the strategy to operate.
Below are all parameters with a detailed explanation.
🔸 Commission %
In this field you set your broker’s fee percentage per trade .
The indicator automatically calculates the correct commission for each leg of every trade. You only need to input the real commission rate that your broker charges for volume. No additional manual calculations are required.
🔸 Main Entry Mode
There are two options for the main entry:
Score - This is the primary entry method based on Z/S Score.
When Score reaches the deviation level defined in the settings below, the strategy opens the first position.
For example, if you set “Entry at 2 deviations”, the trade will be opened when Score hits ±2.
RSI Only - Alternative entry method based on RSI divergence between the two assets.
The exact RSI levels are defined in the RSI settings section below.
For example, if you set the entry threshold at 30, then when one asset has RSI below 30 and the second one has RSI above 70, the first entry will be triggered.
🔸 Extra Entries Mode
This defines how scale-ins (averaging) are executed. There are two modes:
Score - Works the same way as the main entry, but for additional entries.
For example, the main entry can be at 2 deviations, the first scale-in at 3, the second at 4, etc.
Spread - This mode uses the Spread (difference between the two assets) starting from the main entry moment.
As the spread continues to widen, the strategy can add extra entries based on spread growth rather than Score.
Since Score is a non-linear metric and Spread is linear, in some configurations averaging by Spread can produce better results than averaging by Score. This is pair- and strategy-dependent. 🔸 Entry parameters
Deviation / Spread threshold
Entry size
Main Entry – first field (deviation / spread), second field (position size)
Entry 2 – first field (deviation / spread), second field (position size)
Entry 3 – first field (deviation / spread), second field (position size)
Entry 4 – first field (deviation / spread), second field (position size)
This allows you to define up to four scaling steps with different triggers and different sizing.
🔸 Exit Level
This parameter defines at what Score level you want to exit the trade.
By default it is 0, which means the backtester closes the position when Score returns to the neutral (0) zone.
You can also use positive or negative values. Example:
Assume your main entry is configured at a 3 deviation.
You can exit at the 0 level, or you can set Exit Level = 2.
If your initial entry was at −3, the position will be closed when Score reaches +2.
If your initial entry was at +3, the position will be closed when Score reaches −2.
This approach can increase the profit per trade due to a larger captured spread, but it may also increase the holding time of the position.
🔸 Stop Loss
Here you define the maximum loss per trade in PnL units.
If a trade reaches the negative PnL value specified in this field and the Stop Loss option is enabled, the indicator will close the trade at a loss.
The Cooldown parameter sets a pause after a losing trade:
the strategy will wait a specified number of bars before opening the next trade.
🔸 Take Profit
Works similar to Stop Loss but for profit targets.
You set the desired PnL value you want to reach.
The trade will be closed when either the Take Profit target is hit or when Score reaches the exit level defined in the settings, whichever occurs first (depending on your configuration).
🔸 Show Qty in currency
When enabled, trade size is displayed in currency (USD) instead of token quantity.
This is useful for quickly understanding position size in monetary terms.
You will see this in the Current Trade panel, which is described later.
🔸 Size Rounding
Controls how many decimal places are used when rounding position size (from 0 to 10 digits after the decimal).
This is also used for the Current Trade panel so you can adjust how detailed or compact the size display should be.
📊 RSI FILTERS
This section is used for additional trade filtering.
RSI can be used in two ways:
as a primary entry signal,
or as an extra filter for entries based on Z/S Score.
If in the Strategy Settings the Main Entry Mode is set to RSI, then RSI becomes the main trigger for opening a position.
In this case a trade is opened when the RSI of the two assets reaches opposite zones.
Example:
If the threshold is set to 30, then:
when one asset has RSI below 30, and
the second asset has RSI above 70 (100 − 30),
the strategy opens the first entry.
All extra entries after that will be executed either by Spread or by Z/S Score, depending on your Extra Entries Mode.
Below are the parameters in this block:
RSI Length – standard RSI period setting.
RSI Pivot Mode – when enabled, RSI is used as an additional filter together with Z/S Score. The indicator looks for a reversal pattern on RSI (pivot behavior). If RSI forms a reversal structure, the trade is allowed to open. If not, the signal is skipped until a proper RSI pivot is formed.
Entry RSI Filter – here you define the RSI thresholds used for RSI-based entries. These are the same boundary levels described in the example above.
Overall, this section helps filter out lower-quality trades using additional RSI conditions or lets you build RSI-only entry logic based on extreme levels.
🎨 MAIN CHART STYLING
This section controls the visual appearance of trades on the main chart.
You can customize how the second asset line is drawn, as well as the icons for entries, scale-ins, and exits, including their size and style.
▫️ Price Line
This is the line that shows the price of the second asset and the relative difference between the two instruments.
You can adjust the line thickness and color to make it more readable on your chart.
▫️ Adjust Price Line by Hedge Coefficient
When this option is enabled, the second asset’s line is normalized by the hedge coefficient.
If you turn it off, the hedge coefficient will not be applied to the second asset’s line, and it will be displayed in raw form.
▫️ Entry Label
Here you can customize how the entry markers look:
choose the color, icon style, and size of the label that marks each trade entry and scale-in on the chart.
▫️ Exit Label
Similarly, you can define the color, icon style, and size of the label used for exits.
This helps visually separate entries and exits and makes it easier to read the trade history directly from the chart.
🎯 INDICATOR PANEL
This section controls the settings of the indicator panel, which works like an oscillator and allows you to visualize multiple metrics in one place.
You can flexibly enable, style, and scale each parameter.
🔹 Score
Displays the main deviation metric between the two assets.
You can customize the color and line thickness of the Score plot.
🔹 Spread
Shows the spread between the two assets.
It starts calculating from the moment the trade is opened.
You can adjust its color and thickness for better visibility.
🔹 Total Profit
Displays the cumulative profit for this pair and strategy as a line that grows (or falls) over time.
Color, opacity, and line thickness can be customized.
🔹 Unrealized PNL
Once a trade is opened, this line shows the current PnL of the active position.
It also lets you see historical drawdowns on the pair.
Color and thickness can be adjusted.
🔹 Released PNL
Shows the realized PnL of each closed trade as bars.
Useful for quickly evaluating the result of every individual trade in the backtest.
🔹 Correlation
Plots the correlation coefficient between the two assets as a graph, so you can visually track how stable or unstable the relationship between them is over time.
🔹 Hedge Coefficient
Shows the hedge coefficient as a line, which helps understand how the model is rebalancing exposure between the two legs depending on their behavior.
For each metric there is also a 📎 Stretch option.
Stretch allows you to compress or expand the scale of a specific line to visually align metrics with different ranges on the same panel and make the chart easier to read.
📈 PROFIT CHART
Since TradingView does not natively support proper backtesting for pair trading, this indicator includes its own profit curve for the pair.
You can visually see how the strategy performed over historical data: whether there were deep drawdowns, abnormal profit spikes, or stable equity growth over time. This makes it much easier to evaluate the quality of the pair and the strategy on history.
In the settings of this section you can flexibly customize how the profit chart is displayed:
labels, position of the panel, padding, and other visual details.
Everything depends on your personal preferences, so we give full control over styling:
you can adjust the look of the profit chart to match your layout or completely hide it from the chart if you do not need it.
📌 CURRENT TRADE
This section controls the current trade table.
When there is an active trade on the chart, the panel displays all key information for the open position:
direction for each ticker (long or short),
required position size for each leg,
entry price for both assets,
and real-time PnL for each leg separately,
so you always have a clear view of the current situation.
The main thing you can do with this table is customize its appearance:
you can change the size, position on the chart, background and text colors, as well as separate coloring for positive / negative PnL and different colors for long and short positions.
📅 BACKTEST RESULTS
The next key block is Backtest Results.
This results table with detailed metrics gives you an extended view of how the pair and strategy perform: win rate, profit factor, long/short breakdown, and more than 20 additional stats that help you evaluate the potential of your setup.
⚠️ First of all, it is important to note ⚠️
past performance does not guarantee future results.
Every trader must keep this in mind and factor these risks into their strategy.
The table shows metrics in three cuts:
All Entries
Main Entries
Extra Entries (scale-ins)
Core metrics:
Profit – total profit for each entry type.
Winrate – win rate for this pair.
Profit Factor – ratio of gross profit to gross loss for the strategy.
Trades – number of trades in the backtest.
Wins – number of winning trades.
Losses – number of losing trades.
Long Profit – profit generated by long positions.
Short Profit – profit generated by short positions.
Longs – total number of long trades.
Shorts – total number of short trades.
Avg. Time – average time spent in a trade.
Additional metrics for a deeper evaluation of the pair:
Correlation – current correlation between the two assets in the pair.
Bars Processed – number of bars used in the analysis.
Max Drawdown – maximum historical drawdown of the strategy.
Biggest Loss – the largest single losing trade in the backtest.
Recommended Hedge – recommended hedge coefficient based on historical behavior.
Max Spread – maximum positive spread observed in history.
Min Spread – maximum negative spread observed in history.
Avg. Max Spread – average of positive extreme spread values (above 0).
Avg. Min Spread – average of negative extreme spread values (below 0).
Avg Positive Spread – average positive spread across all trades (only values above 0).
Avg Negative Spread – average negative spread across all trades (only values below 0).
Current Spread – current spread between the assets when a trade is open.
These metrics together allow you to quickly assess how stable the pair is, how the risk/return profile looks, and whether the strategy parameters are suitable for live trading. You can fully customize this results table to fit your workflow:
hide metrics you don’t need, change colors, opacity, and other visual styles, and reorder the focus of the stats according to your trading style.
This way the backtest block can show only the metrics that matter to you most and remain clean and readable during analysis.
📣 ALERTS
The next section is dedicated to alerts.
Here you can configure all signals you need, both for manual trading and for full automation of this pair trading strategy. This block is designed to cover most practical use cases. The indicator supports two alert modes:
Single Alert – one universal custom alert for all events.
Two Alerts – separate alerts for each ticker so you can receive different messages per asset.
Available alert events:
Main Entry – when the main entry is triggered.
Entry 2 – when the first scale-in is executed.
Entry 3 – when the second scale-in is executed.
Entry 4 – when the third scale-in is executed.
Exit Alert – when the position is closed.
StopLoss Alert – when Stop Loss is hit.
TakeProfit Alert – when Take Profit is hit.
All alerts are fully customizable and support a set of placeholders for building structured messages or JSON payloads.
🔹1 Alert Type
List of supported placeholders: {{event}} – trigger name ('Entry 1', 'Exit').
{{dir_1}} – 'Long' or 'Short' for the main ticker.
{{dir_2}} – 'Long' or 'Short' for the other ticker.
{{action_1}} – 'Buy', 'Sell' or 'Close' for the main ticker.
{{action_2}} – 'Buy', 'Sell' or 'Close' for the other ticker.
{{price_1}} – price for the main ticker.
{{price_2}} – price for the other ticker.
{{qty_1}} – order size for the main ticker.
{{qty_2}} – order size for the other ticker.
{{ticker_1}} – main ticker (e.g. 'BTCUSD').
{{ticker_2}} – other ticker (e.g. 'ETHUSD').
{{time}} – candle open time in UTC.
{{timenow}} – signal time in UTC.
🔹2 Alert Type
List of supported placeholders: {{event}} – trigger name ('Entry 1', 'Exit', 'SL', 'TP').
{{action}} – 'Buy', 'Sell' or 'Close'.
{{price}} – order price.
{{qty}} – order size.
{{ticker}} – ticker (e.g. 'BTCUSD').
{{time}} – candle open time in UTC.
{{timenow}} – signal time in UTC. You can use these placeholders to build any JSON structure or custom alert text required by your trading bot, exchange API, or automation service.
In this post I’ve explained how the indicator works, the core concept behind this pair trading strategy, and shown practical examples of trades together with a detailed breakdown of each unique feature inside the tool.
We have invested a lot of work into building this indicator and we truly hope it will help you trade pair strategies more efficiently and more profitably by giving you structured, strategy-specific information that is difficult to obtain in any other way.
⚠️ Please also remember that past performance does not guarantee future results.
Always evaluate the risks, the robustness of your setup, and your own risk tolerance before entering any position, and make independent, well-considered decisions when using this or any other strategy.
MirrorPip RSI Funding strategyThis strategy aims at exploiting funding arbitrage between two coins that mimic each other price movement but the funding in them is in opposite direction.
Example ETH funding is negative and ETC funding is positive, this strategy will strategically buy ETC and Short ETH when there is a RSI divergence across these 2 coins and smartly exit them when cumulative P/L turns out positive.
The notional value on both coins has to be kept same.
This is a funding pair strategy and can be fully automated with 5 crypto exchanges.
The ChecklistThis trading checklist will grade how well your trade setup is based on how many confluences are lined up.
Yield Curve Inversion Indicator Will track the TVC:US10Y and TVC:US03MY spread, often followed for the "yield curve inversion" trade/indicator.
When an inversion occurs, which lasts a minimum of the defined days (default 10) the indicator will paint forward a warning period (default is 365 days).
The yield curve being inverted is not the signal, the REVERSION back to a positive curve is the associated signal, namely the following 12 months after a reversion. This is often used as an early warning of trouble in markets.
Hope this helpful for those who follow macro/internal warning signals.
RS High Beta Exposure | QuantLapseRS High Beta Exposure | QuantLapse
Conceptual Foundation and Innovation
The RS High Beta Exposure indicator from QuantLapse is a comprehensive multi-asset allocation and momentum-ranking system that integrates beta and trend analysis, pairwise relative strength comparison, and volatility-adjusted filtering.
Its objective is to identify dominant crypto assets while dynamically reallocating High Beta exposure based on a calculated relative strength. The objective is to integrate trend analysis along with volatility filtering to these pairs to determine its relative strength.
At its core, RS High Beta Exposure indicator measures the systematic (β) performance of each asset relative to other assets provided combining these measures with inter-asset ratio trends to determine which assets exhibit superior strength and momentum relative to the other assets.
This integration of relative strength comparison, and trend and filtering analysis represents a quantitative evolution of traditional relative strength analysis, designed for adaptive asset rotation across major cryptocurrencies.
Technical Composition and Calculation
The indicator is structured around three major analytical layers:
1. Beta and Alpha Analysis
-Each asset’s return is decomposed into systematic components relative to the other assets by using a trend based, volatility filtering model.
-Assets with the highest point on a relative strength basis above the median are considered outperformers and eligible for allocation.
2. Pairwise Ratio Momentum
-Every asset is compared against all others through a ratio-trend, where momentum based trend scores quantify the directional momentum between each pair.
-In addition, we filter any false signals with volatility adjusted trends in which ensure high quality signals.
3. High Confidence Ranking
-Using the Pairwise Momentum signals, the RS High Beta Exposure scores them. If the asset comparison is given a signal, the RS High Beta Exposure scores points for each asset.
-If the total points of an asset is 5, its given the rank the dominant asset and is most likely to outperform.
By combining these layers, RS High Beta Exposure determines not only which assets is the strongest but also which assets to be invested.
User Inputs and Feature Adaptability
The indicator includes set of customizable parameters to support portfolio and risk management preferences:
Start Date Filter – Defines the beginning of live strategy evaluation.
Display Options – Able to change the location of the RS Table, Background and equity color.
Asset Selection – Modify or replace up to six crypto assets in the ranking matrix
asset1 = input.symbol("CRYPTO:XRPUSD", title ="Asset 1")
asset2 = input.symbol("CRYPTO:BNBUSD", title ="Asset 2")
asset3 = input.symbol("CRYPTO:ADAUSD", title ="Asset 3")
asset4 = input.symbol("CRYPTO:DOGEUSD", title ="Asset 4")
asset5 = input.symbol("CRYPTO:XLMUSD", title ="Asset 5")
asset6 = input.symbol("CRYPTO:LINKUSD", title ="Asset 6")
Each module operates cohesively to maintain analytical transparency while allowing user-level control over system sensitivity and behavior.
Real World, Practical Applications
The RS High Beta Exposure indicator is designed for systematic traders and quantitative portfolio managers who seek a disciplined framework for dynamic crypto asset rotation.
Key applications include:
High-Beta Asset Identification: Systematically identify crypto assets exhibiting relative dominance and stronger momentum characteristics versus peers within the comparison set.
Rule-Based Portfolio Rotation: Reallocate exposure toward leading assets using objective pairwise signals, reducing emotional decision-making and FOMO-driven trades.
Trend-Aligned Risk Participation: Employ the pairwise relative strength model to maintain exposure only during favorable momentum conditions, helping avoid prolonged participation in weak or deteriorating trends.
By combining relative strength comparisons with trend-aware filtering, this framework bridges quantitative finance and market regime analysis, providing a structured, data-driven approach to crypto asset allocation.
Advantages and Strategic Value
RS High Beta Exposure goes beyond conventional relative strength tools by integrating multi-asset comparison, ratio-based dominance scoring, and volatility-aware regime filtering into a single coherent framework.
By employing a three-layer confluence model — combining trend integrity, relative performance attribution, and volatility-state confirmation — the system improves the reliability of rotation and trend-following decisions.
The model is particularly valuable for traders seeking to:
Mitigate drawdowns while participating in higher-beta assets through regime-aware exposure control.
Identify persistent outperformers early in emerging market trends.
Maintain capital exposure only when statistical and momentum conditions signal elevated confidence.
The inclusion of visual allocation tables and a dynamic alert system makes RS High Beta Exposure both transparent and actionable, supporting discretionary analysis as well as systematic or automated trading workflows.
Alerts and Visualization
The script delivers clear, intuitive visual cues and alert-based feedback to support real-time decision-making:
Color-coded background states visually indicate the current allocation regime.
Allocation labels and summary tables display the dominant asset and its relative strength in real time.
An integrated alert system automatically notifies users whenever allocation states change (e.g., “100% XRP” or “100% CASH”).
Together, these visualization and alert features make RS High Beta Exposure both analytically rigorous and easy to interpret, even in fast-moving live market conditions.
Summary and Usage Tips
RS High Beta Exposure is an advanced interpretation of relative strength analysis, blending pairwise momentum comparisons, multi-asset dominance scoring, and adaptive volatility filters into a disciplined framework for crypto asset rotation.
By combining cross-asset selection with systematic allocation logic, the indicator helps traders determine when to be exposed, which asset demonstrates leadership, and when to step aside during unfavorable conditions. The model is best applied on the 1D timeframe, where its structure is optimized for identifying sustained leadership rather than short-term price noise. For broader context and confirmation, it can be used alongside other QuantLapse systematic models at the portfolio level.
Note: Past performance does not guarantee future results. This indicator is intended for research and educational use within TradingView.
Futures Sizing Calculator (NQ,MGC,MES)Clean simple, risk indicator that will allow you to see risk before entering trade. This will allow you to use it on MES, MGC and MNQ.
For any ideas or improvements, don't hesitate to contact me.
CoreHedge : Pivots(Main) + Manual RR Monitor
You can fInd Mainly Target Point of Support and Resistance
1. Finding Tipping Point
2. Strategy Build
3. RR Caculator
Momentum Table View (Bar-Based)// NOTE:
// This script uses bar-based lookbacks instead of calendar months.
// Approximate conversions for daily charts:
// - 21 bars ≈ 1 month
// - 63 bars ≈ 3 months
// - 252 bars ≈ 1 year
// For other timeframes, adjust accordingly for different time periods and needs.
// For hourly I have it set at 24*5, 24*5*4 and then finally 24*5*4 to give the same,
// daily, weekly and monthly aggregate returns but on the hourly scale.
// Of course you can split it anyway you like as well depends on the expected needs you have.
Running idea so there will likely be revisions to the z scoring to possibly a different method and the atan angle represented in the code will also likely be changed at some point as to maybe a regression method. These changes will take time as this is only a secondary platform for me not the main source of data. In saying that the table has the data representing the log returns of an asset of n bars which I decided on over the original more accurate daily, weekly and monthly close points which the user can always specify using this method if wanting to be more accurate with the standard method of momentum returns factor.
Student Wyckoff Relative StrengthSTUDENT WYCKOFF Relative Strength compares one instrument against another and plots their relative performance as a single line.
Instead of asking “is this chart going up or down?”, the script answers a more practical question: “is THIS asset doing better or worse than my benchmark?”
━━━━━━━━━━
1. Concept
━━━━━━━━━━
The indicator builds a classic relative strength (RS) line:
• Main symbol = the chart you attach the script to.
• Benchmark symbol = any symbol you choose in the settings (index, ETF, sector, another coin, etc.).
RS is calculated as:
RS = Price(main symbol) / Price(benchmark)
If RS is rising, your symbol outperforms the benchmark.
If RS is falling, your symbol underperforms the benchmark.
You can optionally normalize RS from the first bar (start at 1 or 100) to clearly see how many times the asset has outperformed or lagged behind over the visible history.
This is not a “buy/sell” indicator. It is a **context tool** for rotation, selection and Wyckoff-style comparative analysis.
━━━━━━━━━━
2. How the RS line is built
━━━━━━━━━━
Inputs:
• Source of main symbol – default is close, but you can choose any OHLC/HL2/typical price etc.
• Benchmark symbol – ticker used as reference (index, sector, futures, Bitcoin, stablecoin pair, etc.).
• Benchmark timeframe – by default the current chart timeframe is used, or you can force a different TF.
The script uses `request.security()` with `lookahead_off` and `gaps_off` to pull benchmark prices **without look-ahead**.
A small epsilon is used internally to avoid division by zero when the benchmark price is very close to 0.
Normalization options:
• Normalize RS from first bar – if enabled, the very first valid RS value becomes “1” (or 100), and all further values are expressed relative to this starting point.
• Multiply RS by 100 – purely cosmetic; makes it easier to read RS as a “percentage-like” scale.
━━━━━━━━━━
3. Smoothing and color logic
━━━━━━━━━━
To help read the trend of relative strength, the script calculates a simple moving average of the RS line:
• RS MA length – period of smoothing over the RS values.
• Show RS moving average – toggle to display or hide this line.
Color logic:
• When RS is above its own MA → the line is drawn with the “stronger” color.
• When RS is below its MA → the line uses the “weaker” color.
• When RS is close to its MA → neutral color.
Optional background shading:
• When RS > RS MA → background can be tinted softly green (phase of relative strength).
• When RS < RS MA → background can be tinted softly red (phase of relative weakness).
This makes it easy to read the **trend of strength** at a glance, without measuring every small swing.
━━━━━━━━━━
4. How to interpret it
━━━━━━━━━━
Basic reading rules:
• Rising RS line
– The main symbol is outperforming the benchmark.
– In Wyckoff terms, this can indicate a leader within its group, or a sign of accumulation relative to the market.
• Falling RS line
– The main symbol is underperforming the benchmark.
– Can point to laggards, distribution, or simply an asset that is “dead money” compared to alternatives.
• Flat or choppy RS line
– No clear edge versus the benchmark; performance is similar or rotating back and forth.
With normalization on:
• RS > 1 (or > 100) – the asset has grown more than the benchmark since the starting point.
• RS < 1 (or < 100) – it has grown less (or fallen more) than the benchmark over the same period.
The RS moving average and colored background highlight whether this outperformance/underperformance is a **temporary fluctuation** or a more sustained phase.
━━━━━━━━━━
5. Practical uses
━━━━━━━━━━
This indicator is useful for:
• **Selecting stronger assets inside a group**
– Compare individual stocks vs an index, sector, or industry ETF.
– Compare altcoins vs BTC, ETH, or a crypto index.
– Prefer charts where RS is in a sustained uptrend rather than just price going “up on its own”.
• **Monitoring sector and rotation flows**
– Attach the script to sector ETFs or major coins and switch the benchmark to a broad market index.
– See where capital is rotating: which areas are gaining or losing strength over time.
• **Supporting Wyckoff-style analysis**
– Use RS together with volume, structure, phases and trading ranges.
– A breakout or SOS with rising RS vs the market tells a different story than the same pattern with falling RS.
• **Portfolio review and risk decisions**
– When an asset shows a long period of relative weakness, it may be a candidate to reduce or replace.
– When RS turns up from a long weak phase, it can signal the start of potential leadership (not an entry by itself, but a reason to study the chart deeper).
━━━━━━━━━━
6. Notes and disclaimer
━━━━━━━━━━
• Works on any symbol and timeframe available on TradingView.
• The last bar can change in real time as new prices arrive; this is normal behaviour for all indicators that depend on current close.
• There are no built-in alerts or trading signals – this tool is meant to support your own analysis and trading plan.
This script is published for educational and analytical purposes only.
It does not constitute financial or investment advice and does not guarantee any performance. Always test your ideas, understand the logic of your tools and use proper risk management.
X-Trend Macro Command CenterX-Trend Macro Command Center (MCC) | Institutional Grade Dashboard
📝 Description Body
The Invisible Engine of the Market Revealed.
Traders often focus solely on Price Action, ignoring the massive underwater currents that actually drive trends: Global Liquidity, Inflation, and Central Bank Policy. We created X-Trend Macro Command Center (MCC) to solve this problem.
This is not just an indicator. It is a fundamental heads-up display that bridges the gap between technical charts and macroeconomic reality.
💡 The Idea & Philosophy
Markets don't move in a vacuum. Bull runs are fueled by M2 Money Supply expansion and negative real yields. Crashes are triggered by liquidity crunches and aggressive rate hikes. X-Trend MCC was built to give retail traders the same "Macro Awareness" that institutional desks possess. It aggregates fragmented economic data from Federal Reserve databases (FRED) directly onto your chart in real-time.
🚀 Application & Logic
This tool is designed for Trend Traders, Crypto Investors, and Macro Analysts.
Identify the Regime: Instantly see if the environment is "RISK ON" (High Liquidity, Low Real Rates) or "RISK OFF" (Monetary Tightening).
Validate the Trend: Don't buy the dip if Liquidity (M2) is crashing. Don't short the rally if Real Yields are negative.
Multi-Region Analysis: Switch instantly between economic powerhouses (US, China, Japan) to see where the capital is flowing.
📊 Dashboard Metrics Explained
Every row in the Command Center tells a specific story about the economy:
Interest Rate: The "Gravity" of finance. Higher rates weigh down risk assets (Stocks/Crypto).
Inflation (YoY): The erosion of purchasing power. We calculate this dynamically based on CPI data.
Real Yield (The "Golden" Metric): Calculated as Interest Rate - Inflation.
Green: Real Yield is low/negative. Cash is trash, assets fly.
Red: Real Yield is high. Cash is King, assets struggle.
US Debt & GDP: Fiscal health indicators formatted in Trillions ($T). Watch the Debt-to-GDP ratio—if it spikes >120%, expect currency debasement.
M2 Money Supply: The fuel tank of the market. Tracks the total amount of money in circulation.
↗ Trend: Liquidity is entering the system (Bullish).
↘ Trend: Liquidity is drying up (Bearish).
🧩 The X-Trend Ecosystem
X-Trend MCC is just the tip of the iceberg. This module is part of the larger X-Trend Project — a comprehensive suite of algorithmic tools being developed to quantify market chaos. While our Price Action algorithms (Lite/Pro/Ultra) handle the Micro, the MCC handles the Macro.
Technical Note:
Data Sources: Direct connection to FRED (Federal Reserve Economic Data).
Zero Repainting: Historical data is requested strictly using closed bars to ensure accuracy.
Open Source: We believe in transparency. The code is open for study under MPL 2.0.
Build by Dev0880 | X-Trend © 2025
Alpha Net Stop Loss & Take Profit % 🔒 Invite-only Script: Alpha Net SL/TP %
An automated system that plots fixed-percentage Stop Loss and Take Profit zones using EMA 5/32 cross signals. It captures entries, plots TP/SL zones with colored fills, and tracks trade state.
📌 Features:
- EMA 5/32 cross-based entry signals.
- Auto-reset on SL/TP hit.
- Alerts for entry/exit.
- Clean zone visuals.
The code is protected to preserve proprietary logic. Please contact the author to request access.
Trade Assistant by thedatalayers.comThe Trade Assistant by DataLayers.com is designed to bridge the gap between futures-based trade ideas and their precise execution on CFD instruments.
Many traders identify high-quality setups on futures markets but execute their trades on CFDs due to broker access, margin efficiency, or position sizing flexibility.
This tool ensures that the price levels, risk parameters, and position sizing from the futures contract are translated accurately to the selected CFD.
The indicator supports inverted instruments and differing quote conventions.
For example, it can accurately convert trades from a futures contract such as USD/CAD Future to an inverted CFD like CAD/USD, even when price scales and quotation formats differ.
Users can define custom scaling factors to ensure correct price mapping across instruments with different decimal structures or broker-specific pricing models.
Index Construction Tool🙏🏻 The most natural mathematical way to construct an index || portfolio, based on contraharmonic mean || contraharmonic weighting. If you currently traded assets do not satisfy you, why not make your own ones?
Contraharmonic mean is literally a weighted mean where each value is weighted by itself.
...
Now let me explain to you why contraharmonic weighting is really so fundamental in two ways: observation how the industry (prolly unknowably) converged to this method, and the real mathematical explanation why things are this way.
How it works in the industry.
In indexes like TVC:SPX or TVC:DJI the individual components (stocks) are weighted by market capitalization. This market cap is made of two components: number of shares outstanding and the actual price of the stock. While the number of shares holds the same over really long periods of time and changes rarely by corporate actions , the prices change all the time, so market cap is in fact almost purely based on prices itself. So when they weight index legs by market cap, it really means they weight it by stock prices. That’s the observation: even tho I never dem saying they do contraharmonic weighting, that’s what happens in reality.
Natural explanation
Now the main part: how the universe works. If you build a logical sequence of how information ‘gradually’ combines, you have this:
Suppose you have the one last datapoint of each of 4 different assets;
The next logical step is to combine these datapoints somehow in pairs. Pairs are created only as ratios , this reveals relationships between components, this is the only step where these fundamental operations are meaningful, they lose meaning with 3+ components. This way we will have 16 pairs: 4 of them would be 1s, 6 real ratios, and 6 more inverted ratios of these;
Then the next logical step is to combine all the pairs (not the initial single assets) all together. Naturally this is done via matrices, by constructing a 4x4 design matrix where each cell will be one of these 16 pairs. That matrix will have ones in the main diagonal (because these would be smth like ES/ES, NQ/NQ etc). Other cells will be actual ratios, like ES/NQ, RTY/YM etc;
Then the native way to compress and summarize all this structure is to do eigendecomposition . The only eigenvector that would be meaningful in this case is the principal eigenvector, and its loadings would be what we were hunting for. We can multiply each asset datapoint by corresponding loading, sum them up and have one single index value, what we were aiming for;
Now the main catch: turns out using these principal eigenvector loadings mathematically is Exactly the same as simply calculating contraharmonic weights of those 4 initial assets. We’re done here.
For the sceptics, no other way of constructing the design matrix other than with ratios would result in another type of a defined mean. Filling that design matrix with ratios Is the only way to obtain a meaningful defined mean, that would also work with negative numbers. I’m skipping a couple of details there tbh, but they don’t really matter (we don’t need log-space, and anyways the idea holds even then). But the core idea is this: only contraharmonic mean emerges there, no other mean ever does.
Finally, how to use the thing:
Good news we don't use contraharmonic mean itself because we need an internals of it: actual weights of components that make this contraharmonic mean, (so we can follow it with our position sizes). This actually allows us to also use these weights but not for addition, but for subtraction. So, the script has 2 modes (examples would follow):
Addition: the main one, allows you to make indexes, portfolios, baskets, groups, whatever you call it. The script will simply sum the weighted legs;
Subtraction: allows you to make spreads, residual spreads etc. Important: the script will subtract all the symbols From the first one. So if the first we have 3 symbols: YM, ES, RTY, the script will do YM - ES - RTY, weights would be applied to each.
At the top tight corner of the script you will see a lil table with symbols and corresponding weights you wanna trade: these are ‘already’ adjusted for point value of each leg, you don’t need to do anything, only scale them all together to meet your risk profile.
Symbols have to be added the way the default ones are added, one line : one symbol.
Pls explore the script’s Style setting:
You can pick a visualization method you like ! including overlays on the main chart pane !
Script also outputs inferred volume delta, inferred volume and inferred tick count calculated with the same method. You can use them in further calculations.
...
Examples of how you can use it
^^ Purple dotted line: overlay from ICT script, turned on in Style settings, the contraharmonic mean itself calculated from the same assets that are on the chart: CME_MINI:RTY1! , CME_MINI:ES1! , CME_MINI:NQ1! , CBOT_MINI:YM1!
^^ precious metals residual spread ( COMEX:GC1! COMEX:SI1! NYMEX:PL1! )
^^ CBOT:ZC1! vs CBOT:ZW1! grain spread
^^ BDI (Bid Dope Index), constructed from: NYSE:MO , NYSE:TPB , NYSE:DGX , NASDAQ:JAZZ , NYSE:IIPR , NASDAQ:CRON , OTC:CURLF , OTC:TCNNF
^^ NYMEX:CL1! & ICEEUR:BRN1! basket
^^ resulting index price, inferred volume delta, inferred volume and inferred tick count of CME_MINI:NQ1! vs CME_MINI:ES1! spread
...
Synthetic assets is the whole new Universe you can jump into and never look back, if this is your way
...
∞
Asset Rotation System[Sahebson]Asset Rotation System
Overview
Asset Rotation System is a sophisticated cross-sectional momentum strategy designed to dynamically rotate capital among a customizable selection of assets. The system continuously evaluates the relative strength of multiple assets using proprietary alpha scoring methodology, automatically positioning your portfolio in the strongest-performing asset at any given time.
This indicator provides a complete portfolio management solution for traders seeking to maximize returns through systematic asset rotation while maintaining full transparency with comprehensive performance metrics, trade history, and visual feedback.
Key Features
1. Dynamic Asset Rotation
The system continuously monitors up to 10 customizable assets across any market—stocks, crypto, forex, or commodities. Using cross-sectional analysis, it identifies the asset demonstrating the strongest relative momentum and automatically signals rotation when leadership changes.
Supports any tradable asset available on TradingView
Real-time alpha scoring for each asset
Automatic rotation signals when market leadership shifts
2. Flexible Asset Selection
Each asset slot includes an enable/disable checkbox, allowing traders to:
Quickly toggle assets in and out of the rotation universe
Test different asset combinations without reconfiguring
Adapt to changing market conditions by excluding underperforming sectors
3. Adaptive Rolling Window Strategy
The system offers four pre-configured rolling window strategies that automatically adjust based on your chart timeframe:
Conservative: Strategy Behavior Best For Conservative Very stable, fewer trades Long-term investors seeking minimal turnover
Optimal: Balanced approach Most traders seeking good trend capture with filtered noise
Aggressive: More responsive Active traders wanting to catch trends early
Very Aggressive: Highly responsive Short-term traders comfortable with higher turnover
Manual override option available for advanced users who prefer custom settings.
4. Comprehensive Performance Metrics
Real-time calculation and display of institutional-grade performance ratios:
Sharpe Ratio: Risk-adjusted returns relative to total volatility
Sortino Ratio: Downside risk-adjusted returns (penalizes only negative volatility)
Omega Ratio: Probability-weighted ratio of gains vs. losses
Maximum Drawdown: Largest peak-to-trough decline
Average Holding Period: Mean bars held per position
5. Portfolio vs. Benchmark Comparison
Side-by-side comparison of your rotating portfolio against a customizable benchmark index:
Separate equity curves for visual comparison
Color-coded metrics showing outperformance/underperformance
Real-time tracking of both portfolio and benchmark returns
6. Buy & Hold Comparison Table
Instantly compare your portfolio's performance against buy-and-hold returns for each individual asset:
See which assets would have outperformed the rotation strategy
Validate the effectiveness of dynamic allocation
Identify periods where rotation adds or subtracts value
7. Detailed Trade History
Complete trade log with:
Date and time of each rotation
Sell asset and price
Buy asset and price
P&L % per trade
Holding period (bars) for each position
Configurable display (0-30 trades)
8. Visual Chart Feedback
Rotation Signals: Triangle markers with asset name when rotations occur
Portfolio Label: Current position, equity value, and return percentage
Benchmark Label: Benchmark name, equity value, and return percentage
Top Asset Box: Prominent display of current holding with alpha score
9. Flexible Back testing
Custom start date and time
Optional end date for specific period testing
Configurable starting capital
Adjustable risk-free rate for ratio calculations
Choice of 252 or 365 trading days for annualization
10. Real-Time Alerts
Automatic notifications when rotation occurs:
Alert includes sell asset, sell price, buy asset, and buy price
Compatible with TradingView's alert system
Never miss a rotation signal
************************************************************************
How to Use for Optimal Returns:
Step 1: Select Your Asset Universe
Choose assets that are:
Uncorrelated or negatively correlated: Diversification improves rotation effectiveness
Liquid: Ensures you can execute rotations without slippage
From different sectors/markets: Increases probability of finding strong performers
Step 2: Choose Your Rolling Window Strategy
Conservative, Optimal (default),Aggressive, Very Aggressive
Step 3: Set Your Timeframe
The rolling window automatically adapts to your chart timeframe:
Higher timeframes (Daily, Weekly): Smoother signals, fewer rotations, lower transaction costs
Lower timeframes (1H, 4H): More responsive, more rotations, higher potential but more noise
Recommendation: Start with Daily timeframe and Optimal strategy for most balanced results.
Step 4: Configure Backtest Period
Set start date to include various market conditions (bull, bear, sideways)
Ensure sufficient history for statistical significance (minimum 1 year recommended)
Compare metrics across different time periods to assess consistency
Step 5: Evaluate Performance
Look for:
Sharpe Ratio > 1.0: Acceptable risk-adjusted returns
Sharpe Ratio > 2.0: Very good risk-adjusted returns
Sortino Ratio > Sharpe Ratio: Strategy handles downside well
Omega Ratio > 1.5: Favorable gain/loss distribution
Portfolio Return > Benchmark: Strategy adds value vs. passive holding
Step 6: Monitor and Execute
Enable alerts for rotation notifications
Execute trades promptly when signals occur
Review trade history periodically to understand rotation patterns
Adjust asset universe if certain assets consistently underperform
Best Practices
DO:
✅ Include assets from different sectors or markets
✅ Use higher timeframes for fewer, more reliable signals
✅ Start with Conservative or Optimal strategy
✅ Backtest across multiple market conditions
✅ Consider transaction costs in your evaluation
✅ Monitor the Average Holding metric—longer holds generally mean lower costs
DON'T:
❌ Include highly correlated assets (reduces rotation benefit)
❌ Over-optimize on historical data
❌ Use Very Aggressive on low timeframes without understanding risks
❌ Ignore Maximum Drawdown—high returns with extreme drawdowns may not be sustainable
❌ Chase the highest returning backtest—consistency matters more
Performance Metrics Explained
Metric: What It Measures
Good Value Return Total: percentage gain/loss Positive
Benchmark Max DD Worst peak-to-trough decline: < 20% ideal, < 30% acceptable
Sharpe: Return per unit of total risk> 1.0 good, > 2.0 excellent
Sortino: Return per unit of downside risk> 1.5 good, > 2.5 excellent
Omega: Gain/loss probability ratio> 1.5 good, > 2.0 excellent
Avg Holding: Mean bars per position, Higher = lower turnover costs
***************************************************************************************************
Final Thoughts
Asset Rotation System provides a systematic, data-driven approach to portfolio management. By dynamically allocating capital to the strongest-performing asset among your selected universe, the strategy aims to capture momentum while avoiding underperformers.
The comprehensive metrics suite allows you to evaluate not just returns, but risk-adjusted performance, ensuring you understand the true quality of your results. Whether you're managing a stock portfolio, crypto holdings, or a diversified cross-asset allocation, this indicator provides the tools needed to implement a disciplined rotation strategy.
Remember: Past performance does not guarantee future results. Always validate the strategy across multiple market conditions and consider your personal risk tolerance before trading.
Ichimoku Trading Checklist - 5 Rules🧠 Description
This indicator implements a rule-based checklist built on Ichimoku Kinko Hyo, complemented with RSI and price structure, designed to help traders objectively evaluate whether a bullish setup is valid or not.
⚠️ This indicator does NOT generate buy or sell signals.
⚠️ It is NOT a trading system or financial advice.
The core philosophy is discipline and consistency:
If there is no setup, there is no trade.
________________________________________
✅ The 5 Rules Evaluated
1. Chikou Span above price (26 bars back)
Confirms that current price is above historical price, validating a bullish context.
2. Bullish TK Cross (Tenkan-sen > Kijun-sen)
Measures bullish momentum within the Ichimoku framework.
3. Bullish divergence or convergence between RSI and price
Evaluates relative strength using recent RSI pivots and price structure.
4. Kumo breakout followed by a valid pullback
Requires a bullish cloud breakout and a pullback that respects the structure.
5. Bullish Kumo (green cloud / twist)
Confirms that the Ichimoku cloud supports a bullish bias.
________________________________________
🚦 Decision Traffic Light (Final Row)
The last row of the table provides a traffic-light style summary:
• 🟢 5/5 rules met → Valid setup
• 🟡 1–4 rules met → Incomplete setup
• 🔴 0 rules met → No trade
Core message displayed: “No setup, No trade!” 🚫
________________________________________
🎨 Customization
Through the Inputs panel, users can customize:
• Header, body, and footer background colors
• Traffic-light colors and icons (🟢 🟡 🔴)
• Text alignment (left / center / right)
• Optional rule counter (x/5)
⚠️ Tables do not use TradingView’s Style tab; all customization is handled via Inputs.
________________________________________
⏱️ Timeframe
The indicator is timeframe-agnostic, but it was designed and tested primarily on the 1H timeframe, where Ichimoku and RSI structure tend to be more consistent.
________________________________________
⚠️ Disclaimer
This script is provided for educational and informational purposes only.
It does not constitute financial advice or a recommendation to buy or sell any asset.
Trading involves risk, and all decisions remain the sole responsibility of the user.
Remember that every strategy is based on probabilities and scenarios that you have already tested in hundreds of trades.
________________________________________
👤 Author
© Yesid Correa Cano
Pine Script v6
License: Mozilla Public License 2.0 (MPL-2.0)
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.
USOIL BOS Retest Strategy 2.0 This is generating 4.73% return nothing wow but will form the base of my trading engine






















