Forex Heatmap█ OVERVIEW
This indicator creates a dynamic grid display of currency pair cross rates (exchange rates) and percentage changes, emulating the Cross Rates and Heat Map widgets available on our Forex page. It provides a view of realtime exchange rates for all possible pairs derived from a user-specified list of currencies, allowing users to monitor the relative performance of several currencies directly on a TradingView chart.
█ CONCEPTS
Foreign exchange
The Foreign Exchange (Forex/FX) market is the largest, most liquid financial market globally, with an average daily trading volume of over 5 trillion USD. Open 24 hours a day, five days a week, it operates through a decentralized network of financial hubs in various major cities worldwide. In this market, participants trade currencies in pairs , where the listed price of a currency pair represents the exchange rate from a given base currency to a specific quote currency . For example, the "EURUSD" pair's price represents the amount of USD (quote currency) that equals one unit of EUR (base currency). Globally, the most traded currencies include the U.S. dollar (USD), Euro (EUR), Japanese yen (JPY), British pound (GBP), and Australian dollar (AUD), with USD involved in over 87% of all trades.
Understanding the Forex market is essential for traders and investors, even those who do not trade currency pairs directly, because exchange rates profoundly affect global markets. For instance, fluctuations in the value of USD can impact the demand for U.S. exports or the earnings of companies that handle multinational transactions, either of which can affect the prices of stocks, indices, and commodities. Additionally, since many factors influence exchange rates, including economic policies and interest rate changes, analyzing the exchange rates across currencies can provide insight into global economic health.
█ FEATURES
Requesting a list of currencies
This indicator requests data for every valid currency pair combination from the list of currencies defined by the "Currency list" input in the "Settings/Inputs" tab. The list can contain up to six unique currency codes separated by commas, resulting in a maximum of 30 requested currency pairs.
For example, if the specified "Currency list" input is "CAD, USD, EUR", the indicator requests and displays relevant data for six currency pair combinations: "CADUSD", "USDCAD", "CADEUR", "EURCAD", "USDEUR", "EURUSD". See the "Grid display" section below to understand how the script organizes the requested information.
Each item in the comma-separated list must represent a valid currency code. If the "Currency list" input contains an invalid currency code, the corresponding cells for that currency in the "Cross rates" or "Heat map" grid show "NaN" values. If the list contains empty items, e.g., "CAD, ,EUR, ", the indicator ignores them in its data requests and calculations.
NOTE: Some uncommon currency pair combinations might not have data feeds available. If no available symbols provide the exchange rates between two specified currencies, the corresponding table cells show "NaN" results.
Realtime data
The indicator retrieves realtime market prices, daily price changes, and minimum tick sizes for all the currency pairs derived from the "Currency list" input. It updates the retrieved information shown in its grid display after new ticks become available to reflect the latest known values.
NOTE: Pine scripts execute on realtime bars only when new ticks are available in the chart's data feed. If no new updates are available from the chart's realtime feed, it may cause a delay in the data the indicator receives.
Grid display
This indicator displays the requested data for each currency pair in a table with cells organized as a grid. Each row name corresponds to a pair's base currency , and each column name corresponds to a quote currency . The cell at the intersection of a specific row and column shows the value requested from the corresponding currency pair.
For example, the cell at the intersection of a "EUR" row and "USD" column shows the data retrieved for the "EURUSD" currency pair, and the cell at the "USD" row and "EUR" column shows data for the inverse pair ("USDEUR").
Note that the main diagonal cells in the table, where rows and columns with the same names intersect, are blank. The exchange rate from one currency to itself is always 1, and no Forex symbols such as "EUREUR" exist.
The dropdown input at the top of the "Settings/Inputs" tab determines the type of information displayed in the table. Two options are available: "Cross rates" and "Heat map" . Both modes color their cells for light and dark themes separately based on the inputs in the "Colors" section.
Cross rates
When a user selects the "Cross rates" display mode, the table's cells show the latest available exchange rate for each currency pair, emulating the behavior of the Cross Rates widget. Each cell's value represents the amount of the quote currency (column name) that equals one unit of the base currency (row name). This display allows users to compare cross rates across currency pairs, and their inverses.
The background color of each cell changes based on the most recent update to the exchange rate, allowing users to monitor the direction of short-term fluctuations as they occur. By default, the background turns green (positive cell color) when the cross rate increases from the last recorded update and red (negative cell color) when the rate decreases. The background color disappears after no new updates are available for 200 milliseconds.
Heat map
When a user selects the "Heat map" display mode, the table's cells show the latest daily percentage change of each currency pair, emulating the behavior of the Heat Map widget.
In this mode, the background color of each cell depends on the corresponding currency pair's daily performance. Heat maps typically use colors that vary in intensity based on the calculated values. This indicator uses the following color coding by default:
• Green (Positive cell color): Percentage change > +0.1%
• No color: Percentage change between 0.0% and +0.1%
• Bright red (Negative cell color): Percentage change < -0.1%
• Lighter/darker red (Minor negative cell color): Percentage change between 0.0% and -0.1%
█ FOR Pine Script™ CODERS
• This script utilizes dynamic requests to iteratively fetch information from multiple contexts using a single request.security() instance in the code. Previously, `request.*()` functions were not allowed within the local scopes of loops or conditional structures, and most `request.*()` function parameters, excluding `expression`, required arguments of a simple or weaker qualified type. The new `dynamic_requests` parameter in script declaration statements enables more flexibility in how scripts can use `request.*()` calls. When its value is `true`, all `request.*()` functions can accept series arguments for the parameters that define their requested contexts, and `request.*()` functions can execute within local scopes. See the Dynamic requests section of the Pine Script™ User Manual to learn more.
• Scripts can execute up to 40 unique `request.*()` function calls. A `request.*()` call is unique only if the script does not already call the same function with the same arguments. See this section of the User Manual's Limitations page for more information.
• Typically, when requesting higher-timeframe data with request.security() using barmerge.lookahead_on as the `lookahead` argument, the `expression` argument should use the history-referencing operator to offset the series, preventing lookahead bias on historical bars. However, the request.security() call in this script uses barmerge.lookahead_on without offsetting the `expression` because the script only displays results for the latest historical bar and all realtime bars, where there is no future information to leak into the past. Instead, using this call on those bars ensures each request fetches the most recent data available from each context.
• The request.security() instance in this script includes a `calc_bars_count` argument to specify that each request retrieves only a minimal number of bars from the end of each symbol's historical data feed. The script does not need to request all the historical data for each symbol because it only shows results on the last chart bar that do not depend on the entire time series. In this case, reducing the retrieved bars in each request helps minimize resource usage without impacting the calculated results.
Look first. Then leap.
Portfolio management
USYDFXIA AlgoCombination of MACD, Liquidity, Order Block & Smart Money Trading Concepts.
Algorithmic Signals achieving 90% win rate on 4H timeframe, 88% on 1H, 75% on 15M.
Created by,
Aariz E.
President & Head of Fund
USYD Forex Investment Association
Market Stats Panel [Daveatt]█ Introduction
I've created a script that brings TradingView's watchlist stats panel functionality directly to your charts. This isn't just another performance indicator - it's a pixel-perfect (kidding) recreation of TradingView's native stats panel.
Important Notes
You might need to adjust manually the scaling the firs time you're using this script to display nicely all the elements.
█ Core Features
Performance Metrics
The panel displays key performance metrics (1W, 1M, 3M, 6M, YTD, 1Y) in real-time, with color-coded boxes (green for positive, red for negative) for instant performance assessment.
Display Modes
Switch seamlessly between absolute prices and percentage returns, making it easy to compare assets across different price scales.
Absolute mode
Percent mode
Historical Comparison
View year-over-year performance with color-coded lines, allowing for quick historical pattern recognition and analysis.
Data Structure Innovation
Let's talk about one of the most interesting challenges I faced. PineScript has this quirky limitation where request.security() can only return 127 tuples at most. £To work around this, I implemented a dual-request system. The first request handles indices 0-63, while the second one takes care of indices 64-127.
This approach lets us maintain extensive historical data without compromising script stability.
And here's the cool part: if you need to handle even more years of historical data, you can simply extend this pattern by adding more request.security() calls.
Each additional call can fetch another batch of monthly open prices and timestamps, following the same structure I've used.
Think of it as building with LEGO blocks - you can keep adding more pieces to extend your historical reach.
Flexible Date Range
Unlike many scripts that box you into specific timeframes, I've designed this one to be completely flexible with your date selection. You can set any start year, any end year, and the script will dynamically scale everything to match. The visual presentation automatically adjusts to whatever range you choose, ensuring your data is always displayed optimally.
█ Customization Options
Visual Settings
The panel's visual elements are highly customizable. You can adjust the panel width to perfectly fit your workspace, fine-tune the line thickness to match your preferences, and enjoy the pre-defined year color scheme that makes tracking historical performance intuitive and visually appealing.
Box Dimensions
Every aspect of the performance boxes can be tailored to your needs. Adjust their height and width, fine-tune the spacing between them, and position the entire panel exactly where you want it on your chart. The goal is to make this tool feel like it's truly yours.
█ Technical Challenges Solved
Polyline Precision
Creating precise polylines was perhaps the most demanding aspect of this project.
The challenge was ensuring accurate positioning across both time and price axes, while handling percentage mode scaling with precision.
The script constantly updates the current year's data in real-time, seamlessly integrating new information as it comes in.
Axis Management
Getting the axes right was like solving a complex puzzle. The Y-axis needed to scale dynamically whether you're viewing absolute prices or percentages.
The X-axis required careful month labeling that stays clean and readable regardless of your selected timeframe.
Everything needed to align perfectly while maintaining proper spacing in all conditions.
█ Final Notes
This tool transforms complex market data into clear, actionable insights. Whether you're day trading or analyzing long-term trends, it provides the information you need to make informed decisions. And remember, while we can't predict the future, we can certainly be better prepared for it with the right tools at hand.
A word of warning though - seeing those red numbers in a beautifully formatted panel doesn't make them any less painful! 😉
---
Happy Trading! May your charts be green and your stops be far away!
Daveatt
Systematic Investment Tracker with Enhanced Features DCATürkçe Açıklama:
Bu TradingView Pine Script kodu, belirlenen tarih aralığında iki farklı yatırım stratejisi uygulayarak yatırım performansını analiz etmeyi sağlar. Kullanıcı, "Sürekli Alım" ve "Düştükçe Alım" stratejileri arasında bir karşılaştırma yapabilir. Her stratejide, toplam harcama, elde edilen miktar, ortalama maliyet ve kâr yüzdesi hesaplanır. Kod ayrıca dinamik alım miktarını ayarlama ve grafiksel işaretleyiciler ekleme özelliklerine sahiptir. Performans karşılaştırması için grafik üzerinde bilgi etiketi ve bir tablo sunulur. İki dil arasında geçiş yapma (Türkçe/İngilizce) seçeneği de mevcuttur.
English Description:
This TradingView Pine Script code enables users to analyze investment performance by applying two different investment strategies within a specified date range. Users can compare between "Systematic Purchase" and "Purchase on Decline" strategies. For each strategy, total expenditure, quantity acquired, average cost, and profit percentage are calculated. The script includes options for dynamic purchase adjustment and graphical markers. A performance comparison is presented through an info label and a table on the chart. Additionally, there is an option to switch between English and Turkish languages.
Simplest Strategy Crossover with Labels Buy/Sell to $1000This Pine Script code, titled Custom Moving Average Crossover with Labels, is a trading indicator developed for the TradingView platform. It enables traders to visualize potential buy and sell signals based on the crossover of two moving averages, offering customizable settings for enhanced flexibility. Here’s a breakdown of its key features:
Key Features
User-Defined Moving Averages:
The script includes two moving averages: a fast and a slow one. Users can adjust the periods of each average (default values are 10 for the fast MA and 100 for the slow MA), allowing them to adapt the indicator to various market conditions and trading styles.
Time-Restricted Signal Validity:
The indicator includes settings for active trading hours, defined in UTC time. Users specify a start and end hour, making it possible to limit buy and sell signals to certain times of the day. This is especially useful for traders who wish to avoid signals outside their preferred trading hours or during periods of high volatility.
Crossover-Based Buy and Sell Signals:
Buy Signal: A "Buy" label is triggered and displayed when the fast moving average crosses above the slow moving average within the user-defined trading hours, signifying a potential upward trend.
Sell Signal: A "Sell" label is generated when the fast moving average crosses below the slow moving average, indicating a possible downtrend. Labels are displayed on the chart, color-coded for easy identification: green for buys and red for sells.
Profit Target Labels (+100 Points):
After each buy or sell entry, the indicator tracks price movements. When the price increases by 100 points from a buy entry or decreases by 100 points from a sell entry, a +100 label appears to signify a 100-point movement.
These labels serve as checkpoints to help traders assess performance and decide on further actions, such as taking profits or adjusting stop losses.
Visual Customization:
The moving averages are color-coded (blue for fast MA, red for slow MA) for easy distinction, and label text appears in white to enhance visibility against various chart backgrounds.
Benefits for Traders
Efficient Trade Identification: The moving average crossover combined with time-based restrictions allows traders to capture key market trends within chosen hours.
Clear Profit Checkpoints: The +100 point label alerts traders to significant price movement, useful for those looking for set profit targets.
Flexibility: Customizable inputs give users control over the indicator’s behavior, making it suitable for both day trading and swing trading.
This indicator is designed for traders looking to enhance their technical analysis with reliable, user-defined buy/sell signals, helping to increase confidence and improve trade timing based on objective data.
Trade Management RulesThis script is a visual reminder of the user’s trade management rules, displayed on the left side of the Trading View chart. The purpose is to have these guidelines visible at all times while trading, helping the user stay disciplined.
Universal Trend and Valuation System [QuantAlgo]Universal Trend and Valuation System 📊🧬
The Universal Trend and Valuation System by QuantAlgo is an advanced indicator designed to assess asset valuation and trends across various timeframes and asset classes. This system integrates multiple advanced statistical indicators and techniques with Z-score calculations to help traders and investors identify overbought/sell and oversold/buy signals. By evaluating valuation and trend strength together, this tool empowers users to make data-driven decisions, whether they aim to follow trends, accumulate long-term positions, or identify turning points in mean-reverting markets.
💫 Conceptual Foundation and Innovation
The Universal Trend and Valuation System by QuantAlgo provides a unique framework for assessing market valuation and trend dynamics through a blend of Z-score analysis and trend-following algorithm. Unlike traditional indicators that only reflect price direction, this system incorporates multi-layered data to reveal the relative value of an asset, helping users determine whether it’s overvalued, undervalued, or approaching a trend reversal. By combining high quality trend-following tools, such as Dynamic Score Supertrend, DEMA RSI, and EWMA, it evaluates trend stability and momentum quality, while Z-scores of performance ratios like Sharpe, Sortino, and Omega standardize deviations from historical trends, enabling traders and investors to spot extreme conditions. This dual approach allows users to better identify accumulation (undervaluation) and distribution (overvaluation) phases, enhancing strategies like Dollar Cost Averaging (DCA) and overall timing for entries and exits.
📊 Technical Composition and Calculation
The Universal Trend-Following Valuation System is composed of several trend-following and valuation indicators that create a dynamic dual scoring model:
Risk-Adjusted Ratios (Sharpe, Sortino, Omega): These ratios assess trend quality by analyzing an asset’s risk-adjusted performance. Sharpe and Sortino provide insight into trend consistency and risk/reward, while Omega evaluates profitability potential, helping traders and investors assess how favorable a trend or an asset is relative to its associated risk.
Dynamic Z-Scores: Z-scores are applied to various metrics like Price, RSI, and RoC, helping to identify statistical deviations from the mean, which indicate potential extremes in valuation. By combining these Z-scores, the system produces a cumulative score that highlights when an asset may be overbought or oversold.
Aggregated Trend-Following Indicators: The model consolidates multiple high quality indicators to highlight probable trend shifts. This helps confirm the direction and strength of market moves, allowing users to spot reversals or entry points with greater clarity.
📈 Key Indicators and Features
The Universal Trend and Valuation System combines various technical and statistical tools to deliver a well-rounded analysis of market trends and valuation:
The indicator utilizes trend-following indicators like RSI with DEMA smoothing and Dynamic Score Supertrend to minimize market noise, providing clearer and more stable trend signals. Sharpe, Sortino, and Omega ratios are calculated to assess risk-adjusted performance and volatility, adding a layer of analysis for evaluating trend quality. Z-scores are applied to these ratios, as well as Price and Rate of Change (RoC), to detect deviations from historical trends, highlighting extreme valuation levels.
The system also incorporates multi-layered visualization with gradient color coding to signal valuation states across different market conditions. These adaptive visual cues, combined with threshold-based alerts for overbought and oversold zones, help traders and investors track probable trend reversals or continuations and identify accumulation or distribution zones, adding reliability to both trend-following and mean-reversion strategies.
⚡️ Practical Applications and Examples
✅ Add the Indicator: Add the Universal Trend-Following Valuation System to your favourites and to your chart.
👀 Monitor Trend Shifts and Valuation Levels: Watch the average Z score, trend probability state and gradient colors to identify overbought and oversold conditions. During undervaluation, consider using a DCA strategy to gradually accumulate positions (buy), while overvaluation may signal distribution or profit-taking phases (sell).
🔔 Set Alerts: Configure alerts for significant trend or valuation changes, ensuring you can act on market movements promptly, even when you’re not actively monitoring the charts.
🌟 Summary and Usage Tips
The Universal Trend and Valuation System by QuantAlgo is a highly adaptable tool, designed to support both trend-following and valuation analysis across different market environments. By combining valuation metrics with high quality trend-following indicators, it helps traders and investors identify the relative value of an asset based on historical norms, providing more reliable overbought/sell and oversold/buy signals. The tool’s flexibility across asset types and timeframes makes it ideal for both short-term trading and long-term investment strategies like DCA, allowing users to capture meaningful trends while minimizing noise.
TradeSafe™Trade Safe™ is an innovative tool designed to help traders conquer two of the biggest obstacles to success—greed and overtrading. Our software integrates powerful behavioral insights with intuitive, user-friendly controls, providing a seamless experience that keeps you on track with your strategy. By setting clear boundaries and reminding you when it's time to pause, Trade Safe™ empowers you to trade with confidence, balance, and discipline. Built for both beginners and experienced traders, Trade Safe™ is your partner for maintaining focus and maximizing long-term gains without succumbing to the pitfalls of emotional trading.
Using Trade Safe™ is simple. Just enter your stop-loss on your second trade, and once that limit is reached, a screen will automatically pop up, blocking your ability to see the charts. This feature forces you to step away from the screen, making it easier to pause until the next trading session and preventing impulsive trades that can disrupt your goals.
Watchlist & Symbols Distribution [Daveatt]TLDR;
I got bored so I just coded the TradingView watchlist interface in Pinescript :)
TLDR 2:
Sharing it open-source what took me 1 full day to code - haven't coded in Pinescript in a long time, so I'm a bit slow for now :)
█ OVERVIEW
This script offers a comprehensive market analysis tool inspired by TradingView's native watchlist interface features.
It combines an interactive watchlist with powerful distribution visualization capabilities and a performance comparison panel.
The script was developed with a focus on providing multiple visualization methods while working within PineScript's limitations.
█ DEVELOPMENT BACKGROUND
The pie chart implementation was greatly inspired by the ( "Crypto Map Dashboard" script / )
adapting its circular visualization technique to create dynamic distribution charts. However, due to PineScript's 500-line limitation per script, I had to optimize the code to allow users to switch between pie chart analysis and performance comparison modes rather than displaying both simultaneously.
█ SETUP AND DISPLAY
For optimal visualization, users need to adjust the chart's display settings manually.
This involves:
Expanding the indicator window vertically to accommodate both the watchlist and graphical elements
Adjusting the Y-axis scale by dragging it to ensure proper spacing for the comparison panel grid
Modifying the X-axis scale to achieve the desired time window display
Fine-tuning these adjustments whenever switching between pie chart and comparison panel modes
These manual adjustments are necessary due to PineScript's limitations in controlling chart scaling programmatically. While this requires some initial setup, it allows users to customize the display to their preferred viewing proportions.
█ MAIN FEATURES
Distribution Analysis
The script provides three distinct distribution visualization modes through a pie chart.
Users can analyze their symbols by exchanges, asset types (such as Crypto, Forex, Futures), or market sectors.
If you can't see it well at first, adjust your chart scaling until it's displayed nicely.
Asset Exchanges
www.tradingview.com
Asset Types
Asset Sectors
The pie charts feature an optional 3D effect with adjustable depth and angle parameters. To enhance visual customization, four different color schemes are available: Default, Pastel, Dark, and Neon.
Each segment of the pie chart includes interactive tooltips that can be configured to show different levels of detail. Importantly, the pie chart only visualizes the distribution of selected assets (those marked with a checkmark in the watchlist), providing a focused view of the user's current interests.
Interactive Watchlist
The watchlist component displays real-time data for up to 10 user-defined symbols. Each entry shows current price, price changes (both absolute and percentage), volume metrics, and a comparison toggle.
The table is dynamically updated and features color-coded entries that correspond to their respective performance lines in the comparison chart. The watchlist serves as both an information display and a control panel for the comparison feature.
Performance Comparison
One of the script's most innovative features is its performance comparison panel.
Using polylines for smooth visualization, it tracks the 30-day performance of selected symbols relative to a 0% baseline.
The comparison chart includes a sophisticated grid system with 5% intervals and a dynamic legend showing current performance values.
The polyline implementation allows for fluid, continuous lines that accurately represent price movements, providing a more refined visual experience than traditional line plots. Like the pie charts, the comparison panel only displays performance lines for symbols that have been selected in the watchlist, allowing users to focus on their specific assets of interest.
█ TECHNICAL IMPLEMENTATION
The script utilizes several advanced PineScript features:
Dynamic array management for symbol tracking
Polyline-based charting for smooth performance visualization
Real-time data processing with security calls
Interactive tooltips and labels
Optimized drawing routines to maintain performance
Selective visualization based on user choices
█ CUSTOMIZATION
Users can personalize almost every aspect of the script:
Symbol selection and comparison preferences
Visual theme selection with four distinct color schemes
Pie chart dimensions and positioning
Tooltip information density
Component visibility toggles
█ LIMITATIONS
The primary limitation stems from PineScript's 500-line restriction per script.
This constraint necessitated the implementation of a mode-switching system between pie charts and the comparison panel, as displaying both simultaneously would exceed the line limit. Additionally, the script relies on manual chart scale adjustments, as PineScript doesn't provide direct control over chart scaling when overlay=false is enabled.
However, these limitations led to a more focused and efficient design approach that gives users control over their viewing experience.
█ CONCLUSION
All those tools exist in the native TradingView watchlist interface and they're better than what I just did.
However, now it exists in Pinescript... so I believe it's a win lol :)
Dynamic Market Correlation Analyzer (DMCA) v1.0Description
The Dynamic Market Correlation Analyzer (DMCA) is an advanced TradingView indicator designed to provide real-time correlation analysis between multiple assets. It offers a comprehensive view of market relationships through correlation coefficients, technical indicators, and visual representations.
Key Features
- Multi-asset correlation tracking (up to 5 symbols)
- Dynamic correlation strength categorization
- Integrated technical indicators (RSI, MACD, DX)
- Customizable visualization options
- Real-time price change monitoring
- Flexible timeframe selection
## Use Cases
1. **Portfolio Diversification**
- Identify highly correlated assets to avoid concentration risk
- Find negatively correlated assets for hedging strategies
- Monitor correlation changes during market events
2. Pairs Trading
- Detect correlation breakdowns for potential trading opportunities
- Track correlation strength for pair selection
- Monitor technical indicators for trade timing
3. Risk Management
- Assess portfolio correlation risk in real-time
- Monitor correlation shifts during market stress
- Identify potential portfolio vulnerabilities
4. **Market Analysis**
- Study sector relationships and rotations
- Analyze cross-asset correlations (e.g., stocks vs. commodities)
- Track market regime changes through correlation patterns
Components
Input Parameters
- **Timeframe**: Custom timeframe selection for analysis
- **Length**: Correlation calculation period (default: 20)
- **Source**: Price data source selection
- **Symbol Selection**: Up to 5 customizable symbols
- **Display Options**: Table position, text color, and size settings
Technical Indicators
1. **Correlation Coefficient**
- Range: -1 to +1
- Strength categories: Strong/Moderate/Weak (Positive/Negative)
2. **RSI (Relative Strength Index)**
- 14-period default setting
- Momentum comparison across assets
3. **MACD (Moving Average Convergence Divergence)**
- Standard settings (12, 26, 9)
- Trend direction indicator
4. **DX (Directional Index)**
- Trend strength measurement
- Based on DMI calculations
Visual Components
1. **Correlation Table**
- Symbol identifiers
- Correlation coefficients
- Correlation strength descriptions
- Price change percentages
- Technical indicator values
2. **Correlation Plot**
- Real-time correlation visualization
- Multiple correlation lines
- Reference levels at -1, 0, and +1
- Color-coded for easy identification
Installation and Setup
1. Load the indicator on TradingView
2. Configure desired symbols (up to 5)
3. Adjust timeframe and calculation length
4. Customize display settings
5. Enable/disable desired components (table, plot, RSI)
Best Practices
1. **Symbol Selection**
- Choose related but distinct assets
- Include a mix of asset classes
- Consider market cap and liquidity
2. **Timeframe Selection**
- Match timeframe to trading strategy
- Consider longer timeframes for strategic analysis
- Use shorter timeframes for tactical decisions
3. **Interpretation**
- Monitor correlation changes over time
- Consider multiple timeframes
- Combine with other technical analysis tools
- Account for market conditions and volatility
Performance Notes
- Calculations update in real-time
- Resource usage scales with number of active symbols
- Historical data availability may affect initial calculations
Version History
- v1.0: Initial release with core functionality
- Multi-symbol correlation analysis
- Technical indicator integration
- Customizable display options
Future Enhancements (Planned)
- Additional technical indicators
- Advanced correlation algorithms
- Enhanced visualization options
- Custom alert conditions
- Statistical significance testing
RS+ Majors Allocation | viResearchRS+ Majors Allocation | viResearch
Conceptual Foundation and Innovation
The "RS+ Majors Allocation" script is a comprehensive strategy for managing a crypto portfolio focused on BTC, ETH, and SOL. By dynamically rotating between these major assets, the strategy aims to identify the strongest performer in real-time and allocate capital accordingly. The script incorporates a relative strength (RS) model that leverages price movements and a custom scoring system to rank each asset's performance. This allows the strategy to maintain positions in favorable market conditions while moving to cash during periods of weakness.
The script also includes a trend regime filter to further refine allocations. This filter ensures that an asset's own trend aligns with the market’s trend before committing to an allocation, adding another layer of protection against downturns. The approach is designed to outperform traditional buy-and-hold strategies by minimizing risk exposure during unfavorable market conditions.
Technical Composition and Calculation
The "RS+ Majors Allocation" script combines several technical elements to execute the strategy:
Relative Strength Model: Each asset (BTC, ETH, SOL) is evaluated through a ratio matrix, comparing their performance relative to one another. A scoring system is applied to these ratios to rank the assets, determining which is outperforming. This dynamic evaluation is central to the strategy's decision-making process.
Trend Regime Filter: This filter uses trend indicators to assess whether the market and individual assets are in a favorable state. If an asset’s trend score does not meet the criteria, it won't be allocated capital, thus avoiding exposure to potential downturns.
Equity Tracking and Allocation: The script tracks the portfolio's equity performance over time, plotting it against a traditional buy-and-hold strategy for comparison. Allocation decisions are based on the scores of BTC, ETH, and SOL, with the system selecting the top-performing asset and moving to cash if no asset meets the criteria.
Performance Metrics: To evaluate the effectiveness of the strategy, the script calculates several key performance indicators:
Sharpe Ratio: Measures risk-adjusted returns.
Sortino Ratio: Focuses on downside risk by considering only negative fluctuations.
Omega Ratio: Analyzes returns relative to risk.
Maximum Drawdown: Shows the largest peak-to-trough decline, indicating potential loss exposure.
Features and User Inputs
The script offers a range of customizable parameters to tailor the strategy to individual preferences and market conditions:
Asset Selection: Users can choose the specific assets to include in the rotation, with the script currently focusing on BTC, ETH, and SOL. The trend regime filter is optional, allowing for a more aggressive or conservative approach.
Equity Visualization: The script provides real-time equity tracking, comparing the portfolio's performance with individual assets. Users can adjust visualization settings to focus on specific assets or the overall strategy.
Starting Date: The backtesting period can be set to begin at a specific date, helping to analyze the strategy’s performance over different timeframes.
Bar Colors and Alerts: Visual cues, including colored bars, indicate the active trend direction of the selected asset. Additionally, alerts notify traders when the system rotates between assets or moves to cash.
Practical Applications
The "RS+ Majors Allocation" script is designed for traders who want to manage a crypto portfolio with a focus on risk-adjusted returns. It is particularly effective in several scenarios:
Asset Rotation: The dynamic scoring system allows the script to rotate between BTC, ETH, and SOL based on relative strength, capitalizing on the strongest performer at any given time.
Downside Protection: The trend regime filter helps avoid exposure during market-wide downturns by staying in cash, minimizing drawdowns during periods of high volatility.
Active Portfolio Management: By using real-time data to make allocation decisions, the script offers a more hands-on approach to portfolio management compared to passive holding strategies.
Advantages and Strategic Value
This script brings a structured and disciplined approach to portfolio management, combining trend analysis, relative strength, and performance metrics to optimize returns. The use of a scoring system for asset rotation, along with the trend filter, makes it versatile and adaptable to different market environments. The script aims to outperform traditional buy-and-hold strategies by focusing on the strongest assets while reducing risk during unfavorable conditions.
The visual and performance feedback provided by the script allows traders to gain deeper insights into their portfolio’s behavior, helping to make data-driven decisions.
Summary and Usage Tips
The "RS+ Majors Allocation" script is a powerful tool for managing a crypto portfolio with a focus on performance optimization and risk management. By incorporating this strategy, traders can dynamically allocate capital to the top-performing assets while protecting their portfolio from significant downturns. Adjust the trend regime filter, threshold settings, and asset choices to fit your market outlook and trading goals. The script's equity tracking and performance metrics will provide clear insights into how well the strategy is performing compared to a traditional buy-and-hold approach.
Remember to use backtesting to assess the script's effectiveness over different timeframes and market conditions. Keep in mind that past performance does not guarantee future results, so consider using this strategy in conjunction with other analysis tools for a comprehensive approach to trading.
PortfolioThe "Portfolio" indicator is a specialized tool designed exclusively for European investors who utilize euro-denominated ETFs to invest in the S&P 500 index. This unique instrument provides valuable insights into individual stock allocations within the S&P 500, offering a precise breakdown of each company's weight in the portfolio when viewing the chart of a particular symbol.
Key Features
Real-time Portfolio Composition: The indicator calculates and displays the exact Euro value and percentage of an investor's portfolio allocated to the currently viewed stock. As stock prices fluctuate, it dynamically adjusts to show up-to-date allocation information.
Automatic Currency Conversion: All values are automatically converted to Euros, providing a clear picture of portfolio allocation in the investor's home currency. This feature is particularly useful for European investors who need to consider currency exchange rates when investing in U.S. stocks.
Performance Tracking: The indicator includes a feature that shows the daily change in Euro value for the specific stock holding, helping investors quickly assess performance without the need for manual calculations.
Tailored for Euro-based S&P 500 ETF Investors
This indicator is designed with a specific audience in mind: European investors using euro-denominated ETFs to gain exposure to the S&P 500. It's particularly relevant for those using UCITS-compliant ETFs that track the S&P 500, which are widely available to European investors.
The tool takes into account the nuances of investing in U.S. stocks through European financial products, including considerations of currency hedging that some ETFs offer to protect against EUR/USD fluctuations.
Limited Scope
It's important to note that this indicator has a narrow focus and may not be relevant for investors using other currencies, those not invested in S&P 500 ETFs, or traders focused on short-term strategies. However, for its target audience, it offers a powerful tool for portfolio management and allocation tracking, providing insights that are typically difficult to obtain in real-time for Euro-based S&P 500 ETF investors.
By offering a clear, real-time view of portfolio allocation and performance in Euros, this indicator empowers European investors to make informed decisions about their S&P 500 ETF investments. It bridges the gap between U.S. market data and European investment needs, making it an invaluable tool for its specific user base.
aPortfolioaPortfolio can be overlayed on any chart with any timeframe. It provides a way to keep track of your portfolio(s) real-time and dynamically. Tool tips provide information about each input item.
Up to 8 customizable assets can be defined using 2 exchanges. The amount owned, the exchange used and the amount spent (in Euro or US Dollar) can be entered per asset.
Furthermore, available Euros and US Dollars can be entered as part of your portfolio.
The output consists of a label and a table , which can both be configured or switched off.
The label is being displayed at the current bar and price on the chart. It can show various totals and a total profit percentage.
The table display position can be set to “AUTO” or to a fixed customizable position. Per used asset, it can show the amount, value in BTC, value in Euro, value in US Dollar and value in a customizable currency. Also, the profit percentage and the percentage of the total portfolio value of an asset can be shown.
The total line shows the values and the profit percentage of the whole portfolio.
In the VIEW options, on the bottom of the settings/inputs window, the coloring can be customized. The profit percentages provide dynamic coloring.
It is also possible to use the EU (#.###,#) format in stead of the US format for numbers.
Although it has its limitations, aPortfolio might be useful and conveniently provides real-time insight.
GuidoN - October 2024
Bollinger Bands Mean Reversion by Kevin Davey Bollinger Bands Mean Reversion Strategy Description
The Bollinger Bands Mean Reversion Strategy is a popular trading approach based on the concept of volatility and market overreaction. The strategy leverages Bollinger Bands, which consist of an upper and lower band plotted around a central moving average, typically using standard deviations to measure volatility. When the price moves beyond these bands, it signals potential overbought or oversold conditions, and the strategy seeks to exploit a reversion back to the mean (the central band).
Strategy Components:
1. Bollinger Bands:
The bands are calculated using a 20-period Simple Moving Average (SMA) and a multiple (usually 2.0) of the standard deviation of the asset’s price over the same period. The upper band represents the SMA plus two standard deviations, while the lower band is the SMA minus two standard deviations. The distance between the bands increases with higher volatility and decreases with lower volatility.
2. Mean Reversion:
Mean reversion theory suggests that, over time, prices tend to move back toward their historical average. In this strategy, a buy signal is triggered when the price falls below the lower Bollinger Band, indicating a potential oversold condition. Conversely, the position is closed when the price rises back above the upper Bollinger Band, signaling an overbought condition.
Entry and Exit Logic:
Buy Condition: The strategy enters a long position when the price closes below the lower Bollinger Band, anticipating a mean reversion to the central band (SMA).
Sell Condition: The long position is exited when the price closes above the upper Bollinger Band, implying that the market is likely overbought and a reversal could occur.
This approach uses mean reversion principles, aiming to capitalize on short-term price extremes and volatility compression, often seen in sideways or non-trending markets. Scientific studies have shown that mean reversion strategies, particularly those based on volatility indicators like Bollinger Bands, can be effective in capturing small but frequent price reversals  .
Scientific Basis for Bollinger Bands:
Bollinger Bands, developed by John Bollinger, are widely regarded in both academic literature and practical trading as an essential tool for volatility analysis and mean reversion strategies. Research has shown that Bollinger Bands effectively identify relative price highs and lows, and can be used to forecast price volatility and detect potential breakouts . Studies in financial markets, such as those by Fernández-Rodríguez et al. (2003), highlight the efficacy of Bollinger Bands in detecting overbought or oversold conditions in various assets .
Who is Kevin Davey?
Kevin Davey is an award-winning algorithmic trader and highly regarded expert in developing and optimizing systematic trading strategies. With over 25 years of experience, Davey gained significant recognition after winning the prestigious World Cup Trading Championships multiple times, where he achieved triple-digit returns with minimal drawdown. His success has made him a key figure in algorithmic trading education, with a focus on disciplined and rule-based trading systems.
Dynamic Score Supertrend [QuantAlgo]Dynamic Score Supertrend 📈🚀
The Dynamic Score Supertrend by QuantAlgo introduces a sophisticated trend-following tool that combines the well-known Supertrend indicator with an innovative dynamic trend scoring technique . By tracking market momentum through a scoring system that evaluates price behavior over a customizable window, this indicator adapts to changing market conditions. The result is a clearer, more adaptive tool that helps traders and investors detect and capitalize on trend shifts with greater precision.
💫 Conceptual Foundation and Innovation
At the core of the Dynamic Score Supertrend is the dynamic trend score system , which measures price movements relative to the Supertrend’s upper and lower bands. This scoring technique adds a layer of trend validation, assessing the strength of price trends over time. Unlike traditional Supertrend indicators that rely solely on ATR calculations, this system incorporates a scoring mechanism that provides more insight into trend direction, allowing traders and investors to navigate both trending and choppy markets with greater confidence.
✨ Technical Composition and Calculation
The Dynamic Score Supertrend utilizes the Average True Range (ATR) to calculate the upper and lower Supertrend bands. The dynamic trend scoring technique then compares the price to these bands over a customizable window, generating a trend score that reflects the current market direction.
When the score exceeds the uptrend or downtrend thresholds, it signals a possible shift in market direction. By adjusting the ATR settings and window length, the indicator becomes more adaptable to different market conditions, from steady trends to periods of higher volatility. This customization allows users to refine the Supertrend’s sensitivity and responsiveness based on their trading or investing style.
📈 Features and Practical Applications
Customizable ATR Settings: Adjust the ATR length and multiplier to control the sensitivity of the Supertrend bands. This allows the indicator to smooth out noise or react more quickly to price shifts, depending on market conditions.
Window Length for Dynamic Scoring: Modify the window length to adjust how many data points the scoring system considers, allowing you to tailor the indicator’s responsiveness to short-term or long-term trends.
Uptrend/Downtrend Thresholds: Set thresholds for identifying trend signals. Increase these thresholds for more reliable signals in choppy markets, or lower them for more aggressive entry points in trending markets.
Bar and Background Coloring: Visual cues such as bar coloring and background fills highlight the direction of the current trend, making it easier to spot potential reversals and trend shifts.
Trend Confirmation: The dynamic trend score system provides a clearer confirmation of trend strength, helping you identify strong, sustained movements while filtering out false signals.
⚡️ How to Use
✅ Add the Indicator: Add the Dynamic Score Supertrend to your favourites, then apply it to your chart. Adjust the ATR length, multiplier, and dynamic score settings to suit your trading or investing strategy.
👀 Monitor Trend Shifts: Track price movements relative to the Supertrend bands and use the dynamic trend score to confirm the strength of a trend. Bar and background colors make it easy to visualize key trend shifts.
🔔 Set Alerts: Configure alerts when the dynamic trend score crosses key thresholds, so you can act on significant trend changes without constantly monitoring the charts.
🌟 Summary and Usage Tips
The Dynamic Score Supertrend by QuantAlgo is a robust trend-following tool that combines the power of the Supertrend with an advanced dynamic scoring system. This approach provides more adaptable and reliable trend signals, helping traders and investors make informed decisions in trending markets. The customizable ATR settings and scoring thresholds make it versatile across various market conditions, allowing you to fine-tune the indicator for both short-term momentum and long-term trend following. To maximize its effectiveness, adjust the settings based on current market volatility and use the visual cues to confirm trend shifts. The Dynamic Score Supertrend offers a refined, probabilistic approach to trading and investing, making it a valuable addition to your toolkit.
Lot Size CalculatorThis Pine Script indicator, "Lot Size Calculator", is designed to help traders effectively manage their risk by calculating the optimal lot size for a given position based on account balance, risk percentage, and the distance to Stop Loss. The script also visually plots key price levels such as Entry Price, Stop Loss, and multiple Take Profit targets (1R, 2R, 3R).
Key Features:
Risk Management: Enter your account balance, risk percentage, entry price, and stop loss price to calculate the optimal lot size for your trade. The lot size is computed based on the risk amount you are willing to take.
Take Profit Levels: The script calculates and plots Take Profit levels for 1R, 2R, and 3R multiples of the risk, providing a structured approach to setting targets and managing rewards.
Visual Representation: The indicator plots horizontal lines on the chart for Entry Price, Stop Loss, and Take Profit levels. The Take Profit levels are styled as dotted lines for easy differentiation, and all lines extend infinitely in both directions for clarity.
Convenient Information Table: A table displayed in the top-right corner of the chart provides key information such as account balance, lot size, entry price, stop loss price, and risk details. The lot size value is highlighted for better visibility.
This tool is ideal for traders looking to maintain disciplined risk management and to visually identify key levels directly on the chart.
RiskMosaic | SandiB V2Risk On/Off System
This indicator acts as a comprehensive framework that integrates a diverse range of indicators—spanning liquidity, sentiment, market volatility, and macroeconomic factors—to construct a holistic view of risk.
By blending these varied components, the system identifies shifts in risk-on and risk-off environments, providing a complete and dynamic assessment of global market conditions.
This allows for more informed decision-making by capturing both localized and broad market influences in real time, enabling proactive risk management and the ability to adapt to rapidly changing conditions.
Composition :
4 different categories - each one equal weight
-> Mix of Global & U.S Liquidity
-> Mix of different macro factors
-> Mix of Crypto and Commodities
-> Mix of Volatility & Risk Indicators
Colors description:
- Green = strong = full risk on sentiment/environment
- Red = weak = full risk off sentiment/environment
- Blue = recovery = medium risk on sentiment/environment
- Purple = contraction = medium risk of sentiment/environment
-> Colors are based on oscillator line:
- crossing over 0 or 0.4 = green
- crossing under 0 or -0.5 = red
- crossing over -0.35 = blue
- crossing under 0.35 = purple
Value at Risk [OmegaTools]The "Value at Risk" (VaR) indicator is a powerful financial risk management tool that helps traders estimate the potential losses in a portfolio over a specified period of time, given a certain level of confidence. VaR is widely used by financial institutions, traders, and risk managers to assess the probability of portfolio losses in both normal and volatile market conditions. This TradingView script implements a comprehensive VaR calculation using several models, allowing users to visualize different risk scenarios and adjust their trading strategies accordingly.
Concept of Value at Risk
Value at Risk (VaR) is a statistical technique used to measure the likelihood of losses in a portfolio or financial asset due to market risks. In essence, it answers the question: "What is the maximum potential loss that could occur in a given portfolio over a specific time horizon, with a certain confidence level?" For instance, if a portfolio has a one-day 95% VaR of $10,000, it means that there is a 95% chance the portfolio will not lose more than $10,000 in a single day. Conversely, there is a 5% chance of losing more than $10,000. VaR is a key risk management tool for portfolio managers and traders because it quantifies potential losses in monetary terms, allowing for better-informed decision-making.
There are several ways to calculate VaR, and this indicator script incorporates three of the most commonly used models:
Historical VaR: This approach uses historical returns to estimate potential losses. It is based purely on past price data, assuming that the past distribution of returns is indicative of future risks.
Variance-Covariance VaR: This model assumes that asset returns follow a normal distribution and that the risk can be summarized using the mean and standard deviation of past returns. It is a parametric method that is widely used in financial risk management.
Exponentially Weighted Moving Average (EWMA) VaR: In this model, recent data points are given more weight than older data. This dynamic approach allows the VaR estimation to react more quickly to changes in market volatility, which is particularly useful during periods of market stress. This model uses the Exponential Weighted Moving Average Volatility Model.
How the Script Works
The script starts by offering users a set of customizable input settings. The first input allows the user to choose between two main calculation modes: "All" or "OCT" (Only Current Timeframe). In the "All" mode, the script calculates VaR using all available methodologies—Historical, Variance-Covariance, and EWMA—providing a comprehensive risk overview. The "OCT" mode narrows the calculation to the current timeframe, which can be particularly useful for intraday traders who need a more focused view of risk.
The next input is the lookback window, which defines the number of historical periods used to calculate VaR. Commonly used lookback periods include 21 days (approximately one month), 63 days (about three months), and 252 days (roughly one year), with the script supporting up to 504 days for more extended historical analysis. A longer lookback period provides a more comprehensive picture of risk but may be less responsive to recent market conditions.
The confidence level is another important setting in the script. This represents the probability that the loss will not exceed the VaR estimate. Standard confidence levels are 90%, 95%, and 99%. A higher confidence level results in a more conservative risk estimate, meaning that the calculated VaR will reflect a more extreme loss scenario.
In addition to these core settings, the script allows users to customize the visual appearance of the indicator. For example, traders can choose different colors for "Bullish" (Risk On), "Bearish" (Risk Off), and "Neutral" phases, as well as colors for highlighting "Breaks" in the data, where returns exceed the calculated VaR. These visual cues make it easy to identify periods of heightened risk at a glance.
The actual VaR calculation is broken down into several models, starting with the Historical VaR calculation. This is done by computing the logarithmic returns of the asset's closing prices and then using linear interpolation to determine the percentile corresponding to the desired confidence level. This percentile represents the potential loss in the asset over the lookback period.
Next, the script calculates Variance-Covariance VaR using the mean and standard deviation of the historical returns. The standard deviation is multiplied by a z-score corresponding to the chosen confidence level (e.g., 1.645 for 95% confidence), and the resulting value is subtracted from the mean return to arrive at the VaR estimate.
The EWMA VaR model uses the EWMA for the sigma parameter, the standard deviation, obtaining a specific dynamic in the volatility. It is particularly useful in volatile markets where recent price behavior is more indicative of future risk than older data.
For traders interested in intraday risk management, the script provides several methods to adjust VaR calculations for lower timeframes. By using intraday returns and scaling them according to the chosen timeframe, the script provides a dynamic view of risk throughout the trading day. This is especially important for short-term traders who need to manage their exposure during high-volatility periods within the same day. The script also incorporates an EWMA model for intraday data, which gives greater weight to the most recent intraday price movements.
In addition to calculating VaR, the script also attempts to detect periods where the asset's returns exceed the estimated VaR threshold, referred to as "Breaks." When the returns breach the VaR limit, the script highlights these instances on the chart, allowing traders to quickly identify periods of extreme risk. The script also calculates the average of these breaks and displays it for comparison, helping traders understand how frequently these high-risk periods occur.
The script further visualizes the risk scenario using a risk phase classification system. Depending on the level of risk, the script categorizes the market as either "Risk On," "Risk Off," or "Risk Neutral." In "Risk On" mode, the market is considered bullish, and the indicator displays a green background. In "Risk Off" mode, the market is bearish, and the background turns red. If the market is neither strongly bullish nor bearish, the background turns neutral, signaling a balanced risk environment.
Traders can customize whether they want to see this risk phase background, along with toggling the display of the various VaR models, the intraday methods, and the break signals. This flexibility allows traders to tailor the indicator to their specific needs, whether they are day traders looking for quick intraday insights or longer-term investors focused on historical risk analysis.
The "Risk On" and "Risk Off" phases calculated by this Value at Risk (VaR) script introduce a novel approach to market risk assessment, offering traders an advanced toolset to gauge market sentiment and potential risk levels dynamically. These risk phases are built on a combination of traditional VaR methodologies and proprietary logic to create a more responsive and intuitive way to manage exposure in both normal and volatile market conditions. This method of classifying market conditions into "Risk On," "Risk Off," or "Risk Neutral" is not something that has been traditionally associated with VaR, making it a groundbreaking addition to this indicator.
How the "Risk On" and "Risk Off" Phases Are Calculated
In typical VaR implementations, the focus is on calculating the potential losses at a given confidence level without providing an overall market outlook. This script, however, introduces a unique risk classification system that takes the output of various VaR models and translates it into actionable signals for traders, marking whether the market is in a Risk On, Risk Off, or Risk Neutral phase.
The Risk On and Risk Off phases are primarily determined by comparing the current returns of the asset to the average VaR calculated across several different methods, including Historical VaR, Variance-Covariance VaR, and EWMA VaR. Here's how the process works:
1. Threshold Setting and Effect Calculation: The script first computes the average VaR using the selected models. It then checks whether the current returns (expressed as a negative value to signify loss) exceed the average VaR value. If the current returns surpass the calculated VaR threshold, this indicates that the actual market risk is higher than expected, signaling a potential shift in market conditions.
2. Break Analysis: In addition to monitoring whether returns exceed the average VaR, the script counts the number of instances within the lookback period where this breach occurs. This is referred to as the "break effect." For each period in the lookback window, the script checks whether the returns surpass the calculated VaR threshold and increments a counter. The percentage of periods where this breach occurs is then calculated as the "effect" or break percentage.
3. Dual Effect Check (if "Double" Risk Scenario is selected): When the user chooses the "Double" risk scenario mode, the script performs two layers of analysis. First, it calculates the effect of returns exceeding the VaR threshold for the current timeframe. Then, it calculates the effect for the lower intraday timeframe as well. Both effects are compared to the user-defined confidence level (e.g., 95%). If both effects exceed the confidence level, the market is deemed to be in a high-risk situation, thus triggering a Risk Off phase. If both effects fall below the confidence level, the market is classified as Risk On.
4. Risk Phases Determination: The final risk phase is determined by analyzing these effects in relation to the confidence level:
- Risk On: If the calculated effect of breaks is lower than the confidence level (e.g., fewer than 5% of periods show returns exceeding the VaR threshold for a 95% confidence level), the market is considered to be in a relatively safe state, and the script signals a "Risk On" phase. This is indicative of bullish conditions where the potential for extreme loss is minimal.
- Risk Off: If the break effect exceeds the confidence level (e.g., more than 5% of periods show returns breaching the VaR threshold), the market is deemed to be in a high-risk state, and the script signals a "Risk Off" phase. This indicates bearish market conditions where the likelihood of significant losses is higher.
- Risk Neutral: If the break effect hovers near the confidence level or if there is no clear trend indicating a shift toward either extreme, the market is classified as "Risk Neutral." In this phase, neither bulls nor bears are dominant, and traders should remain cautious.
The phase color that the script uses helps visualize these risk phases. The background will turn green in Risk On conditions, red in Risk Off conditions, and gray in Risk Neutral phases, providing immediate visual feedback on market risk. In addition to this, when the "Double" risk scenario is selected, the background will only turn green or red if both the current and intraday timeframes confirm the respective risk phase. This double-checking process ensures that traders are only given a strong signal when both longer-term and short-term risks align, reducing the likelihood of false signals.
A New Way of Using Value at Risk
This innovative Risk On/Risk Off classification, based on the interaction between VaR thresholds and market returns, represents a significant departure from the traditional use of Value at Risk as a pure risk measurement tool. Typically, VaR is employed as a backward-looking measure of risk, providing a static estimate of potential losses over a given timeframe with no immediate actionable feedback on current market conditions. This script, however, dynamically interprets VaR results to create a forward-looking, real-time signal that informs traders whether they are operating in a favorable (Risk On) or unfavorable (Risk Off) environment.
By incorporating the "break effect" analysis and allowing users to view the VaR breaches as a percentage of past occurrences, the script adds a predictive element that can be used to time market entries and exits more effectively. This **dual-layer risk analysis**, particularly when using the "Double" scenario mode, adds further granularity by considering both current timeframe and intraday risks. Traders can therefore make more informed decisions not just based on historical risk data, but on how the market is behaving in real-time relative to those risk benchmarks.
This approach transforms the VaR indicator from a risk monitoring tool into a decision-making system that helps identify favorable trading opportunities while alerting users to potential market downturns. It provides a more holistic view of market conditions by combining both statistical risk measurement and intuitive phase-based market analysis. This level of integration between VaR methodologies and real-time signal generation has not been widely seen in the world of trading indicators, marking this script as a cutting-edge tool for risk management and market sentiment analysis.
I would like to express my sincere gratitude to @skewedzeta for his invaluable contribution to the final script. From generating fresh ideas to applying his expertise in reviewing the formula, his support has been instrumental in refining the outcome.
Majors Rotation System [BackQuant]Majors Rotation System
Introducing BackQuant's Majors Rotation System, a comprehensive portfolio management tool for rotating among the major cryptocurrencies—BTC, ETH, and SOL. This system is designed to optimize returns by selecting the strongest-performing asset while avoiding periods of market weakness. It employs a long and cash-only strategy, meaning the system will only hold positions when market conditions are favorable, and will stay in cash during downtrends. Additionally, it incorporates a powerful regime filter to ensure the system is inactive during market-wide downturns.
This script is ideal for crypto traders looking to improve performance by dynamically allocating capital based on real-time performance metrics, rather than relying on a simple buy-and-hold strategy.
Key Features
Dynamic Asset Rotation: The system constantly evaluates the performance of BTC, ETH, and SOL, selecting the strongest asset based on a ratio matrix. This matrix compares the relative strength of each asset to one another, ensuring that your portfolio is always positioned in the cryptocurrency with the most momentum.
Long and Cash-Only Portfolio: This system only takes long positions or remains in cash. By avoiding short positions, it reduces exposure during market downturns. The built-in regime filter ensures the system only operates when the broader market (represented by the TOTAL crypto market cap) is trending up, offering additional protection against unfavorable market conditions.
Equity Tracking: The script provides a real-time visualization of portfolio equity compared to a buy-and-hold strategy. It displays the equity curve of the portfolio while allowing you to compare it against the hypothetical equity of holding BTC, ETH, or SOL individually (Buy and Hold).
Performance Metrics: In addition to equity visualization, the system provides detailed performance metrics, including:
Sharpe Ratio: Measures risk-adjusted returns.
Sortino Ratio: Focuses on downside risk.
Omega Ratio: Evaluates returns relative to risk.
Maximum Drawdown: The maximum observed loss from a peak to a trough.
These metrics allow traders to assess the efficiency of the rotation system compared to simply holding assets.
Visual Cues:
Painted Candles: The script provides a visual trend indicator by painting candles according to the trend of the selected chart, helping traders quickly identify momentum shifts.
Support for Multiple Assets: The system allows users to toggle between BTC, ETH, and SOL or view the entire portfolio at once. It displays key metrics for each asset and offers an intuitive way to understand which asset is currently outperforming.
Regime Filter: A key aspect of this system is the regime filter, which only allows trading in favorable market conditions. It uses a Universal TPI (Trend Performance Indicator) to evaluate whether the overall crypto market (TOTAL Market Cap) and key assets (BTC, ETH) are in a bullish trend. If the market is in a downtrend, the system will exit positions and move into cash.
Customizable Parameters: Users can customize several important aspects of the system:
Starting Date: Choose when the backtest or live trading begins.
Starting Capital: Set the initial capital for backtesting purposes.
Visualization Options: Toggle between base data, ratioed data, and equity plots. Users can also customize the line width and color settings for better chart clarity.
Adaptive Momentum Scoring: The system uses advanced indicators, which are not disclosed (proprietary) to assess the trend and momentum of the selected cryptocurrencies dynamically.
How the Rotation Works
The system uses a universal algorithm to calculate trend and momentum signals for BTC, ETH, and SOL. These signals are processed through a ratio matrix, which compares the performance of each asset against the others. Based on this comparison, the system identifies the strongest asset and allocates capital accordingly.
BTC, ETH, and SOL Scores: These scores represent the relative strength of each asset based on the universal algorithm. The system dynamically selects the asset with the highest score, rotating out of underperforming assets and into the top performer.
Allocation Decisions: The system determines whether to allocate capital to BTC, ETH, SOL, or Cash based on the scores. If none of the assets show strength, the system defaults to cash to protect the portfolio from market downturns.
Equity and Buy-and-Hold Comparisons
This script provides a side-by-side comparison of the portfolio’s equity curve and a buy-and-hold strategy:
Portfolio Equity: Shows the performance of the system as it rotates between BTC, ETH, and SOL.
Buy-and-Hold Equity: Displays how the portfolio would have performed if you simply held BTC, ETH, or SOL without trading.
These comparisons allow traders to see how the dynamic rotation system performs relative to a passive holding strategy.
Alerts and Visual Feedback
The system provides real-time alerts when asset allocations change, notifying traders when the system moves capital between assets or into cash. Additionally, the system offers detailed visual feedback, including:
Equity Curve Plots: Displays the equity curve of the portfolio and the individual assets.
Score Labels: Shows the strength scores for BTC, ETH, and SOL directly on the chart for easy monitoring.
Final Thoughts
The Majors Rotation System offers a powerful way to navigate the highly volatile crypto market by rotating between the strongest performing assets and staying in cash when conditions are unfavorable. With its advanced metrics, equity tracking, and built-in regime filter, this system is designed to optimize returns while minimizing risk.
Savitzky Golay Median Filtered RSI [BackQuant]Savitzky Golay Median Filtered RSI
Introducing BackQuant's Savitzky Golay Median Filtered RSI, a cutting-edge indicator that enhances the classic Relative Strength Index (RSI) by applying both a Savitzky-Golay filter and a median filter to provide smoother and more reliable signals. This advanced approach helps reduce noise and captures true momentum trends with greater precision. Let’s break down how the indicator works, the features it offers, and how it can improve your trading strategy.
Core Concept: Relative Strength Index (RSI)
The Relative Strength Index (RSI) is a widely used momentum oscillator that measures the speed and change of price movements. It oscillates between 0 and 100, with levels above 70 typically indicating overbought conditions and levels below 30 indicating oversold conditions. However, the standard RSI can sometimes generate noisy signals, especially in volatile markets, making it challenging to identify reliable entry and exit points.
To improve upon the traditional RSI, this indicator introduces two powerful filters: the Savitzky-Golay filter and a median filter.
Savitzky-Golay Filter: Smoothing with Precision
The Savitzky-Golay filter is a digital filtering technique used to smooth data while preserving important features, such as peaks and trends. Unlike simple moving averages that can distort important price data, the Savitzky-Golay filter uses polynomial regression to fit the data, providing a more accurate and less lagging result.
In this script, the Savitzky-Golay filter is applied to the RSI values to smooth out short-term fluctuations and provide a more reliable signal. By using a window size of 5 and a polynomial degree of 2, the filter effectively reduces noise without compromising the integrity of the underlying price movements.
Median Filter: Reducing Outliers
After applying the Savitzky-Golay filter, the median filter is applied to the smoothed RSI values. The median filter is particularly effective at removing short-lived outliers, further enhancing the accuracy of the RSI by reducing the impact of sudden and temporary price spikes or drops. This combination of filters creates an ultra-smooth RSI that is better suited for detecting true market trends.
Long and Short Signals
The Savitzky Golay Median Filtered RSI generates long and short signals based on user-defined threshold levels:
Long Signals: A long signal is triggered when the filtered RSI exceeds the Long Threshold (default set at 176). This indicates that momentum is shifting upward, and it may present a good buying opportunity.
Short Signals: A short signal is generated when the filtered RSI falls below the Short Threshold (default set at 162). This suggests that momentum is weakening, potentially signaling a selling opportunity or exit from a long position.
These threshold levels can be adjusted to suit different market conditions and timeframes, allowing traders to fine-tune the sensitivity of the indicator.
Customization and Visualization Options
The Savitzky Golay Median Filtered RSI comes with several customization options, enabling traders to tailor the indicator to their specific needs:
Calculation Source: Select the price source for the RSI calculation (default is OHLC4, but it can be changed to close, open, high, or low prices).
RSI Period: Adjust the lookback period for the RSI calculation (default is 14).
Median Filter Length: Control the length of the median filter applied to the smoothed RSI, affecting how much noise is removed from the signal.
Threshold Levels: Customize the long and short thresholds to define the sensitivity for generating buy and sell signals.
UI Settings: Choose whether to display the RSI and thresholds on the chart, color the bars according to trend direction, and adjust the line width and colors used for long and short signals.
Visual Feedback: Color-Coded Signals and Thresholds
To make the signals easier to interpret, the indicator offers visual feedback by coloring the price bars and the RSI plot according to the current market trend:
Green Bars indicate long signals when momentum is bullish.
Red Bars indicate short signals when momentum is bearish.
Gray Bars indicate neutral or undecided conditions when no clear signal is present.
In addition, the Long and Short Thresholds can be plotted directly on the chart to provide a clear reference for when signals are triggered, allowing traders to visually gauge the strength of the RSI relative to its thresholds.
Alerts for Automation
For traders who prefer automated notifications, the Savitzky Golay Median Filtered RSI includes built-in alert conditions for long and short signals. You can configure these alerts to notify you when a buy or sell condition is met, ensuring you never miss a trading opportunity.
Trading Applications
This indicator is versatile and can be used in a variety of trading strategies:
Trend Following: The combination of Savitzky-Golay and median filtering makes this RSI particularly useful for identifying strong trends without being misled by short-term noise. Traders can use the long and short signals to enter trades in the direction of the prevailing trend.
Reversal Trading: By adjusting the threshold levels, traders can use this indicator to spot potential reversals. When the RSI moves from overbought to oversold levels (or vice versa), it may signal a shift in market direction.
Swing Trading: The smoothed RSI provides a clear signal for short to medium-term price movements, making it an excellent tool for swing traders looking to capitalize on momentum shifts.
Risk Management: The filtered RSI can be used as part of a broader risk management strategy, helping traders avoid false signals and stay in trades only when the momentum is strong.
Final Thoughts
The Savitzky Golay Median Filtered RSI takes the classic RSI to the next level by applying advanced smoothing techniques that reduce noise and improve signal reliability. Whether you’re a trend follower, swing trader, or reversal trader, this indicator provides a more refined approach to momentum analysis, helping you make better-informed trading decisions.
As with all indicators, it is important to backtest thoroughly and incorporate sound risk management strategies when using the Savitzky Golay Median Filtered RSI in your trading system.
Thus following all of the key points here are some sample backtests on the 1D Chart
Disclaimer: Backtests are based off past results, and are not indicative of the future.
INDEX:BTCUSD
INDEX:ETHUSD
BINANCE:SOLUSD
Portfolio SnapShot v0.3Here is a Tradingview Pinescript that I call "Portfolio Snapshot". It is based on two other separate scripts that I combined, modified and simplified - shoutout to RedKTrader (Portfolio Tracker - Table Version) and FriendOfTheTrend (Portfolio Tracker For Stocks & Crypto) for their inspiration and code. I was using both of these scripts, and decided to combine the two and increase the number of stocks to 20. I was looking for an easy way to track my entire portfolio (scattered across 5 accounts) PnL on a total and stock basis. PnL - that's it, very simple by design. The features are:
1) Track PnL across multiple accounts, from inception and current day.
2) PnL is reported in two tables, at the portfolio level and individual stock level
3) Both tables can be turned on/off and placed anywhere on the chart.
4) Input up to 20 assets (stocks, crypto, ETFs)
The user has to manually calculate total shares and average basis for stocks in multiple accounts, and then inputs this in the user input dialog. I update mine as each trade is made, or you can just update once a week or so.
I've pre-loaded it with the major indices and sector ETFs, plus URA, GLD, SLV. 100 shares of each, and prices are based on the close Jan 2 2024. So if you don't want to track your portfolio, you can use it to track other things you find interesting, such as annual performance of each sector.
Liquidations Zones [ChartPrime]The Liquidation Zones indicator is designed to detect potential liquidation zones based on common leverage levels such as 10x, 25x, 50x, and 100x. By calculating percentage distances from recent pivot points, the indicator shows where leveraged positions are most likely to get liquidated. It also tracks buy and sell volumes in these zones, helping traders assess market pressure and predict liquidation scenarios. Additionally, the indicator features a heat map mode to highlight areas where orders and stop-losses might be clustered.
⯁ KEY FEATURES AND HOW TO USE
⯌ Leverage Zones Detection :
The indicator identifies zones where positions with leverage ratios of 100x, 50x, 25x, and 10x are at risk of liquidation. These zones are based on percentage moves from recent pivots: a 1% move can liquidate 100x positions, a 4% move affects 25x positions, and so on.
⯌ Liquidated Zones and Volume Tracking :
The indicator displays liquidated zones by plotting gray areas where the price potentually liquidate positons. It calculates the volume needed to liquidate positions in these zones, showing volume from bullish candles if short positions were liquidated and volume from bearish candles for long positions. This feature helps traders assess the risk of liquidation as the price approaches these zones.
⯌ Buy/Sell Volume Calculation :
Buy and sell volumes are calculated from the most recent pivot high or low. For buy volume, only bullish candles are considered, while for sell volume, only bearish candles are summed. This data helps traders gauge the strength of potential liquidation in different zones.
Example of buy and sell volume tracking in active zones:
⯌ Liquidity Heat Map :
In heat map mode, the indicator visualizes potential liquidity areas where orders and stop-losses may be clustered. This map highlights zones that are likely to experience liquidations based on leverage ratios. Additionally, it tracks the highest and lowest price levels for the past 100 bars, while also displaying buy and sell volumes. This feature is useful for predicting market moves driven by liquidation events.
⯁ USER INPUTS
Length : Determines the number of bars used to calculate pivots for liquidation zones.
Extend : Controls how far the liquidation zones are extended on the chart.
Leverage Options : Toggle options to display zones for different leverage levels: 10x, 25x, 50x, and 100x.
Display Heat Map : Enables or disables the liquidity heat map feature.
⯁ CONCLUSION
The Liquidation Zones indicator provides a powerful tool for identifying potential liquidation zones, tracking volume pressure, and visualizing liquidity areas on the chart. With its real-time updates and multiple features, this indicator offers valuable insights for managing risk and anticipating market moves driven by leveraged positions.