Four Supertrend By Baljit AujlaThis Pine Script is an implementation of a "Four Supertrend" indicator by Baljit Aujla. It calculates and plots four Supertrend indicators based on the Average True Range (ATR) method, allowing for different ATR periods and multipliers for each line.
Here is an explanation of the key components:
Inputs
1:- ATR Periods: Four different periods for ATR, adjustable by the user (defaults: 10, 11, 12, 13).
2:- ATR Multipliers: Four different multipliers for the ATR, adjustable by the user (defaults: 1.0, 2.0, 3.0, 4.0).
3:- Source: The data source used for calculation, default is the average of high and low prices (hl2).
4:- Change ATR Calculation Method: Option to switch between the traditional ATR and a simple moving average of true range (SMA of TR).
5:- Signal Display- Options to show buy/sell signals and highlight trends.
Logic:
The script computes four separate Supertrend lines using the ATR method for each line. For each of the four lines, it calculates an uptrend and downtrend threshold, and the trend direction changes when the close price crosses these thresholds.
For each trend line:
1. Uptrend and Downtrend Calculation: The script uses ATR-based bands above and below the price. The uptrend line is calculated by subtracting the ATR multiplied by a given multiplier from the source price, and the downtrend line is calculated by adding the ATR multiplied by a multiplier to the source price.
2. Trend Reversal Logic: The trend switches based on the price action relative to the uptrend and downtrend lines. If the price moves above the downtrend, it signals a switch to an uptrend, and vice versa for a downtrend.
3. Signal Generation: Buy signals occur when the trend changes from negative to positive (down to up), and sell signals occur when the trend changes from positive to negative (up to down).
Plots:
The script plots:
Uptrend and Downtrend Lines: These are visualized as green and red lines for each trend.
Buy/Sell Signals: Small circles are drawn on the chart when a trend change occurs (buy and sell signals).
Trend Highlighting: Background highlighting is applied to show when the market is in an uptrend (green) or downtrend (red).
Alerts:
The script has commented-out alert conditions (alertcondition), which can be enabled to send notifications when a buy or sell signal occurs, or when a trend change happens.
Enhancements:
1. Background Highlighting: This is an option to visually emphasize uptrends and downtrends by filling the background with respective colors.
2. Signal Visibility: You can toggle whether to show the buy/sell signals on the chart.
3. ATR Calculation Method: Option to change the ATR calculation method (using SMA of TR vs the default ATR).
The script is useful for identifying multi-timeframe trends with adjustable parameters and provides both signals and visual markers on the chart to aid in trading decisions.
Issues and Improvements:
The code seems to be truncated, specifically for the last Supertrend line (Line 4). To fully complete the functionality for the fourth line, the logic for up4, down4 and tread4 needs to be finished, similar to the other three lines.
Would you like help finishing the script for the fourth line or improving specific parts of it?
Trend Analysis
Super CCI By Baljit AujlaThe indicator you've shared is a custom CCI (Commodity Channel Index) with multiple types of Moving Averages (MA) and Divergence Detection. It is designed to help traders identify trends and reversals by combining the CCI with various MAs and detecting different types of divergences between the price and the CCI.
Key Components of the Indicator:
CCI (Commodity Channel Index):
The CCI is an oscillator that measures the deviation of the price from its average price over a specific period. It helps identify overbought and oversold conditions and the strength of a trend.
The CCI is calculated by subtracting a moving average (SMA) from the price and dividing by the average deviation from the SMA. The CCI values fluctuate above and below a zero centerline.
Multiple Moving Averages (MA):
The indicator allows you to choose from a variety of moving averages to smooth the CCI line and identify trend direction or support/resistance levels. The available types of MAs include:
SMA (Simple Moving Average)
EMA (Exponential Moving Average)
WMA (Weighted Moving Average)
HMA (Hull Moving Average)
RMA (Running Moving Average)
SMMA (Smoothed Moving Average)
TEMA (Triple Exponential Moving Average)
DEMA (Double Exponential Moving Average)
VWMA (Volume-Weighted Moving Average)
ZLEMA (Zero-Lag Exponential Moving Average)
You can select the type of MA to use with a specified length to help identify the trend direction or smooth out the CCI.
Divergence Detection:
The indicator includes a divergence detection mechanism to identify potential trend reversals. Divergences occur when the price and an oscillator like the CCI move in opposite directions, signaling a potential change in price momentum.
Four types of divergences are detected:
Bullish Divergence: Occurs when the price makes a lower low, but the CCI makes a higher low. This indicates a potential reversal to the upside.
Bearish Divergence: Occurs when the price makes a higher high, but the CCI makes a lower high. This indicates a potential reversal to the downside.
Hidden Bullish Divergence: Occurs when the price makes a higher low, but the CCI makes a lower low. This suggests a continuation of the uptrend.
Hidden Bearish Divergence: Occurs when the price makes a lower high, but the CCI makes a higher high. This suggests a continuation of the downtrend.
Each type of divergence is marked on the chart with arrows and labels to alert traders to potential trading opportunities. The labels include the divergence type (e.g., "Bull Div" for Bullish Divergence) and have customizable text colors.
Visual Representation:
The CCI and its associated moving average are plotted on the indicator panel below the price chart. The CCI is plotted as a line, and its color changes depending on whether it is above or below the moving average:
Green when the CCI is above the MA (indicating bullish momentum).
Red when the CCI is below the MA (indicating bearish momentum).
Horizontal lines are drawn at specific levels to help identify key CCI thresholds:
200 and -200 levels indicate extreme overbought or oversold conditions.
75 and -75 levels represent less extreme levels of overbought or oversold conditions.
The 0 level acts as a neutral or baseline level.
A background color fill between the 75 and -75 levels helps highlight the neutral zone.
Customization Options:
CCI Length: You can customize the length of the CCI, which determines the period over which the CCI is calculated.
MA Length: The length of the moving average applied to the CCI can also be adjusted.
MA Type: Choose from a variety of moving averages (SMA, EMA, WMA, etc.) to smooth the CCI.
Divergence Detection: The indicator automatically detects the four types of divergences (bullish, bearish, hidden bullish, hidden bearish) and visually marks them on the chart.
How to Use the Indicator:
Trend Identification: When the CCI is above the selected moving average, it suggests bullish momentum. When the CCI is below the moving average, it suggests bearish momentum.
Overbought/Oversold Conditions: The CCI values above 100 or below -100 indicate overbought and oversold conditions, respectively.
Divergence Analysis: The detection of bullish or bearish divergences can signal potential trend reversals. Hidden divergences may suggest trend continuation.
Trading Signals: You can use the divergence markers (arrows and labels) as potential buy or sell signals, depending on whether the divergence is bullish or bearish.
Practical Application:
This indicator is useful for traders who want to:
Combine the CCI with different moving averages for trend-following strategies.
Identify overbought and oversold conditions using the CCI.
Use divergence detection to anticipate potential trend reversals or continuations.
Have a highly customizable tool for various trading strategies, including trend trading, reversal trading, and divergence-based trading.
Overall, this is a comprehensive tool that combines multiple technical analysis techniques (CCI, moving averages, and divergence) in a single indicator, providing traders with a robust way to analyze price action and spot potential trading opportunities.
RS Cycles [QuantVue]The RS Cycles indicator is a technical analysis tool that expands upon traditional relative strength (RS) by incorporating Beta-based adjustments to provide deeper insights into a stock's performance relative to a benchmark index. It identifies and visualizes positive and negative performance cycles, helping traders analyze trends and make informed decisions.
Key Concepts:
Traditional Relative Strength (RS):
Definition: A popular method to compare the performance of a stock against a benchmark index (e.g., S&P 500).
Calculation: The traditional RS line is derived as the ratio of the stock's closing price to the benchmark's closing price.
RS=Stock Price/Benchmark Price
Usage: This straightforward comparison helps traders spot periods of outperformance or underperformance relative to the market or a specific sector.
Beta-Adjusted Relative Strength (Beta RS):
Concept: Traditional RS assumes equal volatility between the stock and benchmark, but Beta RS accounts for the stock's sensitivity to market movements.
Calculation:
Beta measures the stock's return relative to the benchmark's return, adjusted by their respective volatilities.
Alpha is then computed to reflect the stock's performance above or below what Beta predicts:
Alpha=Stock Return−(Benchmark Return×β)
Significance: Beta RS highlights whether a stock outperforms the benchmark beyond what its Beta would suggest, providing a more nuanced view of relative strength.
RS Cycles:
The indicator identifies positive cycles when conditions suggest sustained outperformance:
Short-term EMA (3) > Mid-term EMA (10) > Long-term EMA (50).
The EMAs are rising, indicating positive momentum.
RS line shows upward movement over a 3-period window.
EMA(21) > 0 confirms a broader uptrend.
Negative cycles are marked when the opposite conditions are met:
Short-term EMA (3) < Mid-term EMA (10) < Long-term EMA (50).
The EMAs are falling, indicating negative momentum.
RS line shows downward movement over a 3-period window.
EMA(21) < 0 confirms a broader downtrend.
This indicator combines the simplicity of traditional RS with the analytical depth of Beta RS, making highlighting true relative strength and weakness cycles.
IV Rank/Percentile with Williams VIX FixDisplay IV Rank / IV Percentile
This indicator is based on William's VixFix, which replicates the VIX—a measure of the implied volatility of the S&P 500 Index (SPX). The key advantage of the VixFix is that it can be applied to any security, not just the SPX.
IV Rank is calculated by identifying the highest and lowest implied volatility (IV) values over a selected number of past periods. It then determines where the current IV lies as a percentage between these two extremes. For example, if over the past five periods the highest IV was 30%, the lowest was 10%, and the current IV is 20%, the IV Rank would be 50%, since 20% is halfway between 10% and 30%.
IV Percentile, on the other hand, considers all past IV values—not just the highest and lowest—and calculates the percentage of these values that are below the current IV. For instance, if the past five IV values were 30%, 10%, 11%, 15%, and 17%, and the current IV is 20%, the IV Rank remains at 50%. However, the IV Percentile is 80% because 4 out of the 5 past values (80%) are below the current IV of 20%.
TechniTrend: CandleMetrics🟦 Overview
The TechniTrend: CandleMetrics Indicator is a powerful tool designed to give traders an in-depth analysis of candlestick structures. This indicator allows users to identify potential reversal points, trend continuations, and other crucial market behaviors by examining key ratios between candle components—such as body, shadow, and overall range—alongside volume conditions. The advanced filtering options offer flexibility for both novice and experienced traders, enabling tailored setups to suit different trading strategies.
🟦 Key Features
🔸Customizable Ratios: Set thresholds for Body-to-Range, Shadow-to-Range, Upper Shadow-to-Range, and Lower Shadow-to-Range ratios.
🔸Volume-Based Filters: Integrate volume conditions to strengthen the reliability of signals.
🔸Flexible Conditions: Choose whether filters should work independently or in combination, allowing for precise pattern identification.
🔸Visual Markers: Mark potential signals with a distinct background color and symbols on the chart.
🔸Alerts: Receive notifications for each selected condition, ensuring you never miss an opportunity.
🟦 How It Works
The CandleMetrics Indicator operates by analyzing the relationship between different components of each candlestick, combined with volume data to determine the strength of signals. Here’s a detailed breakdown of each feature:
🔸 Body to Range Ratio:
This filter compares the size of the candle's body to its total range (from high to low).
Example Setting: If you’re interested in spotting candles with small bodies relative to their total range, you might set the Body-to-Range Ratio to “Less than 0.3.”
🔸 Shadow to Range Ratio:
This examines the combined size of both shadows (upper and lower) relative to the entire candle range.
Example Setting: Use a Shadow-to-Range Ratio set to “More than 0.8” to find candles with significant wick lengths, suggesting market indecision.
🔸 Upper Shadow to Range Ratio:
This filter assesses the proportion of the upper shadow (wick) in relation to the candle’s full range.
Example Setting: “Less than 0.05” can help identify situations where the upper shadow is minimal, indicating strong downward pressure.
🔸 Lower Shadow to Range Ratio:
It measures the lower shadow compared to the entire candle range.
Example Setting: “More than 0.7” is useful for detecting potential rejection patterns at lower prices, hinting at a possible bullish reversal.
🔸 Volume Filter:
Integrates volume data to verify the reliability of each candle pattern.
Example Setting: Apply a Volume Filter Length of 100 with an SMA type to smooth volume data over a longer period, filtering out short-term noise and focusing on significant volume shifts.
🟦 Combining Filters
The indicator offers an option to Combine Filters. When this setting is enabled, all selected conditions must be met simultaneously for a candle to be marked. If disabled, each condition functions independently, allowing more flexibility in detecting diverse patterns.
🟦 Examples & Use Cases
🔸Example 1: Spotting Reversal Opportunities
I used the following configuration to find potential bullish reversals:
Upper Shadow to Range Ratio: “Less than 0.05” – Looking for candles with almost no upper shadow.
Lower Shadow to Range Ratio: “More than 0.7” – Highlighting candles with a significant lower shadow.
Volume Filter Length: 100 with SMA.
This setup effectively highlights candles where price rejection is happening at lower levels, suggesting a potential trend reversal to the upside.
🔸Example 2: Detecting Market Uncertainty
If you want to focus on candles showing market hesitation, try:
Shadow to Range Ratio: “More than 0.85” – Emphasizing long-wick candles that could indicate indecision.
Disable Combine Filters to allow flexibility, marking any candle meeting the above criteria.
🟦 Detailed Explanation of Each Option
Here’s a clear and concise breakdown of each option for a better understanding:
1. Body to Range Ratio
Purpose: This ratio shows how significant the candle's body is compared to its overall range. A smaller body-to-range ratio can indicate a potential reversal if the market appears indecisive.
How to Use: Increase the ratio to filter for stronger trend candles; decrease it to identify reversal or indecision candles.
2. Shadow to Range Ratio
Purpose: This filter captures the size of both shadows relative to the candle's total range. A larger ratio often points to market hesitation, while a smaller ratio suggests a decisive move.
How to Use: Adjust this filter to focus on candles with long wicks (indecision) or short wicks (decisiveness).
3. Upper Shadow to Range Ratio
Purpose: Helps to identify candles with strong downward moves by focusing on the upper wick length. A small upper shadow can imply sellers' dominance.
How to Use: Lower the ratio to detect candles with minimal upward rejection.
4. Lower Shadow to Range Ratio
Purpose: Targets candles with strong buying pressure by analyzing the lower shadow. A larger lower shadow may indicate a bullish reversal.
How to Use: Increase the ratio to spot rejection candles with significant lower shadows.
5. Volume Filter
Purpose: Adds a volume component to verify the validity of each candlestick pattern. Higher-than-average volume often signifies the strength of a move.
How to Use: Adjust the filter length and type to smooth out volume fluctuations based on your trading timeframe.
🟦 Indicator Alerts
Each filter has its own alert configuration, enabling traders to stay updated on market conditions that meet their selected criteria. You can customize alerts to trigger whenever a condition is met, helping to manage trades even when away from the screen.
Market GhostGhost Candles: Volume-Based Transparency Indicator
Before adding the indicator to the chart, hide the chart candles (the chart would get blank) otherwise no changes will be visible on your chart due to the display of the original candles (transparencies won't be visible because the full-opaque candles cover them)
This unique indicator dynamically adjusts the transparency of candles based on their volume relative to the past X candles. Candles with low volume become more transparent, while those with higher volume appear more opaque, creating a smooth gradient effect. This allows for a visual representation of market activity where low-volume candles "fade" into the background, making high-volume candles stand out more clearly.
Customizable Lookback Period: Adjust the lookback period (X candles) to suit your analysis.
Volume-Based Visualization: A smooth gradient of transparency helps to visualize volume strength relative to recent market activity.
Unique Aesthetic: Adds a unique, "ghostly" aesthetic to the chart, ideal for identifying volume trends without the clutter of traditional indicators.
This script is perfect for traders who want to visually highlight volume strength while maintaining a clean, easy-to-read chart.
Azlan MA Silang PLUS++Overview
Azlan MA Silang PLUS++ is an advanced moving average crossover trading indicator designed for traders who want to jump back into the market when they missed their first opportunity to take a trade. It implements a sophisticated dual moving average system with customizable settings and re-entry signals, making it suitable for both trend following and swing trading strategies.
Key Features
• Dual Moving Average System with multiple MA types (EMA, SMA, WMA, LWMA)
• Customizable price sources for each moving average
• Smart re-entry system with configurable maximum re-entries
• Visual signals with background coloring and shape markers
• Comprehensive alert system for both initial and re-entry signals
• Flexible parameter customization through input options
Input Parameters
Moving Average Configuration
• MA1 Type: Choice between SMA, EMA, WMA, LWMA (default: EMA)
• MA2 Type: Choice between SMA, EMA, WMA, LWMA (default: EMA)
• MA1 Length: Minimum value 1 (default: 8)
• MA2 Length: Minimum value 1 (default: 15)
• MA1 & MA2 Shift: Offset values for moving averages
• Price Sources: Configurable for each MA (Open, High, Low, Close, HL/2, HLC/3, HLCC/4)
Re-entry System
• Enable/Disable re-entry signals
• Maximum re-entries allowed (default: 3)
Technical Implementation
Price Source Calculation
The script implements a flexible price source system through the price_source() function:
• Supports standard OHLC values
• Includes compound calculations (HL/2, HLC/3, HLCC/4)
• Defaults to close price if invalid source specified
Moving Average Types
Implements four MA calculations:
1. SMA (Simple Moving Average)
2. EMA (Exponential Moving Average)
3. WMA (Weighted Moving Average)
4. LWMA (Linear Weighted Moving Average)
Signal Generation Logic
Initial Signals
• Buy Signal: MA1 crosses above MA2 with price above both MAs
• Sell Signal: MA1 crosses below MA2 with price below both MAs
Re-entry Signals
Re-entry system activates when:
1. Price crosses under MA1 in buy mode (or over in sell mode)
2. Price returns to cross back over MA1 (or under for sells)
3. Position relative to MA2 confirms trend direction
4. Number of re-entries hasn't exceeded maximum allowed
Visual Components
• MA1: Blue line (width: 2)
• MA2: Red line (width: 2)
• Background Colors:
o Green (60% opacity): Bullish conditions
o Red (60% opacity): Bearish conditions
• Signal Markers:
o Initial Buy/Sell: Up/Down arrows with "BUY"/"SELL" labels
o Re-entry Buy/Sell: Up/Down arrows with "RE-BUY"/"RE-SELL" labels
Alert System
Generates alerts for:
• Initial buy/sell signals
• Re-entry opportunities
• Alerts include ticker and timeframe information
• Configured for once-per-bar-close frequency
Usage Tips
1. Moving Average Selection
o Shorter periods (MA1) capture faster moves
o Longer periods (MA2) identify overall trend
o EMA responds faster to price changes than SMA
2. Re-entry System
o Best used in strong trending markets
o Limit maximum re-entries based on market volatility
o Monitor price action around MA1 for potential re-entry points
3. Risk Management
o Use additional confirmation indicators
o Set appropriate stop-loss levels
o Consider market conditions when using re-entry signals
Code Structure
The script follows a modular design with distinct sections:
1. Input parameter definitions
2. Helper functions for price and MA calculations
3. Main signal generation logic
4. Visual elements and plotting
5. Alert system implementation
This organization makes the code maintainable and easy to modify for custom needs.
Trend FinderEnglish
Trend Finder is an indicator designed to identify breakouts and breakdowns based on specified timeframes. It monitors the previous high and low prices and changes the bar color when the current close price surpasses these levels.
Features
Customizable Timeframes: Set your preferred high/low and close resolutions.
Visual Alerts: Bars turn lime green on breakout above the previous high and red on breakdown below the previous low.
Alert Conditions: Receive notifications when significant price movements occur.
日本語
Trend Finderは、指定した時間枠に基づいてブレイクアウトとブレイクダウンを識別するためのインジケーターです。前日の高値と安値を監視し、現在の終値がこれらのレベルを超えたときにバーの色を変更します。
特徴
カスタマイズ可能な時間枠 高値/安値と終値の解像度を設定可能。
視覚的アラート 前日の高値を超えるとバーがライムグリーンに、安値を下回ると赤に変化。
アラート条件 重要な価格変動時に通知を受け取れます。
Chart Example
Disclaimer
This indicator is for educational purposes only and should not be considered as financial advice. Always perform your own analysis before making trading decisions.
Breaks and Retests - Free990Strategy Description: "Breaks and Retests - Free990"
The "Breaks and Retests - Free990" strategy is based on identifying breakout and retest opportunities for potential entries in both long and short trades. The idea is to detect price breakouts above resistance levels or below support levels, and subsequently identify retests that confirm the breakout levels. The strategy offers an automated approach to enter trades after a breakout followed by a retest, which serves as a confirmation of trend continuation.
Key Components:
Support and Resistance Detection:
The strategy calculates pivot levels based on historical price movements to define support and resistance areas. A lookback range is used to determine these key levels.
Breakouts and Retests:
The system identifies when a breakout occurs above a resistance level or below a support level.
It then waits for a retest of the previously broken level as confirmation, which is often a better entry opportunity.
Trade Direction Selection:
Users can choose between "Long Only," "Short Only," or "Both" directions for trading based on their market view.
Stop Loss and Trailing Stop:
An initial stop loss is placed at a defined percentage away from the entry.
The trailing stop loss is activated after the position gains a specified percentage in profit.
Long Entry:
A long entry is triggered if the price breaks above a resistance level and subsequently retests that level successfully.
The entry condition checks if the breakout was confirmed and if a retest was valid.
The long entry is only executed if the user-selected direction is either "Long Only" or "Both."
Short Entry:
A short entry is triggered if the price breaks below a support level and subsequently retests that level.
The short entry is only executed if the user-selected direction is either "Short Only" or "Both."
sell_condition checks whether the support has been broken and whether the retest condition is valid.
An initial stop loss is placed when the trade is opened to limit the risk if the trade moves against the position.
The stop loss is calculated based on a user-defined percentage (stop_loss_percent) of the entry price.
pinescript
Copy code
stop_loss_price := strategy.position_avg_price * (1 - stop_loss_percent / 100)
For long positions, the stop loss is placed below the entry price.
For short positions, the stop loss is placed above the entry price.
Trailing Stop:
When a position achieves a certain profit threshold (profit_threshold_percent), the trailing stop mechanism is activated.
For long positions, the trailing stop follows the highest price reached, ensuring that some profit is locked in if the price reverses.
For short positions, the trailing stop follows the lowest price reached.
Code Logic for Trailing Stop:
Exit Execution:
The strategy exits the position when the price hits the calculated stop loss level.
This includes both the initial stop loss and the trailing stop that adjusts as the trade progresses.
Code Logic for Exit:
Summary:
Breaks and Retests - Free990 uses support and resistance levels to identify breakouts, followed by retests for confirmation.
Entry Points: Triggered when a breakout is confirmed and a retest occurs, for both long and short trades.
Exit Points:
Initial Stop Loss: Limits risk for both long and short trades.
Trailing Stop Loss: Locks in profits as the price moves in favor of the position.
This strategy aims to capture the momentum after breakouts and minimize losses through effective use of stop loss and trailing stops. It gives the flexibility of selecting trade direction and ensures trades are taken with confirmation through the retest, which helps to reduce false breakouts.
Original Code by @HoanGhetti
Dynamic Spot vs Perp Spread### **Description for TradingView Publication**
---
**Dynamic Spot vs Perp Spread**
(For USDT-Spot and USDT.P-Perp)
Summary of Usefulness:
This indicator is a valuable tool for traders who want to monitor and capitalize on the relationship between spot and perpetual futures (perp) prices. When the spot price exceeds the perp price, it's often a leading signal that the perp price will follow, creating potential trading opportunities. While this behavior doesn't happen every time, divergences between spot and perp prices can frequently signal significant market movements.
What it Does:
This indicator calculates and displays the price spread (percentage difference) between the spot price and perpetual futures (perp) price of a cryptocurrency asset. It dynamically adjusts to the instrument being viewed, ensuring that spot dominance (spot price higher) is plotted above the zero line and perp dominance (perp price higher) is plotted below the zero line. Additionally, the indicator accounts for symbols with multipliers (e.g., `1000SHIBUSDT.P`) to ensure accurate calculations.
Key features include:
- Automatic symbol detection and adjustment for Spot/Perp pairs.
- Dynamic handling of price multipliers for assets with prefixes like `1000`.
- Visualization of spread with a histogram and optional smoothing using an EMA (Exponential Moving Average).
- Configurable alerts for significant spread changes and spread flips.
- No repainting: the indicator uses the `barmerge.lookahead_off` setting to ensure stable, non-repainting values.
---
### **How to Use**
1. **Add the Indicator:**
- Search for "Dynamic Spot vs Perp Spread" in the TradingView Indicators library and add it to your chart.
2. **Understand the Visualization:**
- A positive spread (green histogram) indicates that the spot price is higher than the perp price (spot dominance).
- A negative spread (red histogram) indicates that the perp price is higher than the spot price (perp dominance).
3. **Customize Settings:**
- **EMA Length:** Use the input field to smooth the spread data over a chosen number of periods.
- **Alert Threshold:** Set a threshold to receive alerts when the spread exceeds a specific percentage.
4. **Receive Alerts:**
- Enable alerts for spread flips (when dominance shifts between spot and perp) or when the spread exceeds the defined threshold.
5. **Use Case Examples:**
- **Spot vs. Perp Arbitrage:** Traders can monitor significant deviations between spot and perp prices to identify potential arbitrage opportunities.
- **Market Sentiment Analysis:** Persistent spot dominance may indicate stronger buying interest in the spot market, while perp dominance may suggest futures market speculation.
---
### **Repainting Behavior**
This indicator **does not repaint** because it uses `barmerge.lookahead_off` for all calculations, ensuring that data from the comparison symbol (spot or perp) is locked to the currently completed candle. This means the values plotted and alerts triggered are reliable and do not change retrospectively.
Repainting occurs when an indicator uses future-looking or incomplete data for calculations. By design, this indicator avoids such practices, making it suitable for live trading and analysis.
---
Relative Strength vs SPX
This indicator calculates the ratio of the current chart's price to the S&P 500 Index (SPX), providing a measure of the stock's relative strength compared to the broader market.
Key Features:
Dynamic High/Low Detection: Highlights periods when the ratio makes a new high (green) or a new low (red) based on a user-defined lookback period.
Customizable Lookback: The lookback period for detecting highs and lows can be adjusted in the settings for tailored analysis.
Visual Overlay: The ratio is plotted in a separate pane, allowing easy comparison of relative strength trends.
This tool is useful for identifying stocks outperforming or underperforming the S&P 500 over specific timeframes.
Trend Speed Analyzer (Zeiierman)█ Overview
The Trend Speed Analyzer by Zeiierman is designed to measure the strength and speed of market trends, providing traders with actionable insights into momentum dynamics. By combining a dynamic moving average with wave and speed analysis, it visually highlights shifts in trend direction, market strength, and potential reversals. This tool is ideal for identifying breakout opportunities, gauging trend consistency, and understanding the dominance of bullish or bearish forces over various timeframes.
█ How It Works
The indicator employs a Dynamic Moving Average (DMA) enhanced with an Accelerator Factor, allowing it to adapt dynamically to market conditions. The DMA is responsive to price changes, making it suitable for both long-term trends and short-term momentum analysis.
Key components include:
Trend Speed Analysis: Measures the speed of market movements, highlighting momentum shifts with visual cues.
Wave Analysis: Tracks bullish and bearish wave sizes to determine market strength and bias.
Normalized Speed Values: Ensures consistency across different market conditions by adjusting for volatility.
⚪ Average Wave and Max Wave
These metrics analyze the size of bullish and bearish waves over a specified Lookback Period:
Average Wave: This represents the mean size of bullish and bearish movements, helping traders gauge overall market strength.
Max Wave: Highlights the largest movements within the period, identifying peak momentum during trend surges.
⚪ Current Wave Ratio
This feature compares the current wave's size against historical data:
Average Wave Ratio: Indicates if the current momentum exceeds historical averages. A value above 1 suggests the trend is gaining strength.
Max Wave Ratio: Shows whether the current wave surpasses previous peak movements, signaling potential breakouts or trend accelerations.
⚪ Dominance
Dominance metrics reveal whether bulls or bears have controlled the market during the Lookback Period:
Average Dominance: Compares the net difference between average bullish and bearish wave sizes.
Max Dominance: Highlights which side had the stronger individual waves, indicating key power shifts in market dynamics.
Positive values suggest bullish dominance, while negative values point to bearish control. This helps traders confirm trend direction or anticipate reversals.
█ How to Use
Identify Trends: Leverage the color-coded candlesticks and dynamic trend line to assess the overall market direction with clarity.
Monitor Momentum: Use the Trend Speed histogram to track changes in momentum, identifying periods of acceleration or deceleration.
Analyze Waves: Compare the sizes of bullish and bearish waves to identify the prevailing market bias and detect potential shifts in sentiment. Additionally, fluctuations in Current Wave ratio values should be monitored as early indicators of possible trend reversals.
Evaluate Dominance: Utilize dominance metrics to confirm the strength and direction of the current trend.
█ Settings
Maximum Length: Sets the smoothing of the trend line.
Accelerator Multiplier: Adjusts sensitivity to price changes.
Lookback Period: Defines the range for wave calculations.
Enable Table: Displays statistical metrics for in-depth analysis.
Enable Candles: Activates color-coded candlesticks.
Collection Period: Normalizes trend speed values for better accuracy.
Start Date: Limits calculations to a specific timeframe.
Timer Option: Choose between using all available data or starting from a custom date.
-----------------
Disclaimer
The information contained in my Scripts/Indicators/Ideas/Algos/Systems does not constitute financial advice or a solicitation to buy or sell any securities of any type. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
My Scripts/Indicators/Ideas/Algos/Systems are only for educational purposes!
Simplified Momentum ScoreIndicator Name: Simplified Momentum Score
Description:
The Simplified Momentum Score indicator calculates the normalized price momentum of an asset over a user-defined period (e.g., 30 days). It provides a single actionable score between 0 and 1, making it easy to compare the relative strength of different tokens or assets:
1: Strongest momentum (best performer).
0: Weakest momentum (worst performer).
How to Use:
Apply this indicator to any chart in TradingView.
Use the normalized score to rank tokens or assets:
Closer to 1: Indicates strong recent price performance.
Closer to 0: Indicates weak recent price performance.
Customize the momentum period to match your trading strategy.
This tool is ideal for quick comparative analysis of multiple tokens to identify top-performing assets. Keep it simple, actionable, and effective! 🚀
Relative Momentum StrengthThe Relative Momentum Strength (RMS) indicator is designed to help traders and investors identify tokens with the strongest momentum over two customizable timeframes. It calculates and plots the percentage price change over 30-day and 90-day periods (or user-defined periods) to evaluate a token's relative performance.
30-Day Momentum (Green Line): Short-term price momentum, highlighting recent trends and movements.
90-Day Momentum (Blue Line): Medium-term price momentum, providing insights into broader trends.
This tool is ideal for comparing multiple tokens or assets to identify those showing consistent strength or weakness. Use it to spot outperformers and potential reversals in a competitive universe of assets.
How to Use:
Apply this indicator to your TradingView chart for any token or asset.
Look for tokens with consistently high positive momentum for potential strength.
Use the plotted values to compare relative performance across your watchlist.
Customization:
Adjust the momentum periods to suit your trading strategy.
Overlay it with other indicators like RSI or volume for deeper analysis.
Potential Upcoming Trend ToolThis Script has the specific use of identifying when and how a new trend may start to take form, rather than focusing on how a trend has already formed on a longer term basis.
This Script is useful on it's own and not in conjunction with another. It works by taking on the most recent price data rather than a long term historical string.
It differs from standard trend following indicators because it's use is far less historical, and more present. It requires less pivot points than normal to be validated as a strong trend.
It works by taking local pivot points and fractals to form its parallel basis. The Trend lines will continually move as more recent price action data appears and the the channel will get thinner, until it is clear a trend has arrived and consolidated.
The idea really is to see a constantly evolving picture of a sudden change in movement, allowing you to have an earlier eye on what is potentially to come.
The faint mid-point line gives a reasonable reading of where you would find yourself halfway within a new trend and will also move inline with the shown trendlines.
This allows you to easily track when sentiment and therefore trends are about to change. It's much more useful on lower timeframes because they will often give the first indication something is changing.
Colours are fully customisable.
Support/Resistance Strength [UAlgo]The Support/Resistance Strength indicator is a tool designed for traders seeking a precise understanding of key support and resistance levels in the market. This tool dynamically identifies and visualizes support and resistance zones based on pivot points and strength criteria, providing traders with actionable insights for better decision-making.
By incorporating features such as ATR-based or percentage-based channel calculations, customizable strength thresholds, and intuitive visualization of key levels, the indicator caters to traders of various skill levels and strategies. It also adapts dynamically to market conditions, allowing users to identify frequently tested zones with minimal manual input.
🔶 Key Features
Dynamic Support and Resistance Zones
Automatically detects significant support and resistance levels using pivot high and low calculations.
Offers ATR-based or percentage-based channel customization to cater to diverse trading styles.
Customizable Parameters
Lookback period for pivot calculations, strength threshold, and maximum stored pivots are fully adjustable.
Display options for showing specific numbers of recent support/resistance lines.
Intuitive Visualization
Highlights key support and resistance levels with color-coded lines and labels.
Includes percentage deviation from the current price for quick assessment.
Interactive Updates
Continuously updates support and resistance levels to reflect changing market dynamics.
Displays pivot points visually for enhanced clarity.
Can be used effectively on various timeframes, from intraday to daily and weekly charts.
🔶 Interpreting the Indicator
Identifying Key Levels
Support levels are indicated by green (lime) lines and resistance levels by red lines. The transparency of colors is adjustable for visual preference.
Labels display the exact price level and the percentage difference from the current price.
Strength Threshold
The "Minimum S/R Strength" parameter defines how frequently a level must be tested to be considered significant.
Higher strength values indicate zones that have been tested more frequently, suggesting stronger support or resistance.
Pivot Points
The indicator marks pivot high and low points on the chart to provide a visual representation of the calculated levels.
Dynamic Updates
The indicator adapts to the most recent price action. If the price moves above a resistance level or below a support level, the color of the lines and labels will dynamically change to reflect the current price positioning.
🔶 Disclaimer
Use with Caution: This indicator is provided for educational and informational purposes only and should not be considered as financial advice. Users should exercise caution and perform their own analysis before making trading decisions based on the indicator's signals.
Not Financial Advice: The information provided by this indicator does not constitute financial advice, and the creator (UAlgo) shall not be held responsible for any trading losses incurred as a result of using this indicator.
Backtesting Recommended: Traders are encouraged to backtest the indicator thoroughly on historical data before using it in live trading to assess its performance and suitability for their trading strategies.
Risk Management: Trading involves inherent risks, and users should implement proper risk management strategies, including but not limited to stop-loss orders and position sizing, to mitigate potential losses.
No Guarantees: The accuracy and reliability of the indicator's signals cannot be guaranteed, as they are based on historical price data and past performance may not be indicative of future results.
Bitcoin Cycle High/Low with functional Alert [heswaikcrypt]Introduction
Just as machines are fine-tuned for maximum efficiency, trading indicators must evolve to meet the demands of ever-changing markets.
Credit goes to the initial author, @NoCreditsLeft I only improved the existing Pi-cycle indicator with a functional alert and included a bull mode indicator in the script. The alert can help you get a live alert at candle close when the cycle tops, bottoms, and the potential bull phase switch occurs.
Philip Swift’s Pi Cycle Top Indicator is a brilliant example of leveraging mathematical relationships to signal critical turning points in Bitcoin’s price cycles. Historically, it has identified market and local tops with some relative accuracy, often within three days, as demonstrated in all the previous bull run cycles.
At its core, the Pi Cycle Indicator derives its name from the mathematical constant π (pi), achieved by using simple moving averages (MAs) in a specific ratio: 𝜋 = Long MA/short MA
The Bull mode switch is calculated using a crossover of the short exponentia moving average and the long moving average.
.
.
.
Knowing when Bitcoin reaches its top—and receiving timely alerts about it—is crucial for successful trading. The indicator is designed to signal;
Potential Bitcoin tops: Purple label
Potential Bitcoin bottoms : green Label, and
Parabolic swing : Yellow diamond shape (relating to the market switching to a potential bull mode)
"Please note: This indicator is tailored for Bitcoin using historical data analysis and should not be considered definitive. However accurate it might be."
Setting alerts
To set the alert conditions, select any alert function call to get alert whenever the conditions are met. The script is configured on dialy TF; you can set it on 1D or weekly TF.
Enjoy and Trade smartly
Linear Regression Channel Screener [Daveatt]Hello traders
First and foremost, I want to extend a huge thank you to @LonesomeTheBlue for his exceptional Linear Regression Channel indicator that served as the foundation for this screener.
Original work can be found here:
Overview
This project demonstrates how to transform any open-source indicator into a powerful multi-asset screener.
The principles shown here can be applied to virtually any indicator you find interesting.
How to Transform an Indicator into a Screener
Step 1: Identify the Core Logic
First, identify the main calculations of the indicator.
In our case, it's the Linear Regression
Channel calculation:
get_channel(src, len) =>
mid = math.sum(src, len) / len
slope = ta.linreg(src, len, 0) - ta.linreg(src, len, 1)
intercept = mid - slope * math.floor(len / 2) + (1 - len % 2) / 2 * slope
endy = intercept + slope * (len - 1)
dev = 0.0
for x = 0 to len - 1 by 1
dev := dev + math.pow(src - (slope * (len - x) + intercept), 2)
dev
dev := math.sqrt(dev / len)
Step 2: Use request.security()
Pass the function to request.security() to analyze multiple assets:
= request.security(sym, timeframe.period, get_channel(src, len))
Step 3: Scale to Multiple Assets
PineScript allows up to 40 request.security() calls, letting you monitor up to 40 assets simultaneously.
Features of This Screener
The screener provides real-time trend detection for each monitored asset, giving you instant insights into market movements.
It displays each asset's position relative to its middle regression line, helping you understand price momentum.
The data is presented in a clean, organized table with color-coded trends for easy interpretation.
At its core, the screener performs trend detection based on regression slope calculations, clearly indicating whether an asset is in a bullish or bearish trend.
Each asset's price is tracked relative to its middle regression line, providing additional context about trend strength.
The color-coded visual feedback makes it easy to spot changes at a glance.
Built-in alerts notify you instantly when any asset experiences a trend change, ensuring you never miss important market moves.
Customization Tips
You can easily expand the screener by adding more symbols to the symbols array, adapting it to your watchlist.
The regression parameters can be adjusted to match your preferred trading timeframes and sensitivity.
The alert system is already configured to notify you of trend changes, but you can customize the alert messages and conditions to your needs.
Limitations
While powerful, the screener is bound by PineScript's limitation of 40 security calls, capping the maximum number of monitored assets.
Using AI to Help With Conversion
An interesting tip:
You can use AI tools to help convert single-asset indicators to screeners.
Simply provide the original code and ask for assistance in transforming it into a screener format. While the AI output might need some syntax adjustments, it can handle much of the heavy lifting in the conversion process.
Prompt (example) : " Please make a pinescript version 5 screener out of this indicator below or in attachment to scan 20 instruments "
I prefer Claude AI (Opus model) over ChatGPT for pinescript.
Conclusion
This screener transformation technique opens up endless possibilities for market analysis.
By following these steps, you can convert any indicator into a powerful multi-asset scanner, enhancing your trading toolkit significantly.
Remember: The power of a screener lies not just in monitoring multiple assets, but in applying consistent analysis across your entire watchlist in real-time.
Feel free to fork and modify this screener for your own needs.
Happy trading! 🚀📈
Daveatt
Double Top/Bottom [AlgoAlpha]Introducing the Double Top/Bottom Indicator by AlgoAlpha, a powerful tool designed to identify key reversal patterns in the market with precision. This indicator meticulously detects double tops and double bottoms, helping traders recognize potential trend reversals and make informed trading decisions.
Key Features:
🔍 Pattern Detection : Accurately identifies double top and double bottom formations based on customizable time horizons.
🎨 Customizable Appearance : Choose your preferred colors for bullish and bearish trends to match your trading style.
📊 Signal Labels : Option to display only the second pivot of the double top/bottom for a cleaner chart view.
🔧 Flexible Settings : Adjust the time horizon to control the look-back period, allowing for detection of both short-term and long-term patterns.
📈 Visual Enhancements : Draws trend lines and fills between pivotal points to visually highlight potential reversal zones.
🔔 Alerts : Set up alerts for potential double top and double bottom formations to stay informed of key market movements.
How to Use the Double Top/Bottom Indicator :
🛠 Add the Indicator : Simply add the Double Top/Bottom Indicator to your TradingView chart from your favorites. Customize the time horizon and appearance settings to fit your trading preferences.
📊 Analyze Patterns : Watch for the identified double top and double bottom patterns along with the corresponding trend lines and filled areas to anticipate potential market reversals.
🔔 Set Alerts : Enable alerts to receive notifications when double top or double bottom patterns are detected, ensuring you never miss a critical trading opportunity.
How It Works : The indicator scans the price action for pivot highs and lows within a specified time horizon, identifying potential double top and double bottom patterns. It maintains a sequence of these pivots and verifies the formation of these patterns based on the relationship between consecutive pivots and the proximity to a defined limit. When a double top or double bottom is confirmed, the indicator marks the second pivot point with a label and draws trend lines to visualize the reversal pattern. Additionally, it provides alert conditions to notify traders of potential confirmations, enhancing decision-making without cluttering the chart.
⚠️ Important Reminder : The labels indicating double tops and bottoms appear with a delay and are intended to mark the formations after they have already formed. They are not meant to be used as real-time trading signals. While they align perfectly with pivot points in hindsight, please use them as markers for analysis rather than immediate trading triggers.
Daily PlayDaily Play Indicator
The Daily Play Indicator is a clean and versatile tool designed to help traders organize and execute their daily trading plan directly on their charts. This indicator simplifies your workflow by visually displaying key inputs like market trend, directional bias, and key levels, making it easier to focus on your trading strategy.
Features
Dropdown Selection for Trend and Bias:
• Set the overall market trend (Bullish, Bearish, or Neutral) and your directional bias (Long, Short, or Neutral) using intuitive dropdown menus. No more manual typing or guesswork!
Key Levels:
Quickly input and display the Previous Day High and Previous Day Low. These levels are essential for many trading strategies, such as breakouts.
Real-Time News Notes:
Add a quick note about impactful news or market events (e.g., “Fed meeting today” or “Earnings season”) to keep contextual awareness while trading.
Simple On-Chart Display:
The indicator creates a “table-like” structure on the chart, aligning your inputs in an easy-to-read format. The data is positioned dynamically so it doesn’t obstruct the price action.
Customisable Visual Style:
Simple labels with clear text to ensure that your chart remains neat and tidy.
----
Use Case
The Daily Play Indicator is ideal for:
• Day traders and scalpers who rely on precise planning and real-time execution.
• Swing traders looking to mark critical levels and develop a trade plan before the session begins.
• Anyone who needs a structured way to stay focused and disciplined during volatile market conditions.
By integrating this tool into your workflow, you can easily align your daily preparation with live market action.
----
How to Use
Open the indicator settings to configure your inputs:
• Trend: Use the dropdown to choose between Bullish, Bearish, or Neutral.
• Bias: Select Long, Short, or Neutral to align your personal bias with the market.
• Previous Day Levels: Enter the High and Low of the previous trading session for key reference points.
• News: Add a short description of any relevant market-moving events.
Accumulation Momentum IndicatorEveryone wants to be in a trend, I think this indicator does a great job at showing that key momentum that traders try and capitalize on everyday. I used a Stochastic Momentum Indicator (SMI) indicator. It's a lot like a slower MACD which allows me to capitalize on changing momentum. My goal was to make an indicator that was able to use a weighted mean of many accumulation/momentum indicators. This would give me a well rounded look to really see what direction the momentum and volume is heading.
I did some research on some of the best Accumulation and Momentum Indicators. I landed on 4.
The Accumulation Distribution line which measures the cumulative flow of money in or out of a security. It helps show how quickly money is going in and out of a commodity. The line moving up quickly indicates fast Accumulation while the A/C line is moving down quickly is shows falling Distribution. This can show the momentum and accumulation of a commodity in short and long term based off of Volume.
The On Balance Volume, OBV is a combination of Price Movement and Volume. If price closes higher then the previous bar volume is added while if the price closes lower volume is subtracted. This gives us an overall tally of whether volume is increasing with price or slowing down the momentum in the direction of the current trend. This gives us the ability to see if volume is supporting the price increasing (beginning/middle of a trend) or price is slowing down even though it is still heading in the direction of the current trend (signaling the end of the current trend).
The Force Index, this indicator measures the overall strength of the price movements. It does this by a calculation of price and volume. The close of the current bar subtracted by the previous multiplied by the volume. The result gives us either strong upward or downward motion. This adds magnitude to the overall movement/momentum of the indicator.
Lastly but most certainly not least is the Momentum indicator, (Price Momentum) a simple indicator that shows you the difference between the current close price and the close price from a specified period ago (Most commonly 14 periods/bars ago). Having this indicator is a must because it shows the speed at which price is accelerating or decelerating.
These 4 indicators together help round out the current volume, price movements, accumulation, and momentum of the current market. Since these indicators all have different scales and calculations I had to Normalize the Values to a 0-100 scale. This gives us 1 line and a much more readable easy to understand indicator. After they were normalized I gave them a weighted average that you can control. So lets say you cared more about the Force Index and the OBV rather then the Momentum and the Accumulation Distribution indicators, you would be able to give them more weight in the overall calculation as well as 0 out those you don't even want involved.
I hope the flexibility and the combination of 4 strong Accumulation Momentum indicators helps you better gauge the direction a commodity might head. The way it's used is when the Accumulation Momentum line is Above 50 buying pressure is stronger then selling pressure. An Accumulation Momentum line Below 50 suggests that distribution is more dominant in the current market. This indicator combines four different methods of analyzing price and volume to give you a single composite momentum score, making it easier to visualize when a commodity is being accumulated or distributed and how quickly this process is happening. It helps you track market sentiment based on both price movement and volume, with a clear, visual representation of buying and selling pressure.
Please let me know what you think and how you think I might be able to improve the script. Enjoy!
Stock vs Sector Comparison with HighlightsThis graph is meant as a support to select a stock that is expected to perform better than the sector.
The graph is based on weekly chart. So this is a medium / long term strategy.
How is expected to be used: when the stock has under performed the sector for some time, there is a natural tendence that it will catch up with the sector again. So, for example, if the color change from green to red, you should consider find another stock in the sector. If the stock looses the green color, but is not red yet, you should wait. And vice versa if you start with red. However, life is not that simple, as you can get fake signal. To mitigate this problem, you can adjust the threshold in the input setting, so just go for the signal after x weeks over/underperforming. You also need remember to select the sector in the settings, as the sector is not give automatically when you select the stock.
Below the sectors used:
Sector Name Ticker
S&P 500 (Market Index) SPY
Technology XLK
Financials XLF
Consumer Discretionary XLY
Industrials XLI
Health Care XLV
Consumer Staples XLP
Energy XLE
Utilities XLU
Communication Services XLC
Real Estate XLRE
Materials XLB
MadTrend [InvestorUnknown]The MadTrend indicator is an experimental tool that combines the Median and Median Absolute Deviation (MAD) to generate signals, much like the popular Supertrend indicator. In addition to identifying Long and Short positions, MadTrend introduces RISK-ON and RISK-OFF states for each trade direction, providing traders with nuanced insights into market conditions.
Core Concepts
Median and Median Absolute Deviation (MAD)
Median: The middle value in a sorted list of numbers, offering a robust measure of central tendency less affected by outliers.
Median Absolute Deviation (MAD): Measures the average distance between each data point and the median, providing a robust estimation of volatility.
Supertrend-like Functionality
MadTrend utilizes the median and MAD in a manner similar to how Supertrend uses averages and volatility measures to determine trend direction and potential reversal points.
RISK-ON and RISK-OFF States
RISK-ON: Indicates favorable conditions for entering or holding a position in the current trend direction.
RISK-OFF: Suggests caution, signaling RISK-ON end and potential trend weakening or reversal.
Calculating MAD
The mad function calculates the median of the absolute deviations from the median, providing a robust measure of volatility.
// Function to calculate the Median Absolute Deviation (MAD)
mad(series float src, simple int length) =>
med = ta.median(src, length) // Calculate median
abs_deviations = math.abs(src - med) // Calculate absolute deviations from median
ta.median(abs_deviations, length) // Return the median of the absolute deviations
MADTrend Function
The MADTrend function calculates the median and MAD-based upper (med_p) and lower (med_m) bands. It determines the trend direction based on price crossing these bands.
MADTrend(series float src, simple int length, simple float mad_mult) =>
// Calculate MAD (volatility measure)
mad_value = mad(close, length)
// Calculate the MAD-based moving average by scaling the price data with MAD
median = ta.median(close, length)
med_p = median + (mad_value * mad_mult)
med_m = median - (mad_value * mad_mult)
var direction = 0
if ta.crossover(src, med_p)
direction := 1
else if ta.crossunder(src, med_m)
direction := -1
Trend Direction and Signals
Long Position (direction = 1): When the price crosses above the upper MAD band (med_p).
Short Position (direction = -1): When the price crosses below the lower MAD band (med_m).
RISK-ON: When the price moves further in the direction of the trend (beyond median +- MAD) after the initial signal.
RISK-OFF: When the price retraces towards the median, signaling potential weakening of the trend.
RISK-ON and RISK-OFF States
RISK-ON LONG: Price moves above the upper band after a Long signal, indicating strengthening bullish momentum.
RISK-OFF LONG: Price falls back below the upper band, suggesting potential weakness in the bullish trend.
RISK-ON SHORT: Price moves below the lower band after a Short signal, indicating strengthening bearish momentum.
RISK-OFF SHORT: Price rises back above the lower band, suggesting potential weakness in the bearish trend.
Picture below show example RISK-ON periods which can be identified by “cloud”
Note: Highlighted areas on the chart indicating RISK-ON and RISK-OFF periods for both Long and Short positions.
Implementation Details
Inputs and Parameters:
Source (input_src): The price data used for calculations (e.g., close, open, high, low).
Median Length (length): The number of periods over which the median and MAD are calculated.
MAD Multiplier (mad_mult): Determines the distance of the upper and lower bands from the median.
Calculations:
Median and MAD are recalculated each period based on the specified length.
Upper (med_p) and Lower (med_m) Bands are computed by adding and subtracting the scaled MAD from the median.
Visual representation of the indicator on a price chart:
Backtesting and Performance Metrics
The MadTrend indicator includes a Backtesting Mode with a performance metrics table to evaluate its effectiveness compared to a simple buy-and-hold strategy.
Equity Calculation:
Calculates the equity curve based on the signals generated by the indicator.
Performance Metrics:
Metrics such as Mean Returns, Standard Deviation, Sharpe Ratio, Sortino Ratio, and Omega Ratio are computed.
The metrics are displayed in a table for both the strategy and the buy-and-hold approach.
Note: Due to the use of labels and plot shapes, automatic chart scaling may not function ideally in Backtest Mode.
Alerts and Notifications
MadTrend provides alert conditions to notify traders of significant events:
Trend Change Alerts
RISK-ON and RISK-OFF Alerts - Provides real-time notifications about the RISK-ON and RISK-OFF states for proactive trade management.
Customization and Calibration
Default Settings: The provided default settings are experimental and not optimized. They serve as a starting point for users.
Parameter Adjustment: Traders are encouraged to calibrate the indicator's parameters (e.g., length, mad_mult) to suit their specific trading style and the characteristics of the asset being analyzed.
Source Input: The indicator allows for different price inputs (open, high, low, close, etc.), offering flexibility in how the median and MAD are calculated.
Important Notes
Market Conditions: The effectiveness of the MadTrend indicator can vary across different market conditions. Regular calibration is recommended.
Backtest Limitations: Backtesting results are historical and do not guarantee future performance.
Risk Management: Always apply sound risk management practices when using any trading indicator.