Simplified Gap Strategy with SMA FilterThe Simplified Gap Strategy leverages price gaps as a trading signal, focusing on their significance in market behavior. Gaps occur when the opening price of a security differs significantly from the previous closing price, often signaling potential continuation or reversal patterns.
Key Features:
Gap Threshold:
This strategy requires a minimum percentage gap (defined by the user) to qualify for trading signals.
Directional Trading:
Users can select from various gap types, including "Long Up Gap" and "Short Down Gap," allowing for tailored trading approaches.
SMA Filter:
An optional Simple Moving Average (SMA) filter helps refine trade entries based on trend direction, increasing the probability of successful trades.
Hold Duration:
Positions can be held for a user-defined duration, providing flexibility in trade management.
Statistical Significance of Gaps:
Research has shown that gaps can provide insights into future price movements. According to studies such as those by Hutton and Jiang (2008), price gaps are often followed by momentum in the direction of the gap, indicating that they can serve as reliable indicators for traders. The "Gap Theory" suggests that gaps are filled approximately 90% of the time, emphasizing their relevance in market dynamics (Nikkinen, Sahlström, & Kinnunen, 2006).
Important Note:
This strategy is designed solely for statistical analysis and should not be construed as financial advice. Users are encouraged to conduct their own research and analysis before applying this strategy in live trading scenarios.
By understanding the underlying mechanisms of price gaps and their statistical significance, traders can enhance their decision-making processes and potentially improve trading outcomes.
References:
Hutton, A. W., & Jiang, W. (2008). "Price Gaps: A Guide to Trading Gaps."
Nikkinen, J., Sahlström, P., & Kinnunen, J. (2006). "The Gaps in Financial Markets: An Empirical Study."
This description provides an overview of the strategy while emphasizing its analytical purpose and backing it with relevant academic insights.
Pine utilities
Streak-Based Trading StrategyThe strategy outlined in the provided script is a streak-based trading strategy that focuses on analyzing winning and losing streaks. It’s important to emphasize that this strategy is not intended for actual trading but rather for statistical analysis of streak series.
How the Strategy Works
1. Parameter Definition:
• Trade Direction: Users can choose between “Long” (buy) and “Short” (sell).
• Streak Threshold: Defines how many consecutive wins or losses are needed to trigger a trade.
• Hold Duration: Specifies how many periods the position will be held.
• Doji Threshold: Determines the sensitivity for Doji candles, which indicate market uncertainty.
2. Streak Calculation:
• The script identifies Doji candles and counts winning and losing streaks based on the closing price compared to the previous closing price.
• Streak counting occurs only when no position is currently held.
3. Trade Conditions:
• If the loss streak reaches the defined threshold and the trade direction is “Long,” a buy position is opened.
• If the win streak is met and the trade direction is “Short,” a sell position is opened.
• The position is held for the specified duration.
4. Visualization:
• Winning and losing streaks are plotted as histograms to facilitate analysis.
Scientific Basis
The concept of analyzing streaks in financial markets is well-documented in behavioral economics and finance. Studies have shown that markets often exhibit momentum and trend-following behavior, meaning the likelihood of consecutive winning or losing periods can be higher than what random statistics would suggest (see, for example, “The Behavior of Stock-Market Prices” by Eugene Fama).
Additionally, empirical research indicates that investors often make decisions based on psychological factors influenced by streaks. This can lead to irrational behavior, as they may focus on past wins or losses (see “Behavioral Finance: Psychology, Decision-Making, and Markets” by R. M. F. F. Thaler).
Overall, this strategy serves as a tool for statistical analysis of streak series, providing deeper insights into market behavior and trends rather than being directly used for trading decisions.
Price Movement > Custom Points with Day of WeekThe code is a TradingView Pine Script indicator designed to track and visualize price movements in a financial market (like stocks or cryptocurrencies) based on a specific point threshold. Here’s a breakdown of its functionality:
Purpose of the Code:
Price Movement Calculation: It calculates the difference between the closing price and the opening price of each bar (or candle) to determine if the price has moved significantly.
Threshold Input: The user can set a threshold (e.g., 500 points) to determine what constitutes a significant movement.
Movement Conditions:
Positive Movement: If the price movement is greater than the threshold, it’s marked as a positive movement.
Negative Movement: If the price movement is less than the negative threshold (i.e., below -500 points), it’s marked as a negative movement.
Day of the Week Identification: The script identifies the day of the week for each bar (Monday through Sunday).
Visual Output:
It plots shapes (like labels) on the chart:
For positive movements, it shows "YES" in green, indicating the movement exceeded the threshold for that day.
For negative movements, it shows "YES" in red, indicating the movement fell below the negative threshold for that day.
Use Cases:
Traders: It helps traders quickly identify days where significant price movements occurred, allowing them to analyze trends and make informed trading decisions.
Market Analysis: The indicator can be used for backtesting strategies based on significant price movements.
Overall, this code serves as a visual tool for analyzing price volatility in a market based on user-defined thresholds and day-based observations. If you have any specific questions or need further clarification about any part of it, feel free to ask!
Currency Futures StatisticsThe "Currency Futures Statistics" indicator provides comprehensive insights into the performance and characteristics of various currency futures. This indicator is crucial for portfolio management as it combines multiple metrics that are instrumental in evaluating currency futures' risk and return profiles.
Metrics Included:
Historical Volatility:
Definition: Historical volatility measures the standard deviation of returns over a specified period, scaled to an annual basis.
Importance: High volatility indicates greater price fluctuations, which translates to higher risk. Investors and portfolio managers use volatility to gauge the stability of a currency future and to make informed decisions about risk management and position sizing (Hull, J. C. (2017). Options, Futures, and Other Derivatives).
Open Interest:
Definition: Open interest represents the total number of outstanding futures contracts that are held by market participants.
Importance: High open interest often signifies liquidity in the market, meaning that entering and exiting positions is less likely to impact the price significantly. It also reflects market sentiment and the degree of participation in the futures market (Black, F., & Scholes, M. (1973). The Pricing of Options and Corporate Liabilities).
Year-over-Year (YoY) Performance:
Definition: YoY performance calculates the percentage change in the futures contract's price compared to the same week from the previous year.
Importance: This metric provides insight into the long-term trend and relative performance of a currency future. Positive YoY performance suggests strengthening trends, while negative values indicate weakening trends (Fama, E. F. (1991). Efficient Capital Markets: II).
200-Day Simple Moving Average (SMA) Position:
Definition: This metric indicates whether the current price of the currency future is above or below its 200-day simple moving average.
Importance: The 200-day SMA is a widely used trend indicator. If the price is above the SMA, it suggests a bullish trend, while being below indicates a bearish trend. This information is vital for trend-following strategies and can help in making buy or sell decisions (Bollinger, J. (2001). Bollinger on Bollinger Bands).
Why These Metrics are Important for Portfolio Management:
Risk Assessment: Historical volatility and open interest provide essential information for assessing the risk associated with currency futures. Understanding the volatility helps in estimating potential price swings, which is crucial for managing risk and setting appropriate stop-loss levels.
Liquidity and Market Participation: Open interest is a critical indicator of market liquidity. Higher open interest usually means tighter bid-ask spreads and better liquidity, which facilitates smoother trading and better execution of trades.
Trend Analysis: YoY performance and the SMA position help in analyzing long-term trends. This analysis is crucial for making strategic investment decisions and adjusting the portfolio based on changing market conditions.
Informed Decision-Making: Combining these metrics allows for a holistic view of the currency futures market. This comprehensive view helps in making informed decisions, balancing risks and returns, and optimizing the portfolio to align with investment goals.
In summary, the "Currency Futures Statistics" indicator equips investors and portfolio managers with valuable data points that are essential for effective risk management, liquidity assessment, trend analysis, and overall portfolio optimization.
Pseudo-Renko Stabilized (Val)█ CALCULATE PSEUDO-RENKO VALUE
Calculates and returns the Pseudo-Renko Stabilized value (or close price) based on a given input value, along with the direction of the current Renko brick. This function adapts the traditional Renko brick size dynamically based on the volatility of the input value using a combination of SMA and EMA calculations. The calculated price represents the closing price of the most recent Pseudo-Renko brick, while the direction indicates the trend ( 1 for uptrend, -1 for downtrend).
Parameters:
* `val` :
* Type: ` float `
* Description: The input value upon which the Pseudo-Renko calculations are performed. You can use any price series or custom value as input.
* `sensitivity` :
* Type: ` float `
* Default Value: ` 1.0 `
* Description: Controls the sensitivity of the brick size to the volatility of the `val`. Higher values lead to larger bricks, resulting in a smoother Renko chart. Lower values produce smaller bricks, leading to a more reactive chart.
* Possible Values: Any positive float.
* `length` :
* Type: ` int `
* Default Value: ` 7 `
* Description: The length used for calculating the EMA and SMA in the dynamic brick size calculation. It influences how quickly the brick size adapts to changing volatility of the `val`.
* Possible Values: Any positive integer.
Return Values:
* `lastRenkoClose` :
* Type: ` float `
* Description: The closing price of the last completed Pseudo-Renko brick based on the `val`.
* `renkoDirection` :
* Type: ` int `
* Description: The direction of the current Pseudo-Renko brick based on the `val`:
* ` 1 `: Uptrend
* ` -1 `: Downtrend
* ` 0 `: No change (initially, or no brick change since the previous bar)
Example Usage:
//@version=5
indicator("Pseudo-Renko Stabilized (Val)", overlay=true)
// Get user inputs
sensitivityInput = input.float(0.1, "Sensitivity",0.01,step=0.01)
lengthInput = input.int(5, "Length",2)
// Example usage with the 'close' price as the input value
= pseudo_renko(math.avg(close,open), sensitivityInput, lengthInput)
// Plot the Renko close price
plot(renkoClose, "Renko Close", renkoDirection>0?color.aqua:color.orange,2)
// You can also use other values as input, such as:
// = pseudo_renko(high, sensitivityInput, lengthInput)
// = pseudo_renko(low, sensitivityInput, lengthInput)
This example demonstrates how to use the `pseudo_renko` function within an indicator. It takes user inputs for `sensitivity` and `length`, then calculates the Pseudo-Renko values using the average of the `close` and `open` prices as the `val`. The resulting `renkoClose` price is plotted on the chart, with a color change based on the `renkoDirection`. It also illustrates how you can use other values, like `high` and `low`, as input to the function.
Note: The Pseudo-Renko algorithm is based on adapting the Renko brick size dynamically based on the input `val`. This provides more flexibility compared to the normal, but is experimental. The `sensitivity` and `length` parameters, along with the choice of the `val`, offer further customization to tune the algorithm's behavior to your preference and trading style.
Sinc MAKaiser Windowed Sinc Moving Average Indicator
The Kaiser Windowed Sinc Moving Average is an advanced technical indicator that combines the sinc function with the Kaiser window to create a highly customizable finite impulse response (FIR) filter for financial time series analysis.
Sinc Function: The Ideal Low-Pass Filter
At the core of this indicator is the sinc function, which represents the impulse response of an ideal low-pass filter. In signal processing and technical analysis, the sinc function is crucial because it allows for the creation of filters with precise frequency cutoff characteristics. When applied to financial data, this means the ability to separate long-term trends from short-term fluctuations with remarkable accuracy.
The primary advantage of using a sinc-based filter is the independent control over two critical parameters: the cutoff frequency and the number of samples used. The cutoff frequency, analogous to the "length" in traditional moving averages, determines which price movements are considered significant (low frequency) and which are treated as noise (high frequency). By adjusting the cutoff, analysts can fine-tune the filter to respond to specific market cycles or timeframes of interest.
The number of samples used in the filter doesn't affect the cutoff frequency but instead influences the filter's accuracy and steepness. Increasing the sample size results in a better approximation of the ideal low-pass filter, leading to sharper transitions between passed and attenuated frequencies. This allows for more precise trend identification and noise reduction without changing the fundamental frequency response characteristics.
Kaiser Window: Optimizing the Sinc Filter
While the sinc function provides excellent frequency domain characteristics, it has infinite length in the time domain, which is impractical for real-world applications. This is where the Kaiser window comes into play. By applying the Kaiser window to the sinc function, we create a finite-length filter that approximates the ideal response while minimizing unwanted oscillations (known as the Gibbs phenomenon) in the frequency domain.
The Kaiser window introduces an additional parameter, alpha, which controls the trade-off between the main-lobe width and side-lobe levels in the frequency response. This parameter allows users to fine-tune the filter's behavior, balancing between sharp cutoffs and minimal ripple effects.
Customizable Parameters
The Kaiser Windowed Sinc Moving Average offers several key parameters for customization:
Cutoff: Controls the filter's cutoff frequency, determining the divide between trends and noise.
Length: Sets the number of samples used in the FIR filter calculation, affecting the filter's accuracy and computational complexity.
Alpha: Influences the shape of the Kaiser window, allowing for fine-tuning of the filter's frequency response characteristics.
Centered and Non-Centered Modes
The indicator provides two operational modes:
Non-Centered (Real-time) Mode: Uses half of the windowed sinc function, suitable for real-time analysis and current market conditions.
Centered Mode: Utilizes the full windowed sinc function, resulting in a zero-phase filter. This mode introduces a delay but offers the most accurate trend identification for historical analysis.
Visualization Features
To enhance the analytical value of the indicator, several visualization options are included:
Gradient Coloring: Offers a range of color schemes to represent trend direction and strength.
Glow Effect: An optional visual enhancement for improved line visibility.
Background Fill: Highlights the area between the moving average and price, aiding in trend visualization.
Applications in Technical Analysis
The Kaiser Windowed Sinc Moving Average is particularly useful for precise trend identification, cycle analysis, and noise reduction in financial time series. Its ability to create custom low-pass filters with independent control over cutoff and filter accuracy makes it a powerful tool for analyzing various market conditions and timeframes.
Compared to traditional moving averages, this indicator offers superior frequency response characteristics and reduced lag in trend identification when properly tuned. It provides greater flexibility in filter design, allowing analysts to create moving averages tailored to specific trading strategies or market behaviors.
Conclusion
The Kaiser Windowed Sinc Moving Average represents an advanced approach to price smoothing and trend identification in technical analysis. By making the ideal low-pass filter characteristics of the sinc function practically applicable through Kaiser windowing, this indicator provides traders and analysts with a sophisticated tool for examining price trends and cycles.
Its implementation in Pine Script contributes to the TradingView community by making advanced signal processing techniques accessible for experimentation and further development in technical analysis. This indicator serves not only as a practical tool for market analysis but also as an educational resource for those interested in the intersection of signal processing and financial markets.
Related script:
Thai Gold 96.5%Gold 96.5% Price Display (Test Version)
This Pine Script indicator is a test version designed to display the current price of Thai gold (96.5%) in a customizable table on your TradingView chart. The script calculates the gold price using the latest values for XAU/USD and USD/THB, reflecting the price of gold in Thai Baht (THB) with a purity adjustment.
Features:
- Price Calculation: Computes the Thai gold price by multiplying the XAU/USD price with USD/THB and adjusting for gold purity (0.49 * 0.965).
- Customizable Display: Adjust text size, text color, background color, and table position (Top Right, Top Left, Bottom Right, Bottom Left).
- Formatted Output: Gold price is formatted with commas for better readability.
Inputs:
- Text Size: Choose from tiny, small, normal, large, or huge.
- Text Color: Customize the text color.
- Background Color: Select a background color for the table.
- Table Position: Choose the table position on the chart.
Usage:
Add this test script to your TradingView chart to see the current Thai gold price displayed in a table format. This version is for testing purposes and may be updated based on feedback.
Feel free to test and customize the script further!
Kaiser Window MAKaiser Window Moving Average Indicator
The Kaiser Window Moving Average is a technical indicator that implements the Kaiser window function in the context of a moving average. This indicator serves as an example of applying the Kaiser window and the modified Bessel function of the first kind in technical analysis, providing an open-source implementation of these functions in the TradingView Pine Script ecosystem.
Key Components
Kaiser Window Implementation
This indicator incorporates the Kaiser window, a parameterized window function with certain frequency response characteristics. By making this implementation available in Pine Script, it allows for exploration and experimentation with the Kaiser window in the context of financial time series analysis.
Modified Bessel Function of the First Kind
The indicator includes an implementation of the modified Bessel function of the first kind, which is integral to the Kaiser window calculation. This mathematical function is now accessible within TradingView, potentially useful for other custom indicators or studies.
Customizable Alpha Parameter
The indicator features an adjustable alpha parameter, which directly influences the shape of the Kaiser window. This parameter allows for experimentation with the indicator's behavior:
Lower alpha values: The indicator's behavior approaches that of a Simple Moving Average (SMA)
Moderate alpha values: The behavior becomes more similar to a Weighted Moving Average (WMA)
Higher alpha values: Increases the weight of more recent data points
In signal processing terms, the alpha parameter affects the trade-off between main-lobe width and side lobe level in the frequency domain.
Centered and Non-Centered Modes
The indicator offers two operational modes:
Non-Centered (Real-time) Mode: Uses half of the Kaiser window, starting from the peak. This mode operates similarly to traditional moving averages, suitable for real-time analysis.
Centered Mode: Utilizes the full Kaiser window, resulting in a phase-correct filter. This mode introduces a delay equal to half the window size, with the plot automatically offset to align with the correct time points.
Visualization Options
The indicator includes several visualization features to aid in analysis:
Gradient Coloring: Offers three gradient options:
• Three-color gradient: Includes a neutral color
• Two-color gradient: Traditional up/down color scheme
• Solid color: For a uniform appearance
Glow Effect: An optional visual enhancement for the moving average line.
Background Fill: An option to fill the area between the moving average and the price.
Use Cases
The Kaiser Window Moving Average can be applied similarly to other moving averages. Its primary value lies in providing an example implementation of the Kaiser window and modified Bessel function in TradingView. It serves as a starting point for traders and analysts interested in exploring these mathematical concepts in the context of technical analysis.
Conclusion
The Kaiser Window Moving Average indicator demonstrates the application of the Kaiser window function in a moving average calculation. By providing open-source implementations of the Kaiser window and the modified Bessel function of the first kind, this indicator contributes to the expansion of available mathematical tools in the TradingView Pine Script environment, potentially facilitating further experimentation and development in technical analysis.
Break of High/Low with Volume, MACD, and MAsHow It Works:
Sessions:
The London session is defined between 8:00 and 16:00 UTC.
The New York session is defined between 13:00 and 21:00 UTC.
Previous High/Low:
The script identifies the highest high and lowest low from the previous bar using ta.highest(high, 1) and ta.lowest(low, 1) .
Candle Body Size:
The script calculates the size of the current candle's body and checks if it is at least double the size of the previous candle's body.
Volume Check:
A high volume threshold is set as 1.5 times the 50-period SMA of the volume.
MACD Crossover:
The script calculates the MACD and its signal line and checks for bullish (buy) or bearish (sell) crossovers.
Signals:
A long signal (buy) is generated if the price breaks the previous high with a large body candle, high volume, and a bullish MACD crossover during the specified sessions.
A short signal (sell) is generated if the price breaks the previous low with a large body candle, high volume, and a bearish MACD crossover during the specified sessions.
Plotting:
The 50-period and 200-period moving averages, previous high, and previous low are plotted on the chart.
If a long condition is met, a "BUY" label is displayed below the bar. If a short condition is met, a "SELL" label is displayed above the bar.
Alerts:
Alerts are triggered whenever the conditions for a long or short trade are met.
Customization:
Feel free to adjust the session times, volume threshold, MACD settings, or moving averages based on your trading strategy or the specific asset you are trading.
GC Strategy with Trend Filter and Sudden Move Profit TakingBYBIT:BTCUSDT.P 15M
Situation Assessment with Three Moving Averages
The strategy uses the crossover of the 5SMA and 25SMA as entry signals.
Additionally, the 75SMA is used as a filter. Long entries are only allowed when the price is above the 75SMA, and short entries are only allowed when the price is below the 75SMA.
ADX Filter
The Average Directional Index (ADX) is used to check the strength of the trend. Entry signals are only activated when the ADX is above 20. This ensures that trades are only executed when the trend is strong.
Sudden Move Detection
The strategy detects sudden price movements. If a sudden move occurs, the position is closed to lock in profits.
Entry
Long Entry: When the 5SMA crosses above the 25SMA, the price is above the 75SMA, and the ADX is above 20.
Short Entry: When the 5SMA crosses below the 25SMA, the price is below the 75SMA, and the ADX is above 20.
Exit
Positions are closed if a sudden move occurs. Positions are also closed if an opposing entry signal is generated.
This strategy aims to confirm the strength of the trend using moving average crossovers and ADX and to lock in profits based on sudden price movements.
3本の移動平均線による状況判断
5SMAと25SMA のクロスオーバーをエントリーシグナルとして使用します。
さらに、75SMAをフィルターとして使用し、価格が75SMAの上にある場合のみロングエントリーを許可し、75SMAの下にある場合のみショートエントリーを許可します。
ADXフィルター
ADX(平均方向性指数)を使ってトレンドの強さを確認します。
ADXが20より大きい場合のみ、エントリーシグナルを有効にします。これにより、トレンドが強い時にのみ取引を行うことができます。
急激な変動検知
価格の急激な変動を検出します。
急激な変動があった場合には、ポジションをクローズして利益を確定します。
エントリー
ロングエントリー
5SMAが25SMAを上にクロスし、価格が75SMAの上にあり、ADXが20を超えているとき。
ショートエントリー
5SMAが25SMAを下にクロスし、価格が75SMAの下にあり、ADXが20を超えているとき。
エグジット
急激な変動があった場合、ポジションをクローズします。
反対のエントリーシグナルが発生した場合にも、ポジションをクローズします。
このストラテジーは、移動平均のクロスオーバーとADXを使ってトレンドの強さを確認し、急激な変動に基づいて利益を確定することを目的としています。
Fibonacci Retracements & Trend Following Strategy V2This Pine Script strategy generates trading signals using Fibonacci levels and trend-following indicators.
1. Strategy Summary
This strategy analyzes price movements using a combination of Fibonacci levels and trend-following indicators, providing potential trading signals. The strategy includes Fibonacci levels as well as EMA (Exponential Moving Average) and ADX (Average Directional Index) indicators.
2. Indicators and Parameters
Fibonacci Levels
Fibonacci Level 1, Level 2, Level 3, Level 4: Used as Fibonacci retracement levels. These levels are typically set at 0.236, 0.382, 0.618, and 0.786. Users can adjust these values according to their preferences.
Trend-Following Indicator
Trend Length: The period for calculating the EMA used as the trend-following indicator. For example, if set to 20, the EMA will be calculated over 20 periods.
ADX (Average Directional Index)
ADX Length: The period for calculating the ADX. ADX measures the strength of the price trend and is usually set to 14 periods.
ADX Threshold: A threshold value for the ADX. This value determines when trading signals will be activated.
3. Usage Steps
Displaying the Indicator on the Chart:
On the TradingView platform, paste the code into the Pine Editor and click the "Add to Chart" button to add it to the chart.
Analyzing the Indicators:
Fibonacci Levels: Show retracement levels of price movements. When the price reaches one of these levels, potential reversals may occur.
Trend-Following Indicator: EMAs determine the direction of the trend. Green EMA represents an uptrend, while red EMA represents a downtrend.
ADX: Measures the strength of the trend. When ADX surpasses the threshold value, it indicates a strong trend.
Trading Signals:
Long Signal: Generated when the price is above the second Fibonacci level and the trend is upward. Additionally, the ADX value must be above the set threshold.
Short Signal: Generated when the price is below the second Fibonacci level and the trend is downward. Additionally, the ADX value must be above the set threshold.
Target Prices:
Long Targets: Determines upward targets based on Fibonacci levels. These targets indicate expected prices if the price reverses from Fibonacci levels.
Short Targets: Determines downward targets based on Fibonacci levels. These targets indicate expected prices if the price reverses from Fibonacci levels.
4. Chart Displays
Trend Up (Green Line): Shows the rising EMA.
Trend Down (Red Line): Shows the falling EMA.
Fibonacci Levels (Blue Lines): Shows Fibonacci retracement levels.
Long Targets (Green Circles): Shows targets for long positions.
Short Targets (Red Circles): Shows targets for short positions.
Long Signal (Green Label): Buy signal.
Short Signal (Red Label): Sell signal.
5. Important Notes
Retracement and Target Levels: Fibonacci levels can act as potential retracement or support/resistance levels. However, they should always be used in conjunction with other technical analysis tools.
Trend and ADX: ADX is used to determine the strength of the trend. Be aware that when ADX is low, trends may be weak.
6. Example Scenarios
Example 1: If the trend is upward (green EMA) and the price is above the second Fibonacci level, you may receive a long position signal. If the ADX value is above the threshold, the signal may be stronger.
Example 2: If the trend is downward (red EMA) and the price is below the second Fibonacci level, you may receive a short position signal. If the ADX value is above the threshold, the signal may be stronger.
This updated version contains significant improvements in both technical aspects and user experience. Innovations such as ADX calculations and dynamic Fibonacci levels make the strategy more robust and flexible. The code's readability and comprehensibility have been enhanced, and errors have been corrected.
This guide will help you understand the basic operation of the strategy. It is always recommended to conduct your own research and test the strategy before using it.
GOOD LUCK. // halilvarol
World Clock [VHX]Keeping track of local times across different time zones has always been a challenge, especially when working with global markets.
But worry no more, as we now have a solution tailored for this very need. With this indicator, you can effortlessly add two different time zones to your chart, making it easier than ever to stay on top of market activity. The indicator not only shows the current date and time for the selected time zones but also integrates seamlessly with your chart, ensuring that you’re always aligned with the right market timings, no matter where you or your trades are based.
Unfortunately, the clock won't function when the market is closed.
Volatility Projection Levels (VPL)### Indicator Name: **Volatility Projection Levels (VPL)**
### Description:
The **Volatility Projection Levels (VPL)** indicator is a powerful tool designed to help traders anticipate key support and resistance levels for the E-mini S&P 500 (ES) by leveraging the CBOE Volatility Index (^VIX). This indicator utilizes historical volatility data to project potential price movements for the upcoming month, offering clear visual cues that enhance swing trading strategies.
### Key Features:
- **Volatility-Based Projections**: The VPL indicator uses the previous month’s closing value of the VIX, normalizing it for monthly analysis by dividing by the square root of 12. This calculated percentage is then applied to the E-mini S&P 500’s closing price from the last day of the previous month.
- **Upper and Lower Projection Levels**: The indicator calculates two essential levels:
- **Upper Projection Level**: The previous month’s closing price of the E-mini S&P 500 plus the calculated volatility percentage.
- **Lower Projection Level**: The previous month’s closing price of the E-mini S&P 500 minus the calculated volatility percentage.
- **Continuous Visualization**: The VPL indicator plots these projection levels on the chart throughout the entire month, providing traders with a consistent reference for potential support and resistance zones. This continuous visualization allows for better anticipation of market movements.
- **Previous Month's Close Reference**: Additionally, the indicator plots the previous month’s closing price as a reference point, offering further context for current price action.
### Use Cases:
- **Swing Trading**: The VPL indicator is ideal for swing traders looking to exploit predicted price ranges within a monthly timeframe.
- **Support & Resistance Identification**: It aids traders in identifying critical levels where the market may encounter support or resistance, thus informing entry and exit decisions.
- **Risk Management**: By forecasting potential price levels, traders can set more strategic stop-loss and take-profit levels, enhancing risk management.
### Summary:
The **Volatility Projection Levels (VPL)** indicator equips traders with a forward-looking tool that incorporates volatility data into market analysis. By projecting key price levels based on historical VIX data, the VPL indicator enhances decision-making, helping traders anticipate market movements and optimize their trading strategies.
Made by Serpenttrading
Raj - Mark Minervini Stage 2 with RSTitle: Mark Minervini Stage 2 Screener with Custom RS
Description:
This script is designed to identify stocks that meet the criteria for Mark Minervini's Stage 2 trend setup, incorporating custom relative strength (RS) ranking.
Key Features:
Moving Averages: Tracks the 50-day, 150-day, and 200-day Simple Moving Averages (SMA) to identify trend alignment.
Price Conditions: Ensures the stock price is above key moving averages, is within 25% of its 52-week high, and is at least 25% above its 52-week low.
Custom Relative Strength (RS): Compares the stock's performance against a benchmark (e.g., S&P 500) to ensure it has a strong relative strength. The RS is normalized on a 0-100 scale, and only stocks with an RS above 70 are highlighted.
Visual Indicators: The script plots moving averages on the chart and labels points where all conditions for the Stage 2 setup are met.
Usage:
Apply this script to your charts to find stocks that are in a strong uptrend and meet Mark Minervini's Stage 2 criteria.
Customize the benchmark symbol for the RS calculation to fit your market or preference
csv_series_libraryThe CSV Series Library is an innovative tool designed for Pine Script developers to efficiently parse and handle CSV data for series generation. This library seamlessly integrates with TradingView, enabling the storage and manipulation of large CSV datasets across multiple Pine Script libraries. It's optimized for performance and scalability, ensuring smooth operation even with extensive data.
Features:
Multi-library Support: Allows for distribution of large CSV datasets across several libraries, ensuring efficient data management and retrieval.
Dynamic CSV Parsing: Provides robust Python scripts for reading, formatting, and partitioning CSV data, tailored specifically for Pine Script requirements.
Extensive Data Handling: Supports parsing CSV strings into Pine Script-readable series, facilitating complex financial data analysis.
Automated Function Generation: Automatically wraps CSV blocks into distinct Pine Script functions, streamlining the process of integrating CSV data into Pine Script logic.
Usage:
Ideal for traders and developers who require extensive data analysis capabilities within Pine Script, especially when dealing with large datasets that need to be partitioned into manageable blocks. The library includes a set of predefined functions for parsing CSV data into usable series, making it indispensable for advanced trading strategy development.
Example Implementation:
CSV data is transformed into Pine Script series using generated functions.
Multiple CSV blocks can be managed and parsed, allowing for flexible data series creation.
The library includes comprehensive examples demonstrating the conversion of standard CSV files into functional Pine Script code.
To effectively utilize the CSV Series Library in Pine Script, it is imperative to initially generate the correct data format using the accompanying Python program. Here is a detailed explanation of the necessary steps:
1. Preparing the CSV Data:
The Python script provided with the CSV Series Library is designed to handle CSV files that strictly contain no-space, comma-separated single values. It is crucial that your CSV file adheres to this format to ensure compatibility and correctness of the data processing.
2. Using the Python Program to Generate Data:
Once your CSV file is prepared, you need to use the Python program to convert this file into a format that Pine Script can interpret. The Python script performs several key functions:
Reads the CSV file, ensuring that it matches the required format of no-space, comma-separated values.
Formats the data into blocks, where each block is a string of data that does not exceed a specified character limit (default is 4,000 characters). This helps manage large datasets by breaking them down into manageable chunks.
Wraps these blocks into Pine Script functions, each block being encapsulated in its own function to maintain organization and ease of access.
3. Generating and Managing Multiple Libraries:
If the data from your CSV file exceeds the Pine Script or platform limits (e.g., too many characters for a single script), the Python script can split this data into multiple blocks across several files.
4. Creating a Pine Script Library:
After generating the formatted data blocks, you must create a Pine Script library where these blocks are integrated. Each block of data is contained within its function, like my_csv_0(), my_csv_1(), etc. The full_csv() function in Pine Script then dynamically loads and concatenates these blocks to reconstruct the full data series.
5. Exporting the full_csv() Function:
Once your Pine Script library is set up with all the CSV data blocks and the full_csv() function, you export this function from the library. This exported function can then be used in your actual trading projects. It allows Pine Script to access and utilize the entire dataset as if it were a single, continuous series, despite potentially being segmented across multiple library files.
6. Reconstructing the Full Series Using vec :
When your dataset is particularly large, necessitating division into multiple parts, the vec type is instrumental in managing this complexity. Here’s how you can effectively reconstruct and utilize your segmented data:
Definition of vec Type: The vec type in Pine Script is specifically designed to hold a dataset as an array of floats, allowing you to manage chunks of CSV data efficiently.
Creating an Array of vec Instances: Once you have your data split into multiple blocks and each block is wrapped into its own function within Pine Script libraries, you will need to construct an array of vec instances. Each instance corresponds to a segment of your complete dataset.
Using array.from(): To create this array, you utilize the array.from() function in Pine Script. This function takes multiple arguments, each being a vec instance that encapsulates a data block. Here’s a generic example:
vec series_vector = array.from(vec.new(data_block_1), vec.new(data_block_2), ..., vec.new(data_block_n))
In this example, data_block_1, data_block_2, ..., data_block_n represent the different segments of your dataset, each returned from their respective functions like my_csv_0(), my_csv_1(), etc.
Accessing and Utilizing the Data: Once you have your vec array set up, you can access and manipulate the full series through Pine Script functions designed to handle such structures. You can traverse through each vec instance, processing or analyzing the data as required by your trading strategy.
This approach allows Pine Script users to handle very large datasets that exceed single-script limits by segmenting them and then methodically reconstructing the dataset for comprehensive analysis. The vec structure ensures that even with segmentation, the data can be accessed and utilized as if it were contiguous, thus enabling powerful and flexible data manipulation within Pine Script.
Library "csv_series_library"
A library for parsing and handling CSV data to generate series in Pine Script. Generally you will store the csv strings generated from the python code in libraries. It is set up so you can have multiple libraries to store large chunks of data. Just export the full_csv() function for use with this library.
method csv_parse(data)
Namespace types: array
Parameters:
data (array)
method make_series(series_container, start_index)
Namespace types: array
Parameters:
series_container (array)
start_index (int)
Returns: A tuple containing the current value of the series and a boolean indicating if the data is valid.
method make_series(series_vector, start_index)
Namespace types: array
Parameters:
series_vector (array)
start_index (int)
Returns: A tuple containing the current value of the series and a boolean indicating if the data is valid.
vec
A type that holds a dataset as an array of float arrays.
Fields:
data_set (array) : A chunk of csv data. (A float array)
RSI - ARIEIVhe RSI MAPPING - ARIEIV is a powerful technical indicator based on the Relative Strength Index (RSI) combined with moving averages and divergence detection. This indicator is designed to provide a clear view of overbought and oversold conditions, as well as identifying potential reversals and signals for market entries and exits.
Key Features:
Customizable RSI:
The indicator offers flexibility in adjusting the RSI length and data source (closing price, open price, etc.).
The overbought and oversold lines can be customized, allowing the RSI to signal critical market zones according to the trader’s strategy.
RSI-Based Moving Averages (MA):
Users can enable a moving average based on the RSI with support for multiple types such as SMA, EMA, WMA, VWMA, and SMMA (RMA).
For those who prefer Bollinger Bands, there’s an option to use the moving average with standard deviation to detect market volatility.
Divergence Detection:
Detects both regular and hidden divergences (bullish and bearish) between price and RSI, which can indicate potential market reversals.
These divergences can be customized with specific colors for easy identification on the chart, allowing traders to quickly spot significant market shifts.
Zone Mapping:
The script maps zones of buying and selling strength, filling the areas between the overbought and oversold levels with specific colors, highlighting when the market is in extreme conditions.
Strength Tables:
At the end of each session, a table appears on the right side of the chart, displaying the "Buying Strength" and "Selling Strength" based on calculated RSI levels. This allows for quick analysis of the dominant pressure in the market.
Flexible Settings:
Many customization options are available, from adjusting the number of decimal places to the choice of colors and the ability to toggle elements on or off within the chart.
Maximum Bar Range in TicksThis is a simple indicator that gives the maximum range of any bar on the chart in ticks. I found it useful when sizing arrays and it might also be valuable when working out risk parameters.
Fibonacci-Only StrategyFibonacci-Only Strategy
This script is a custom trading strategy designed for traders who leverage Fibonacci retracement levels to identify potential trade entries and exits. The strategy is versatile, allowing users to trade across multiple timeframes, with built-in options for dynamic stop loss, trailing stops, and take profit levels.
Key Features:
Custom Fibonacci Levels:
This strategy calculates three specific Fibonacci retracement levels: 19%, 82.56%, and the reverse 19% level. These levels are used to identify potential areas of support and resistance where price reversals or breaks might occur.
The Fibonacci levels are calculated based on the highest and lowest prices within a 100-bar period, making them dynamic and responsive to recent market conditions.
Dynamic Entry Conditions:
Touch Entry: The script enters long or short positions when the price touches specific Fibonacci levels and confirms the move with a bullish (for long) or bearish (for short) candle.
Break Entry (Optional): If the "Use Break Strategy" option is enabled, the script can also enter positions when the price breaks through Fibonacci levels, providing more aggressive entry opportunities.
Stop Loss Management:
The script offers flexible stop loss settings. Users can choose between a fixed percentage stop loss or an ATR-based stop loss, which adjusts based on market volatility.
The ATR (Average True Range) stop loss is multiplied by a user-defined factor, allowing for tailored risk management based on market conditions.
Trailing Stop Mechanism:
The script includes an optional trailing stop feature, which adjusts the stop loss level as the market moves in favor of the trade. This helps lock in profits while allowing the trade to run if the trend continues.
The trailing stop is calculated as a percentage of the difference between the entry price and the current market price.
Multiple Take Profit Levels:
The strategy calculates seven take profit levels, each at incremental percentages above (for long trades) or below (for short trades) the entry price. This allows for gradual profit-taking as the market moves in the trade's favor.
Each take profit level can be customized in terms of the percentage of the position to be closed, providing precise control over exit strategies.
Strategy Backtesting and Results:
Realistic Backtesting:
The script has been backtested with realistic account sizes, commission rates, and slippage settings to ensure that the results are applicable to actual trading scenarios.
The backtesting covers various timeframes and markets to ensure the strategy's robustness across different trading environments.
Default Settings:
The script is published with default settings that have been optimized for general use. These settings include a 15-minute timeframe, a 1.0% stop loss, a 2.0 ATR multiplier for stop loss, and a 1.5% trailing stop.
Users can adjust these settings to better fit their specific trading style or the market they are trading.
How It Works:
Long Entry Conditions:
The strategy enters a long position when the price touches the 19% Fibonacci level (from high to low) or the reverse 19% level (from low to high) and confirms the move with a bullish candle.
If the "Use Break Strategy" option is enabled, the script will also enter a long position when the price breaks below the 19% Fibonacci level and then moves back up, confirming the break with a bullish candle.
Short Entry Conditions:
The strategy enters a short position when the price touches the 82.56% Fibonacci level and confirms the move with a bearish candle.
If the "Use Break Strategy" option is enabled, the script will also enter a short position when the price breaks above the 82.56% Fibonacci level and then moves back down, confirming the break with a bearish candle.
Stop Loss and Take Profit Logic:
The stop loss for each trade is calculated based on the selected method (fixed percentage or ATR-based). The strategy then manages the trade by either trailing the stop or taking profit at predefined levels.
The take profit levels are set at increments of 0.5% above or below the entry price, depending on whether the position is long or short. The script gradually exits the trade as these levels are hit, securing profits while minimizing risk.
Usage:
For Fibonacci Traders:
This script is ideal for traders who rely on Fibonacci retracement levels to find potential trade entries and exits. The script automates the process, allowing traders to focus on market analysis and decision-making.
For Trend and Swing Traders:
The strategy's flexibility in handling both touch and break entries makes it suitable for trend-following and swing trading strategies. The multiple take profit levels allow traders to capture profits in trending markets while managing risk.
Important Notes:
Originality: This script uniquely combines Fibonacci retracement levels with dynamic stop loss management and multiple take profit levels. It is not just a combination of existing indicators but a thoughtful integration designed to enhance trading performance.
Disclaimer: Trading involves risk, and it is crucial to test this script in a demo account or through backtesting before applying it to live trading. Users should ensure that the settings align with their individual risk tolerance and trading strategy.
Total Bars CalculatorThis indicator simply plots how much bars are available to the user in the respective chart.
For Example if plot shows 5000 , therefore you have total 5000 bars of OHLC available.
Custom Text DisplayThe "Custom Text Display" indicator allows users to display customizable text in a fixed position in the bottom-right corner of their chart. Each text entry can have its own color, which can be set in the indicator's settings. Follow these steps to set up and use the indicator effectively:
Adding the Indicator to Your Chart:
Apply the "Custom Text Display" indicator to your chart from the indicators list.
Configuring Text and Colors:
Open the settings for the indicator.
Enter the desired text for each of the five text fields labeled "Text 1", "Text 2", etc.
Choose a color for each text entry using the color pickers labeled "Color 1", "Color 2", etc.
Selecting the Active Text:
In the indicator settings, find the "Select Active Text" dropdown menu.
This menu offers six options: "0" (None), "1" (Text 1), "2" (Text 2), "3" (Text 3), "4" (Text 4), and "5" (Text 5).
Select the number corresponding to the text you want to activate. Only one text can be active at a time.
Viewing the Active Text on the Chart:
The selected active text will be displayed in the bottom-right corner of the chart with the corresponding background color.
If no text is selected (option "0"), no text will be displayed.
Large Shadow Detector V.1Large Shadow Detector for TradingView
This Pine Script indicator highlights candles with shadows (wicks) exceeding a customizable threshold in points on the XAU/USD chart, specifically for the 1-hour timeframe.
Key Features:
Customizable Shadow Threshold: An input field allows users to set the threshold for detecting large shadows. The default is set to 3400 points.
Upper and Lower Shadows Calculation: The script calculates the upper and lower shadows of each candle.
Condition Checks: It checks if the shadows exceed the defined threshold.
Visual Indicators: Red triangles are plotted above candles with large upper shadows, and green triangles are plotted below candles with large lower shadows.
BB Position CalculatorPosition Size Calculator Instructions
Overview
The Position Size Calculator is designed to help traders automatically determine the appropriate lot size based on the dollar amount they are willing to risk. It includes features for automatic lot sizing, fixed lot risk calculations, take profit calculations (both automatic and fixed), max run-up, and max drawdown. Calculated values are displayed in ticks, points, and USD.
Key Features
• Automatic Lot Sizing: Automatically calculates lot size based on the amount of money you are willing to risk.
• Fixed Lot Risk Calculations: Provides risk calculations for fixed lot sizes.
• Take Profit Calculations: Offers both automatic and fixed take profit calculations.
• Max Run-Up and Max Drawdown: Monitors and displays the maximum run-up and drawdown of your trade.
• Detailed Metrics: Displays all calculated values in ticks, points, and USD.
Setup Instructions
1. Add and Remove for Each Position: The calculator is designed to be added to your chart for each new position. Once your preferences are set the first time, save them as your default to retain your settings for future use.
2. Adding the Indicator to Favorites:
• Use the TradingView keyboard shortcut “/” then type “pos.”
• Use the arrow key to select the Position Size Calculator and press enter.
• Close the indicator selection pop-up.
3. Setting the Trigger Price:
• A blue pop-up labeled “SET TRIGGER PRICE” will appear at the bottom of the chart.
• Click on the chart at the price level where you want to enter the trade.
4. Setting the Stop Loss:
• The pop-up will change to “SET STOP LOSS.”
• Click on the chart at the price level where your stop loss will be set.
5. Setting the Take Profit:
• The pop-up will change to “SET TAKE PROFIT.”
• Click on the chart at the price level where you want to take profit. If you have selected the option to overwrite with a set risk/reward ratio (R:R), the calculation will use this price level.
6. Setting the Trade Window Start:
• The pop-up will change to “SET TRADE WINDOW START.”
• Click on the bar in time where you want the indicator to start monitoring for price to trigger the position.
7. Adjusting the Position:
• Clicking on any part of the indicator will display draggable lines, allowing you to fine-tune the position that was previously plotted by the first four chart clicks.
Additional Notes
• Compatibility: This calculator has only been tested with futures trading.
• Customization: Once your preferences are set, save them as your default to make setup quicker for future trades.
• Support: If you have any questions or feature requests, please feel free to reach out.
1000SATS and ORDI Market Cap RatioSure! Here is a detailed description and usage guide for your TradingView indicator:
### Indicator Description
**Title**: 1000SATS/ORDI Market Cap Ratio
**Description**: The "1000SATS/ORDI Market Cap Ratio" indicator calculates and visualizes the market capitalization ratio between 1000SATS and ORDI. This indicator allows traders and investors to analyze the relative market strength and valuation trends of 1000SATS compared to ORDI over time. By tracking this ratio, users can gain insights into market dynamics and potential trading opportunities between these two assets.
### Indicator Usage
**Purpose**:
- To compare the market capitalizations of 1000SATS and ORDI.
- To identify potential undervaluation or overvaluation of 1000SATS relative to ORDI.
- To assist in making informed trading and investment decisions based on market cap trends.
**How to Use**:
1. **Add the Indicator to Your Chart**:
- Open TradingView and navigate to your chart.
- Click on the "Indicators" button at the top of the chart.
- Select "Pine Editor" and paste the provided script.
- Click "Add to Chart" to apply the indicator.
2. **Interpret the Ratio**:
- The indicator will plot a line representing the ratio of the market capitalization of 1000SATS to ORDI.
- A rising ratio indicates that the market cap of 1000SATS is increasing relative to ORDI, suggesting stronger market performance or higher valuation of 1000SATS.
- A falling ratio indicates that the market cap of 1000SATS is decreasing relative to ORDI, suggesting weaker market performance or lower valuation of 1000SATS.
3. **Analyze Trends**:
- Use the indicator to spot trends and potential reversal points in the market cap ratio.
- Combine the ratio analysis with other technical indicators and chart patterns to enhance your trading strategy.
4. **Set Alerts**:
- Set custom alerts on the ratio to notify you of significant changes or specific thresholds being reached, enabling timely decision-making.
**Example**:
- If the ratio is consistently rising, it may indicate a good opportunity to consider 1000SATS as a stronger investment relative to ORDI.
- Conversely, if the ratio is falling, it may be a signal to reevaluate the strength of 1000SATS compared to ORDI.
**Note**: Always conduct thorough analysis and consider other market factors before making trading decisions based on this indicator.
### Script
```pinescript
//@version=4
study("1000SATS and ORDI Market Cap Ratio", shorttitle="1000SATS/ORDI Ratio", overlay=true)
// Define the circulating supply for ORDI and 1000SATS
ORDI_supply = 21000000 // Circulating supply of ORDI
SATS_1000_supply = 2100000000000 // Circulating supply of 1000SATS
// Fetch the price data for ORDI
ordi_price = security("BINANCE:ORDIUSDT", timeframe.period, close)
// Fetch the price data for 1000SATS
sats_1000_price = security("BINANCE:1000SATSUSDT", timeframe.period, close)
// Calculate the market capitalizations
ordi_market_cap = ordi_price * ORDI_supply
sats_1000_market_cap = sats_1000_price * SATS_1000_supply
// Calculate the market cap ratio
ratio = sats_1000_market_cap / ordi_market_cap
// Plot the ratio
plot(ratio, title="1000SATS/ORDI Market Cap Ratio", color=color.blue, linewidth=2)
```
This description and usage guide should help users understand the purpose and functionality of your indicator, as well as how to effectively apply it in their trading activities on TradingView.