KalmanfilterLibrary "Kalmanfilter"
A sophisticated Kalman Filter implementation for financial time series analysis
@author Rocky-Studio
@version 1.0
initialize(initial_value, process_noise, measurement_noise)
Initializes Kalman Filter parameters
Parameters:
initial_value (float) : (float) The initial state estimate
process_noise (float) : (float) The process noise coefficient (Q)
measurement_noise (float) : (float) The measurement noise coefficient (R)
Returns: A tuple containing
update(prev_state, prev_covariance, measurement, process_noise, measurement_noise)
Update Kalman Filter state
Parameters:
prev_state (float)
prev_covariance (float)
measurement (float)
process_noise (float)
measurement_noise (float)
calculate_measurement_noise(price_series, length)
Adaptive measurement noise calculation
Parameters:
price_series (array)
length (int)
calculate_measurement_noise_simple(price_series)
Parameters:
price_series (array)
update_trading(prev_state, prev_velocity, prev_covariance, measurement, volatility_window)
Enhanced trading update with velocity
Parameters:
prev_state (float)
prev_velocity (float)
prev_covariance (float)
measurement (float)
volatility_window (int)
model4_update(prev_mean, prev_speed, prev_covariance, price, process_noise, measurement_noise)
Kalman Filter Model 4 implementation (Benhamou 2018)
Parameters:
prev_mean (float)
prev_speed (float)
prev_covariance (array)
price (float)
process_noise (array)
measurement_noise (float)
model4_initialize(initial_price)
Initialize Model 4 parameters
Parameters:
initial_price (float)
model4_default_process_noise()
Create default process noise matrix for Model 4
model4_calculate_measurement_noise(price_series, length)
Adaptive measurement noise calculation for Model 4
Parameters:
price_series (array)
length (int)
Indicadores e estratégias
Daily COC Strategy with SHERLOCK WAVESThis indicator implements a unique trading strategy known as the "Daily COC (Candle Over Candle) Strategy" enhanced with "SHERLOCK WAVES" for pattern recognition. It's designed for traders looking to capitalize on specific candlestick formations with a negative risk-reward ratio, with the aim of achieving a high win rate (over 70%) through numerous trading opportunities, despite each trade having a higher risk relative to the reward.
Key Features:
Pattern Recognition: Identifies a setup based on three consecutive candles - a red candle followed by a shooting star, then an entry candle that does not break below the shooting star's low.
Negative Risk/Reward Trade Selection: Focuses on entries where the potential stop loss is greater than the take profit, banking on a high win rate to offset the individual trade's negative risk-reward ratio.
Visual Signals:
Green Label: Marks potential entry points at the high of the candle before the entry.
Green Dot: Indicates a winning trade closure.
Red Dot: Signals a losing trade closure.
Blue Circle: Warns when the current candle is within 2% of breaking above the previous candle's high, suggesting a potential setup is developing.
Green Circle: Plots the take profit level.
Red Circle: Plots the stop loss level.
Dynamic Statistics: A live updating label showing the number of trades, wins, losses, open trades, current account balance, and win percentage.
Customizable Parameters:
Risk % per Trade: Adjust the percentage of your account balance you're willing to risk on each trade.
Initial Account Balance: Set your starting balance for tracking performance.
Start Date for Strategy: Define when the strategy should start calculating from, allowing for backtesting.
Alerts:
An alert condition is set for when a potential trade setup is developing, helping traders prepare for entries.
Usage Tips:
This strategy is predicated on the idea that a high win rate can compensate for the negative risk-reward ratio of individual trades. It might not suit all market conditions or traders' risk profiles.
Use this strategy in conjunction with other analysis methods to validate trade setups.
Note: Always backtest thoroughly before applying to live markets. Consider this tool as part of a broader trading strategy, not a standalone solution. Monitor your win rate and adjust your risk management accordingly to ensure the strategy remains profitable over time.
This description now correctly explains the purpose behind the negative risk-reward ratio in the context of your trading strategy.
Dow Theory Swing Trading-DexterThis Pine Script strategy that implements a basic price action-based trading system inspired by Dow Theory, focusing on swing highs and swing lows. This strategy will generate buy and sell signals based on the formation of higher highs (HH) and higher lows (HL) for an uptrend, and lower highs (LH) and lower lows (LL) for a downtrend.
Swing Highs and Swing Lows:
The script identifies swing highs and swing lows using the ta.highest and ta.lowest functions over a specified lookback period.
A swing high is identified when the high of the current bar is the highest high over the lookback period.
A swing low is identified when the low of the current bar is the lowest low over the lookback period.
Trend Detection:
An uptrend is detected when the current low is higher than the last identified swing low.
A downtrend is detected when the current high is lower than the last identified swing high.
Buy and Sell Signals:
A buy signal is generated when the price closes above the last swing high during an uptrend.
A sell signal is generated when the price closes below the last swing low during a downtrend.
Plotting:
Swing highs and swing lows are plotted on the chart using plotshape.
Buy and sell signals are also plotted on the chart for visual reference.
How to Use:
Copy and paste the script into the Pine Script editor in TradingView.
Adjust the lookback period as needed to suit your trading style and timeframe.
Apply the script to your chart and it will generate buy and sell signals based on the price action.
NOTE: Please uncheck the all the unwanted symbol from chart for clear view .
Global M2 Index Percentage### **Global M2 Index Percentage**
**Description:**
The **Global M2 Index Percentage** is a custom indicator designed to track and visualize the global money supply (M2) in a normalized percentage format. It aggregates M2 data from major economies (e.g., the US, EU, China, Japan, and the UK) and adjusts for exchange rates to provide a comprehensive view of global liquidity. This indicator helps traders and investors understand the broader macroeconomic environment, identify trends in money supply, and make informed decisions based on global liquidity conditions.
---
### **How It Works:**
1. **Data Aggregation**:
- The indicator collects M2 data from key economies and adjusts it using exchange rates to calculate a global M2 value.
- The formula for global M2 is:
\
2. **Normalization**:
- The global M2 value is normalized into a percentage (0% to 100%) based on its range over a user-defined period (default: 13 weeks).
- The formula for normalization is:
\
3. **Visualization**:
- The indicator plots the M2 Index as a line chart.
- Key reference levels are highlighted:
- **10% (Red Line)**: Oversold level (low liquidity).
- **50% (Black Line)**: Neutral level.
- **80% (Green Line)**: Overbought level (high liquidity).
---
### **How to Use the Indicator:**
#### **1. Understanding the M2 Index:**
- **Below 10%**: Indicates extremely low liquidity, which may signal economic contraction or tight monetary policy.
- **Above 80%**: Indicates high liquidity, which may signal loose monetary policy or potential inflationary pressures.
- **Between 10% and 80%**: Represents a neutral to moderate liquidity environment.
#### **2. Trading Strategies:**
- **Long-Term Investing**:
- Use the M2 Index to assess global liquidity trends.
- **High M2 Index (e.g., >80%)**: Consider investing in risk assets (stocks, commodities) as liquidity supports growth.
- **Low M2 Index (e.g., <10%)**: Shift to defensive assets (bonds, gold) as liquidity tightens.
- **Short-Term Trading**:
- Combine the M2 Index with technical indicators (e.g., RSI, MACD) for timing entries and exits.
- **M2 Index Rising + RSI Oversold**: Potential buying opportunity.
- **M2 Index Falling + RSI Overbought**: Potential selling opportunity.
#### **3. Macroeconomic Analysis**:
- Use the M2 Index to monitor the impact of central bank policies (e.g., quantitative easing, rate hikes).
- Correlate the M2 Index with inflation data (CPI, PPI) to anticipate inflationary or deflationary trends.
---
### **Key Features:**
- **Customizable Timeframe**: Adjust the lookback period (e.g., 13 weeks, 26 weeks) to suit your trading style.
- **Multi-Economy Data**: Aggregates M2 data from the US, EU, China, Japan, and the UK for a global perspective.
- **Normalized Output**: Converts raw M2 data into an easy-to-interpret percentage format.
- **Reference Levels**: Includes key levels (10%, 50%, 80%) for quick analysis.
---
### **Example Use Case:**
- **Scenario**: The M2 Index rises from 49% to 62% over two weeks.
- **Interpretation**: Global liquidity is increasing, potentially due to central bank stimulus.
- **Action**:
- **Long-Term**: Increase exposure to equities and commodities.
- **Short-Term**: Look for buying opportunities in oversold assets (e.g., RSI < 30).
---
### **Why Use the Global M2 Index Percentage?**
- **Macro Insights**: Understand the broader economic environment and its impact on financial markets.
- **Risk Management**: Identify periods of high or low liquidity to adjust your portfolio accordingly.
- **Enhanced Timing**: Combine with technical analysis for better entry and exit points.
---
### **Conclusion:**
The **Global M2 Index Percentage** is a powerful tool for traders and investors seeking to incorporate macroeconomic data into their strategies. By tracking global liquidity trends, this indicator helps you make informed decisions, whether you're trading short-term or planning long-term investments. Add it to your TradingView charts today and gain a deeper understanding of the global money supply!
---
**Disclaimer**: This indicator is for informational purposes only and should not be considered financial advice. Always conduct your own research and consult with a professional before making investment decisions.
On Balance Volume with Cross DetectionThis indicator enhances the On Balance Volume (OBV) indicator by detecting and visually highlighting crossovers and crossunders between the OBV and its smoothed moving average. The script colors the background of the chart to make these key events more noticeable: red highlights a bearish crossunder when the OBV crosses below the smoothed OBV, while green marks a bullish crossover when the OBV crosses above the smoothed OBV. By focusing on these significant interactions, the script provides traders with a clear visual cue to help identify potential buying and selling opportunities based on the relationship between OBV and its smoothed trend.
This script offers several customizable features to suit different trading preferences. The main editable parameter is the type of moving average used to smooth the OBV: you can choose from options such as Simple Moving Average (SMA), Exponential Moving Average (EMA), Smoothed Moving Average (RMA), Weighted Moving Average (WMA), or Volume Weighted Moving Average (VWMA). The length of the moving average can also be adjusted to better match the trader’s desired sensitivity, with the default set to 14 periods. These options allow traders to tailor the script to their preferred smoothing method and time frame, making it a flexible tool for a variety of strategies. The ability to switch between different moving averages and adjust their lengths ensures that the script can be adapted to various market conditions and trading styles.
This indicator enhances the analysis of the On Balance Volume (OBV) indicator by visually highlighting key crossovers and crossunders with its smoothed moving average. With customizable settings for different moving averages and lengths, traders can tailor the script to their specific strategies. By offering clear visual cues through background coloring, it helps quickly identify potential buy and sell signals. When combined with other technical analysis tools, this script can further improve trading decisions by providing additional context and confirmation, allowing traders to create a more robust and comprehensive trading strategy.
Binance Pseudo Funding FeeThe indicator calculates the Funding Fee for Binance based on the Premium Index provided by TradingView. The calculation formula can be found here: Binance Funding Rate Introduction . This is NOT the official rate visible on binance.com and used for settlements, but rather an estimated rate, which is inherently INACCURATE . The accuracy of the calculation heavily depends on the timeframe, with almost perfect results on minute-based timeframes.
For the most accurate calculations, you need to visit Binance Funding History and fill in the corresponding Interval , Interest Rate , and Funding Cap/Floor settings for the specific symbol in the indicator's settings. I understand this is not convenient, but for now, this is how it works.
The blue bars indicate the settlement time. Funding can be smoothed using moving averages. Both the funding rate and the moving averages are displayed using plot and are labeled, so you can set alerts on them.
Displaced MAsDisplaced Moving Averages with Customizable Bands
Overview
The "Displaced Moving Averages with Customizable Bands" indicator is a powerful and versatile tool designed to provide a comprehensive view of price action in relation to various moving averages (MAs) and their volatility. It offers a high degree of customization, allowing traders to tailor the indicator to their specific needs and trading styles. The indicator features a primary moving average with multiple configurable percentage-based displacement bands. It also includes additional moving averages with standard deviation bands for a more in-depth analysis of different timeframes.
Key Features
Multiple Moving Average Types:
Choose from a wide range of popular moving average types for the primary MA calculation:
WMA (Weighted Moving Average)
EMA (Exponential Moving Average)
SMA (Simple Moving Average)
HMA (Hull Moving Average)
VWAP (Volume-Weighted Average Price)
Smoothed VWAP
Rolling VWAP
The flexibility to select the most appropriate MA type allows you to adapt the indicator to different market conditions and trading strategies.
Smoothed VWAP with Customizable Smoothing:
When "Smoothed VWAP" is selected, you can further refine it by choosing a smoothing type: SMA, EMA, WMA, or HMA.
Customize the smoothing period based on the chart's timeframe (1H, 4H, D, W) or use a default period. This feature offers fine-grained control over the responsiveness of the VWAP calculation.
Rolling VWAP with Adjustable Lookback:
The "Rolling VWAP" option calculates the VWAP over a user-defined lookback period.
Customize the lookback length for different timeframes (1H, 4H, D, W) or use a default period. This provides a dynamic VWAP calculation that adapts to the chosen timeframe.
Customizable Lookback Lengths:
Define the lookback period for the primary moving average calculation.
Tailor the lookback lengths for different timeframes (1H, 4H, D, W) or use a default value.
This allows you to adjust the sensitivity of the MA to recent price action based on the timeframe you are analyzing. Also has inputs for 5m, and 15m timeframes.
Percentage-Based Displacement Bands:
The core feature of this indicator is the ability to plot multiple displacement bands above and below the primary moving average.
These bands are calculated as a percentage offset from the MA, providing a clear visualization of price deviations.
Visibility Toggles: Independently show or hide each band (+/- 2%, 5%, 7%, 10%, 15%, 20%, 25%, 30%, 40%, 50%, 60%, 70%).
Customizable Colors: Assign unique colors to each band for easy visual identification.
Adjustable Multipliers: Fine-tune the percentage displacement for each band using individual multiplier inputs.
The bands are useful for identifying potential support and resistance levels, overbought/oversold conditions, and volatility expansions/contractions.
Labels for Displacement Bands:
The indicator displays labels next to each plotted band, clearly indicating the percentage displacement (e.g., "+7%", "-15%").
Customize the label text color for optimal visibility.
The labels can be horizontally offset by a user-defined number of bars.
Additional Moving Averages with Standard Deviation Bands:
The indicator includes three additional moving averages, each with upper and lower standard deviation bands. These are designed to provide insights into volatility on different timeframes.
Timeframe Selection: Choose the timeframes for these additional MAs (e.g., Weekly, 4-Hour, Daily).
Sigma (Standard Deviation Multiplier): Adjust the standard deviation multiplier for each MA.
MA Length: Set the lookback period for each additional MA.
Visibility Toggles: Show or hide the lower band of MA1, the middle/upper/lower bands of MA2, and the bands of MA3.
4h Bollinger Middle MA is unticked by default to provide a less cluttered chart
These additional MAs are particularly useful for multi-timeframe analysis and identifying potential trend reversals or volatility shifts.
How to Use
Add the indicator to your TradingView chart.
Customize the settings:
Select the desired Moving Average Type for the primary MA.
If using Smoothed VWAP, choose the Smoothing Type and adjust the Smoothing Period for different timeframes.
If using Rolling VWAP, adjust the Lookback Length for different timeframes.
Set the Lookback Length for the primary MA for different timeframes.
Toggle the visibility of the Displacement Bands and adjust their Colors and Multipliers.
Customize the Label Text Color and Offset.
Configure the Timeframes, Sigma, and MA Length for the additional moving averages.
Toggle the visibility of the additional MA bands.
Interpret the plotted lines and bands:
Primary MA: Represents the average price over the selected lookback period, calculated using the chosen MA type.
Displacement Bands: Indicate potential support and resistance levels, overbought/oversold conditions, and volatility ranges. Price trading outside these bands may signal significant deviations from the average.
Additional MAs with Standard Deviation Bands: Provide insights into volatility on different timeframes. Wider bands suggest higher volatility, while narrower bands indicate lower volatility.
Potential Trading Applications
Trend Identification: Use the primary MA to identify the overall trend direction.
Support and Resistance: The displacement bands can act as dynamic support and resistance levels.
Overbought/Oversold: Price reaching the outer displacement bands may suggest overbought or oversold conditions, potentially indicating a pullback or reversal.
Volatility Analysis: The standard deviation bands of the additional MAs can help assess volatility on different timeframes.
Multi-Timeframe Analysis: Combine the primary MA with the additional MAs to gain a broader perspective on price action across multiple timeframes.
Entry and Exit Signals: Use the interaction of price with the MA and bands to generate potential entry and exit signals. For example, a bounce off a lower band could be a buy signal, while a rejection from an upper band could be a sell signal.
Disclaimer
This indicator is for informational and educational purposes only and should not be considered financial advice. Trading involves risk, and past performance is not indicative of future results. Always conduct thorough research and consider your risk tolerance before making any trading decisions.
Enjoy using the "Displaced Moving Averages with Customizable Bands" indicator!
Higher Timeframe SeparatorThis script helps visually identify when a higher timeframe candle starts by drawing a vertical line. It also shades the area above or below the opening price, making it easier to track price movement relative to the higher timeframe.
Why It's Useful
If you use multiple timeframes, this indicator provides a clear visual reference for where the price is relative to the higher timeframe. This is much more convenient than constantly switching between charts. You can see in the screenshot below how much clearer the price action becomes when the indicator is enabled:
Additional Benefit
If you trade on a lower timeframe and notice that the number of bars between separators is inconsistent, it means there weren’t enough trades during that period—indicating low liquidity. Illiquid instruments can be riskier to trade. For example, observe how the vertical lines on the left side of the image below are densely packed:
HTC peppermint_07 CCI w signal + s&r RSI
This CCI version enhances the traditional Commodity Channel Index (CCI) by integrating a dynamically calculated Relative Strength Index (RSI) that acts as support and resistance as shown in the screenshot, it can add as a confirmation to the divergence found in the CCI.
Key Features:
Enhanced CCI: The primary plot (black line but customizable) represents the standard CCI, providing insight into price momentum and potential overbought/oversold conditions.
Dynamic RSI Support/Resistance: The upper and lower bands (medium cyan line) are derived from a smoothed RSI, dynamically adjusting to the current market volatility. These bands serve as potential support and resistance levels for the CCI as additional confirmation for the divergence.
Overbought/Oversold Zones: The traditional overbought (+100) and oversold (-100) levels for CCI are marked with horizontal dotted lines.
Benefits:
Improved Entry/Exit Signals: Combining CCI with dynamic RSI support/resistance may offer more precise trading signals compared to using CCI alone.
Dynamic Adaptation: The RSI-based bands adapt to changing market conditions, potentially providing more relevant support and resistance levels.
Divergence Confirmation: dynamic s&r RSI adds confluence to potential trend reversals identified by the CCI.
Potential Usage:
Traders might use this indicator to:
Identify potential overbought/oversold conditions using the CCI and its relationship to the dynamic RSI bands.
Look for breakouts beyond the dynamic support/resistance levels as potential entry points.
Confirm potential trend reversals using RSI divergence (cyan and red label above divergence) signals.
Further Development Considerations:
Customizable Parameters: Allowing users to adjust the CCI length, RSI periods, and smoothing factors would enhance flexibility.
Alert Conditions: Adding alerts for breakouts, overbought/oversold conditions, and divergence signals would improve usability.
Backtesting: Thoroughly backtesting the indicator's performance across different assets and timeframes is essential before using it for live trading.
DISCLAIMER: !!
indicator is a custom technical analysis tool designed for educational and informational purposes only. It should not be construed as financial advice or a recommendation to buy or sell any security. Trading involves substantial risk of loss and may not be suitable for all investors.
Key Points to Consider:
No Guarantee of Profitability: The indicator's past performance is not indicative of future results. No trading strategy can guarantee profits or eliminate the risk of losses. You could lose some or all of your investment.
Use at Your Own Risk: Use of this indicator is solely at your own discretion and risk. You are responsible for your trading decisions. The developers and distributors of this indicator are not liable for any losses incurred as a result of using it.
Not Financial Advice: This indicator does not provide financial advice. Consult with a qualified financial advisor before making any investment decisions.
Backtesting Limitations: Backtested results, if presented, should be viewed with caution. Past performance may not reflect future results due to various factors, including changing market conditions and the limitations of backtesting methodologies.
Indicator Limitations: Technical indicators, including this one, are not perfect. They can generate false signals, and their effectiveness can vary depending on market conditions and the specific parameters used.
Parameter Optimization: Optimizing indicator parameters for past performance can lead to overfitting, which may not translate to future profitability.
No Warranty: The indicator is provided "as is" without any warranty of any kind, either express or implied, including but not limited to warranties of merchantability, fitness for a particular purpose, or non-infringement.
Changes and Updates: The developers may make changes or updates to the indicator without notice.
By using the "HTC peppermint_07 CCI w signal + s&r RSI" indicator, you acknowledge and agree to the terms of this disclaimer. If you do not agree with these terms, do not use the indicator.
RoGr75 - EMA Cross Signal with Buffer and Variable Distance**Overview**:
This script is designed to identify potential buy and sell signals based on the crossover of two Exponential Moving Averages (EMAs) – a short-term EMA (default: 8 periods) and a long-term EMA (default: 50 periods). To reduce noise and false signals, the script incorporates a customizable buffer percentage, ensuring that signals are only generated when the short-term EMA moves significantly above or below the long-term EMA. Additionally, the script allows users to adjust the distance of the signals from the candles using the Average True Range (ATR) for better visualization.
---
Improvements: Added Buffer Percentage for reduced noise in Signals
### **Key Features**:
1. **EMA Crossover Signals**:
Buy Signal: Generated when the short-term EMA crosses above the long-term EMA.
Sell Signal: Generated when the short-term EMA crosses below the long-term EMA.
2. **Buffer Percentage**:
A user-defined buffer percentage ensures that signals are only triggered when the short-term EMA moves a specified percentage above or below the long-term EMA, reducing false signals.
3. **Customizable Signal Distance**:
Signals are plotted at a user-defined distance from the candles, calculated using the ATR (Average True Range) for dynamic positioning.
4. **Visual Enhancements**:
Buy and sell signals are displayed as labels above or below the candles, with optional background highlighting for better visibility.
5. **Flexible Inputs**:
Users can customize the lengths of the short-term and long-term EMAs, the ATR period, the signal distance multiplier, and the buffer percentage.
6. **Alerts**:
Built-in alert conditions allow users to receive real-time notifications for buy and sell signals.
### **Input Parameters**:
**Short EMA Length**: Period for the short-term EMA (default: 8).
**Long EMA Length**: Period for the long-term EMA (default: 50).
**Signal Distance**: Multiplier for ATR to determine the distance of signals from the candles (default: 2.0).
**ATR Length**: Period for the ATR calculation (default: 14).
**Buffer Percentage**: Percentage buffer for reversal signals to reduce noise (default: 1.0%).
### **Ideal For**:
Traders who use EMA crossovers as part of their strategy.
Those looking to reduce false signals with a buffer mechanism.
Users who prefer dynamic signal positioning based on market volatility (ATR).
### **Notes**:
The buffer percentage ensures that signals are only generated when the price moves significantly, making it suitable for trend-following strategies.
The script is highly customizable, allowing traders to adapt it to different timeframes and instruments.
Micha Stocks Custom WatermarkThis Pine Script v5 indicator adds a customizable watermark to TradingView charts, displaying key stock information while allowing for flexible positioning and formatting.
📌 Features & Functionality:
✅ Custom Positioning:
• Fixed to the top-left corner.
• Adjustable spacing ensures the text is properly aligned.
✅ Displayed Information (Configurable):
• Company Name & Market Cap (Optional: Shows dynamically calculated market cap)
• Stock Ticker & Timeframe
• Industry & Sector
✅ Customization Options:
• Font Size: Huge, Large, Normal, Small
• Text Color & Transparency: Adjustable
• Proper Left Alignment for a clean, structured display
• Vertical Offset Tweaks to move text down for better visibility
✅ Optimized Table Layout:
• Uses table.new() for persistent placement.
• Added an empty row to fine-tune positioning, ensuring the watermark doesn’t overlap key chart areas.
🔧 Use Case:
Designed for traders who want a clear, customizable stock watermark to enhance their charting experience without obstructing price action.
Support and Resistancelookback: This input allows you to specify the number of bars to look back to calculate the support and resistance levels.
support: This is calculated as the lowest low over the specified lookback period.
resistance: This is calculated as the highest high over the specified lookback period.
plot: The support and resistance levels are plotted on the chart with different colors.
bgcolor: This optional feature highlights the support and resistance zones with a semi-transparent background color.
MA Win RateMoving Average Cross Win Rate
This simple yet useful script calculates the percentage of times a moving average crossover successfully predicts price movement.
Win Conditions:
1] A Golden Cross (fast MA crossing above slow MA) where the price moves up afterward.
2] A Death Cross (fast MA crossing below slow MA) where the price moves down afterward.
In this script, I have used a Simple Moving Average (SMA) for illustration.
You can modify the code to apply any type of moving average and test its accuracy.
RoGr75 - EMA 50/8 Cross With Buy/Sell Signals RoGr75 - EMA 50/8 Cross With Buy/Sell Signals
---
**Overview:**
This script is designed to generate **Buy** and **Sell** signals based on the crossover and crossunder of two Exponential Moving Averages (EMAs): **EMA 8** (green line) and **EMA 50** (blue line). The signals are plotted at a user-defined distance from the candles, ensuring clear visibility and adaptability to market volatility.
---
**Key Features:**
1. **EMA Cross Signals**:
- A **Buy Signal** is generated when the **EMA 8** crosses above the **EMA 50**.
- A **Sell Signal** is generated when the **EMA 8** crosses below the **EMA 50**.
2. **Variable Signal Distance**:
- The distance of the Buy and Sell signals from the candles is controlled by a **user-defined input** (`signal_distance`).
- The distance is calculated using the **Average True Range (ATR)** to adapt to market volatility.
3. **Customizable Parameters**:
- `signal_distance`: Adjust the distance of the signals from the candles (default: 2.0).
- ATR period: Fixed at 14 but can be modified in the script.
4. **Visual Enhancements**:
- Buy signals are displayed as green labels below the candles.
- Sell signals are displayed as red labels above the candles.
- Optional background highlighting for Buy and Sell signals.
---
**How It Works:**
- The script calculates the **EMA 8** and **EMA 50** and plots them on the chart.
- When a crossover or crossunder occurs, a label is placed at a distance determined by the formula:
- **Buy Signal Position**: `low - (signal_distance * ATR(14))`
- **Sell Signal Position**: `high + (signal_distance * ATR(14))`
- The signals are clearly visible and adapt to the volatility of the asset.
---
**Input Parameters:**
- `signal_distance` (type: input float): Controls the distance of the Buy and Sell signals from the candles. Default value is `2.0`.
---
**Usage:**
1. Add the script to your chart in TradingView.
2. Adjust the `signal_distance` input to set the desired distance of the signals from the candles.
3. Monitor the Buy and Sell signals generated by the script for potential trading opportunities.
---
**Example:**
- If `signal_distance` is set to `2.0`, the Buy signal will appear **2x ATR** below the candle's low, and the Sell signal will appear **2x ATR** above the candle's high.
---
**Customization:**
- Modify the ATR period or replace it with a fixed value for static distance.
- Adjust the colors, styles, and sizes of the labels and EMAs to suit your preferences.
---
**Ideal For:**
- Traders looking for a simple and effective EMA crossover strategy.
- Users who want customizable signal placement for better visibility.
- Those who prefer volatility-adjusted signal distances.
---
**Note:**
This script is for educational and informational purposes only. Always backtest and validate strategies before using them in live trading.
Triple Trend Indicator [BigBeluga]Triple Trend Indicator is a versatile trend-following tool designed to help traders identify trend strength and potential pullback levels using a three-band system. Each band represents a varying degree of price deviation from the mean, providing progressively stronger trend signals.
🔵 Key Features:
Three Adaptive Bands:
The indicator dynamically calculates three bands (1, 2, and 3) based on moving averages (SMA, EMA, WMA) and ATR multipliers.
Bands are positioned below the price in an uptrend and above the price in a downtrend, offering clear trend direction visualization.
Signal System:
Signals are generated when price interacts with the bands:
Signal 1: Triggered when the price touches Band 1, indicating a minor pullback within the trend.
Signal 2: Triggered at Band 2, showing a stronger price deviation and trend confirmation.
Signal 3: Triggered at Band 3, representing the most significant price deviation and strongest trend signal.
The further the price deviates from the mean, the stronger the trend signal, with Signal 3 being the most robust.
Color-Coded Bands:
Bands dynamically change color based on the trend direction:
Green bands signify an uptrend.
Brown bands signify a downtrend.
Dynamic Trend Line Changes:
Dashed lines highlight trend changes, helping traders visualize key turning points in the market.
🔵 Usage:
Use the bands to identify trend direction and strength.
Monitor the signal system to assess the level of price deviation and potential pullback strength.
Combine Signal 1, 2, and 3 to confirm trend momentum:
Signal 1 suggests a weaker pullback and continuation.
Signal 2 indicates a stronger trend confirmation.
Signal 3 highlights the strongest momentum and potential exhaustion points.
Utilize the color-coded bands for an intuitive understanding of current market conditions.
The Triple Trend Indicator is an ideal tool for trend traders looking for structured signals and dynamic support and resistance levels to optimize entries and exits.
RSI Crossover dipali parikhThis script generates buy and sell signals based on the crossover of the Relative Strength Index (RSI) and the RSI-based Exponential Moving Average (EMA). It also includes an additional condition for both buy and sell signals that the RSI-based EMA must be either above or below 50.
Key Features:
Buy Signal: Triggered when:
The RSI crosses above the RSI-based EMA.
The RSI-based EMA is above 50.
A green "BUY" label will appear below the bar when the buy condition is met.
Sell Signal: Triggered when:
The RSI crosses below the RSI-based EMA.
The RSI-based EMA is below 50.
A red "SELL" label will appear above the bar when the sell condition is met.
Customizable Inputs:
RSI Length: Adjust the period for calculating the RSI (default is 14).
RSI-based EMA Length: Adjust the period for calculating the RSI-based EMA (default is 9).
RSI Threshold: Adjust the threshold (default is 50) for when the RSI-based EMA must be above or below.
Visuals:
The RSI is plotted as a blue line.
The RSI-based EMA is plotted as an orange line.
Buy and sell signals are indicated by green "BUY" and red "SELL" labels.
Alerts:
Alerts can be set for both buy and sell conditions to notify you when either condition is met.
How to Use:
Use this script to identify potential buy and sell opportunities based on the behavior of the RSI relative to its EMA.
The buy condition indicates when the RSI is strengthening above its EMA, and the sell condition signals when the RSI is weakening below its EMA.
Strategy Use:
Ideal for traders looking to leverage RSI momentum for entering and exiting positions.
The RSI-based EMA filter helps smooth out price fluctuations, focusing on stronger signals.
This script is designed for both discretionary and algorithmic traders, offering a simple yet effective method for spotting trend reversals and continuation opportunities using RSI.
Machine Learning SupertrendThe Machine Learning Supertrend is an advanced trend-following indicator that enhances the traditional Supertrend with Gaussian Process Regression (GPR) and kernel-based learning. Unlike conventional methods that rely purely on historical ATR values, this indicator integrates machine learning techniques to dynamically estimate volatility and forecast future price movements, resulting in a more adaptive and robust trend detection system.
At the core of this indicator lies Gaussian Process Regression (GPR), which utilizes a Radial Basis Function (RBF) kernel to model price distributions and anticipate future trends. Instead of simply looking at past price action, it constructs a kernel matrix, enabling a probabilistic approach to price forecasting. This allows the indicator to not only detect current trends but also project potential trend reversals with greater accuracy.
By applying machine learning to ATR estimation, the ML Supertrend dynamically adjusts its thresholds based on predicted values rather than a fixed multiplier. This makes the trend signals more responsive to market conditions, reducing false signals and minimizing whipsaws often seen with traditional Supertrend indicators. The upper and lower bands are no longer static but evolve based on the underlying price structure, improving the reliability of trend shifts.
When the price crosses these adaptive levels, the indicator detects a trend change and plots it accordingly. Green signifies a bullish trend, while red indicates a bearish one. Alerts can also be triggered when the trend shifts, allowing traders to react quickly to potential reversals.
What makes this approach powerful is its ability to adapt to different market conditions. Traditional ATR-based methods use fixed parameters that might not always be optimal, whereas this ML-driven Supertrend continuously refines its estimations based on real-time data. The result is a more intelligent, less lagging, and highly adaptive trend-following tool.
This indicator is particularly useful for traders looking to enhance trend-following strategies with AI-driven insights. It reduces noise, improves signal reliability, and even offers a degree of trend forecasting, making it ideal for those who want a more advanced and dynamic alternative to standard Supertrend indicators.
This indicator is provided for educational and informational purposes only. It does not constitute financial advice, and past performance is not indicative of future results. Trading involves risk, and users should conduct their own research and use proper risk management before making investment decisions.
200-Week EMA % Difference200-Week EMA Percentage Difference Indicator – Understanding Market Stretch & Reversion
What This Indicator Does
Even if an individual stock is delivering strong earnings and solid fundamentals, it is still influenced by overall market sentiment. When the broader market begins reverting to its long-term mean, stocks—no matter how strong—are often pulled down along with it. Unrealized gains can erode if one ignores these macro movements.
The 200-Week EMA Percentage Difference indicator measures how far the price of an asset or index has moved away from its 200-week Exponential Moving Average (EMA) in percentage terms. This provides a reliable gauge of whether the market is overstretched (overbought) or pulling back to support (oversold) relative to a long-term trend.
How It Helps Investors
Identifying Market Extremes:
When the indicator moves into the 50-80% range, historical trends show that broad-based indices like BSE Smallcap, Nifty 500, Nifty Microcap, and Nifty Smallcap 250 have often experienced corrections.
This suggests that the market may be overextended, and investors should exercise caution.
Spotting Support Zones:
Past data indicates that when the percentage difference falls back to around 30%, the market often finds a new support level, leading to fresh buying opportunities.
This can help long-term investors identify favorable entry points.
Mean Reversion & Market Cycles:
The indicator essentially measures how far these indices have stretched from their long-term mean (200-week EMA).
Extreme deviations from the EMA often result in mean reversion, where prices eventually return to more sustainable levels.
How to Use It in Broad-Based Indices
Above 50-80% → Caution Zone: Historically associated with market tops or overheated conditions.
Around 30% → Support Zone: A potential level where corrections stabilize and new market uptrends begin.
By applying this indicator to indices like BSE Smallcap, Nifty 500, Nifty Microcap, and Nifty Smallcap 250, investors can gauge market strength, anticipate corrections, and position themselves strategically for long-term opportunities.
NDTECH Tool-N1CPR (Central Pivot Range) is a popular trading indicator used in technical analysis to identify potential support and resistance levels. It is based on the concept of pivot points, which are calculated using the high, low, and close prices of the previous trading session. The CPR indicator provides three key levels: the Central Pivot (P), the Bottom Central Pivot (BC), and the Top Central Pivot (TC).
Key Components of CPR:
Central Pivot (P): This is the primary level and is calculated as the average of the high, low, and close prices of the previous session.
P=High+Low+Close3
P=3High+Low+Close
Bottom Central Pivot (BC): This level acts as a support level and is calculated as the average of the Central Pivot and the low of the previous session.
BC=P+Low2
BC=2P+Low
Top Central Pivot (TC): This level acts as a resistance level and is calculated as the average of the Central Pivot and the high of the previous session.
TC=P+High2
TC=2P+High
Explanation:
request.security: This function is used to fetch the high, low, and close prices of the previous day. The "D" parameter specifies the daily timeframe.
plot: This function is used to plot the CPR levels on the chart.
fill: This function is used to highlight the area between the BC and TC levels, providing a visual representation of the CPR range.
Usage:
Support and Resistance: Traders use the CPR levels to identify potential support (BC) and resistance (TC) levels. Price action around these levels can provide insights into market sentiment.
Trend Identification: If the price is consistently above the Central Pivot (P), it may indicate a bullish trend, while prices below P may indicate a bearish trend.
Breakout Trading: Breakouts above TC or below BC can signal potential trading opportunities.
Conclusion:
The CPR indicator is a versatile tool that can be used in various trading strategies. By implementing it in Pine Script, traders can customize and automate their analysis on the TradingView platform, making it easier to identify key levels and make informed trading decisions.
Delta SMA 1-Year High/Low Strategy### Summary:
This Pine Script code implements a trading strategy based on the **Delta SMA (Simple Moving Average)** of buy and sell volumes over a 1-year lookback period. The strategy identifies potential buy and sell signals by analyzing the relationship between the Delta SMA and its historical high/low thresholds. Key features include:
1. **Delta Calculation**:
- The Delta is calculated as the difference between buy volume (when close > open) and sell volume (when close < open).
- A 14-period SMA is applied to the Delta to smooth the data.
2. **1-Year High/Low Thresholds**:
- The strategy calculates the 1-year high and low of the Delta SMA.
- Buy and sell conditions are derived from thresholds set at 70% of the 1-year low and 90% and 50% of the 1-year high, respectively.
3. **Buy Condition**:
- A buy signal is triggered when the Delta SMA crosses above 0 after being below 70% of the 1-year low.
4. **Sell Condition**:
- A sell signal is triggered when the Delta SMA drops below 60% of the 1-year high after crossing above 90% of the 1-year high.
5. **Visualization**:
- The Delta SMA and its thresholds are plotted on the chart for easy monitoring.
- Optional buy/sell signals can be plotted as labels on the chart.
This strategy is designed to capture trends in volume-based momentum over a long-term horizon, making it suitable for swing or position trading.
High-Low Breakout Strategy with ATR traling Stop LossThis script is a TradingView Pine Script strategy that implements a High-Low Breakout Strategy with ATR Trailing Stop.created by SK WEALTH GURU, Here’s a breakdown of its key components:
Features and Functionality
Custom Timeframe and High-Low Detection
Allows users to select a custom timeframe (default: 30 minutes) to detect high and low levels.
Tracks the high and low within a user-specified period (e.g., first 30 minutes of the session).
Draws horizontal lines for high and low, persisting for a specified number of days.
Trade Entry Conditions
Long Entry: If the closing price crosses above the recorded high.
Short Entry: If the closing price crosses below the recorded low.
The user can choose to trade Long, Short, or Both.
ATR-Based Trailing Stop & Risk Management
Uses Average True Range (ATR) with a multiplier (default: 3.5) to determine a dynamic trailing stop-loss.
Trades reset daily, ensuring a fresh start each day.
Trade Execution and Partial Profit Taking
Stop-loss: Default at 1% of entry price.
Partial profit: Books 50% of the position at 3% profit.
Max 2 trades per day: If the first trade hits stop-loss, the strategy allows one re-entry.
Intraday Exit Condition
All positions close at 3:15 PM to ensure no overnight risk.
Ultimate Stochastics Strategy by NHBprod Use to Day Trade BTCHey All!
Here's a new script I worked on that's super simple but at the same time useful. Check out the backtest results. The backtest results include slippage and fees/commission, and is still quite profitable. Obviously the profitability magnitude depends on how much capital you begin with, and how much the user utilizes per order, but in any event it seems to be profitable according to backtests.
This is different because it allows you full functionality over the stochastics calculations which is designed for random datasets. This script allows you to:
Designate ANY period of time to analyze and study
Choose between Long trading, short trading, and Long & Short trading
It allows you to enter trades based on the stochastics calculations
It allows you to EXIT trades using the stochastics calculations or take profit, or stop loss, Or any combination of those, which is nice because then the user can see how one variable effects the overall performance.
As for the actual stochastics formula, you get control, and get to SEE the plot lines for slow K, slow D, and fast K, which is usually not considered.
You also get the chance to modify the smoothing method, which has not been done with regular stochastics indicators. You get to choose the standard simple moving average (SMA) method, but I also allow you to choose other MA's such as the HMA and WMA.
Lastly, the user gets the option of using a custom trade extender, which essentially allows a buy or sell signal to exist for X amount of candles after the initial signal. For example, you can use "max bars since signal" to 1, and this will allow the indicator to produce an extra sequential buy signal when a buy signal is generated. This can be useful because it is possible that you use a small take profit (TP) and quickly exit a profitable trade. With the max bars since signal variable, you're able to reenter on the next candle and allow for another opportunity.
Let me know if you have any questions! Please take a look at the performance report and let me know your thoughts! :)
Overnight vs Intra-day Performance█ STRATEGY OVERVIEW
The "Overnight vs Intra-day Performance" indicator quantifies price behaviour differences between trading hours and overnight periods. It calculates cumulative returns, compound growth rates, and visualizes performance components across user-defined time windows. Designed for analytical use, it helps identify whether returns are primarily generated during market hours or overnight sessions.
█ USAGE
Use this indicator on Stocks and ETFs to visualise and compare intra-day vs overnight performance
█ KEY FEATURES
Return Segmentation : Separates total returns into overnight (close-to-open) and intraday (open-to-close) components
Growth Tracking : Shows simple cumulative returns and compound annual growth rates (CAGR)
█ VISUALIZATION SYSTEM
1. Time-Series
Overnight Returns (Red)
Intraday Returns (Blue)
Total Returns (White)
2. Summary Table
Displays CAGR
3. Price Chart Labels
Floating annotations showing absolute returns and CAGR
Color-coded to match plot series
█ PURPOSE
Quantify market behaviour disparities between active trading sessions and overnight positioning
Provide institutional-grade attribution analysis for returns generation
Enable tactical adjustment of trading schedules based on historical performance patterns
Serve as foundational research for session-specific trading strategies
█ IDEAL USERS
1. Portfolio Managers
Analyse overnight risk exposure across holdings
Optimize execution timing based on return distributions
2. Quantitative Researchers
Study market microstructure through time-segmented returns
Develop alpha models leveraging session-specific anomalies
3. Market Microstructure Analysts
Identify liquidity patterns in overnight vs daytime sessions
Research ETF premium/discount mechanics
4. Day Traders
Align trading hours with highest probability return windows
Avoid overnight gaps through informed position sizing