9 and 21 day EMA Crossover StrategyHow It Works:
Buy Signal: When the 9-day EMA crosses above the 21-day EMA, it indicates a potential buy signal.
Sell Signal: When the 9-day EMA crosses below the 21-day EMA, it indicates a potential sell signal.
Indicators and strategies
libTFLibrary "libTF"
libTF: Find higher/lower TF automatically
This library to find higher/lower TF from current timeframe(timeframe.period) for Pine Script version6(or higher).
Basic Algorithm
Using a timeframe scale Array and timeframe.in_seconds() function to find higher/lower timeframe.
Return value is na if could not find TF in the timeframe scale.
The timeframe scale could be changed by the parameter 'scale'(CSV).
How to use
1. Set higher/lower TF
higher()/lower() function returns higher/lower TF.
Default timeframe scale is "1, 5, 15, 60, 240, 1D, 1M, 3M, 12M".
example:
htf1 = higher()
htf2 = higher(htf1)
ltf1 = lower()
ltf2 = lower(ltf1)
2. Set higher/lower TF using your timeframe scale
The timeframe scale could be changed by the parameter.
example:
myscale="1,60,1D,1M,12M"
htf1 = higher(timeframe.period,myscale)
htf2 = higher(htf1,myscale)
ltf1 = lower(timeframe.period,myscale)
ltf2 = lower(ltf1,myscale)
3. How to use with request.*() function
na value is set if no higher/lower TF in timeframe scale.
It returns current timeframe's value, when na value as timeframe parameter in request.*().
As bellow, if it should be na when timeframe is na.
example:
return_value_request_htf1 = na(htf1)?na:request.security(syminfo.tickerid,htf1,timeframe.period)
return_value_request_ltf1 = na(ltf1)?na:request.security(syminfo.tickerid,ltf1,timeframe.period)
higher(tf, scale)
higher: find higher TF from TF string.
Parameters:
tf (string) : default value is timeframe.period.
scale (string) : TF scale in CSV. default is "1,5,15,60,240,1D,1W,1M,3M,12M".
Returns: higher TF string.
lower(tf, scale)
lower: find lower TF from TF string.
Parameters:
tf (string) : default value is timeframe.period.
scale (string) : TF scale in CSV. defalut is "1,5,15,60,240,1D,1W,1M,3M,12M".
Returns: lower TF string.
Dynamic Spot vs Perp Spread### **Description for TradingView Publication**
---
**Dynamic Spot vs Perp Spread**
(For USDT-Spot and USDT.P-Perp)
Summary of Usefulness:
This indicator is a valuable tool for traders who want to monitor and capitalize on the relationship between spot and perpetual futures (perp) prices. When the spot price exceeds the perp price, it's often a leading signal that the perp price will follow, creating potential trading opportunities. While this behavior doesn't happen every time, divergences between spot and perp prices can frequently signal significant market movements.
What it Does:
This indicator calculates and displays the price spread (percentage difference) between the spot price and perpetual futures (perp) price of a cryptocurrency asset. It dynamically adjusts to the instrument being viewed, ensuring that spot dominance (spot price higher) is plotted above the zero line and perp dominance (perp price higher) is plotted below the zero line. Additionally, the indicator accounts for symbols with multipliers (e.g., `1000SHIBUSDT.P`) to ensure accurate calculations.
Key features include:
- Automatic symbol detection and adjustment for Spot/Perp pairs.
- Dynamic handling of price multipliers for assets with prefixes like `1000`.
- Visualization of spread with a histogram and optional smoothing using an EMA (Exponential Moving Average).
- Configurable alerts for significant spread changes and spread flips.
- No repainting: the indicator uses the `barmerge.lookahead_off` setting to ensure stable, non-repainting values.
---
### **How to Use**
1. **Add the Indicator:**
- Search for "Dynamic Spot vs Perp Spread" in the TradingView Indicators library and add it to your chart.
2. **Understand the Visualization:**
- A positive spread (green histogram) indicates that the spot price is higher than the perp price (spot dominance).
- A negative spread (red histogram) indicates that the perp price is higher than the spot price (perp dominance).
3. **Customize Settings:**
- **EMA Length:** Use the input field to smooth the spread data over a chosen number of periods.
- **Alert Threshold:** Set a threshold to receive alerts when the spread exceeds a specific percentage.
4. **Receive Alerts:**
- Enable alerts for spread flips (when dominance shifts between spot and perp) or when the spread exceeds the defined threshold.
5. **Use Case Examples:**
- **Spot vs. Perp Arbitrage:** Traders can monitor significant deviations between spot and perp prices to identify potential arbitrage opportunities.
- **Market Sentiment Analysis:** Persistent spot dominance may indicate stronger buying interest in the spot market, while perp dominance may suggest futures market speculation.
---
### **Repainting Behavior**
This indicator **does not repaint** because it uses `barmerge.lookahead_off` for all calculations, ensuring that data from the comparison symbol (spot or perp) is locked to the currently completed candle. This means the values plotted and alerts triggered are reliable and do not change retrospectively.
Repainting occurs when an indicator uses future-looking or incomplete data for calculations. By design, this indicator avoids such practices, making it suitable for live trading and analysis.
---
Relative Strength vs SPX
This indicator calculates the ratio of the current chart's price to the S&P 500 Index (SPX), providing a measure of the stock's relative strength compared to the broader market.
Key Features:
Dynamic High/Low Detection: Highlights periods when the ratio makes a new high (green) or a new low (red) based on a user-defined lookback period.
Customizable Lookback: The lookback period for detecting highs and lows can be adjusted in the settings for tailored analysis.
Visual Overlay: The ratio is plotted in a separate pane, allowing easy comparison of relative strength trends.
This tool is useful for identifying stocks outperforming or underperforming the S&P 500 over specific timeframes.
Simplified Momentum ScoreIndicator Name: Simplified Momentum Score
Description:
The Simplified Momentum Score indicator calculates the normalized price momentum of an asset over a user-defined period (e.g., 30 days). It provides a single actionable score between 0 and 1, making it easy to compare the relative strength of different tokens or assets:
1: Strongest momentum (best performer).
0: Weakest momentum (worst performer).
How to Use:
Apply this indicator to any chart in TradingView.
Use the normalized score to rank tokens or assets:
Closer to 1: Indicates strong recent price performance.
Closer to 0: Indicates weak recent price performance.
Customize the momentum period to match your trading strategy.
This tool is ideal for quick comparative analysis of multiple tokens to identify top-performing assets. Keep it simple, actionable, and effective! 🚀
Stock vs Sector Comparison with HighlightsThis graph is meant as a support to select a stock that is expected to perform better than the sector.
The graph is based on weekly chart. So this is a medium / long term strategy.
How is expected to be used: when the stock has under performed the sector for some time, there is a natural tendence that it will catch up with the sector again. So, for example, if the color change from green to red, you should consider find another stock in the sector. If the stock looses the green color, but is not red yet, you should wait. And vice versa if you start with red. However, life is not that simple, as you can get fake signal. To mitigate this problem, you can adjust the threshold in the input setting, so just go for the signal after x weeks over/underperforming. You also need remember to select the sector in the settings, as the sector is not give automatically when you select the stock.
Below the sectors used:
Sector Name Ticker
S&P 500 (Market Index) SPY
Technology XLK
Financials XLF
Consumer Discretionary XLY
Industrials XLI
Health Care XLV
Consumer Staples XLP
Energy XLE
Utilities XLU
Communication Services XLC
Real Estate XLRE
Materials XLB
MadTrend [InvestorUnknown]The MadTrend indicator is an experimental tool that combines the Median and Median Absolute Deviation (MAD) to generate signals, much like the popular Supertrend indicator. In addition to identifying Long and Short positions, MadTrend introduces RISK-ON and RISK-OFF states for each trade direction, providing traders with nuanced insights into market conditions.
Core Concepts
Median and Median Absolute Deviation (MAD)
Median: The middle value in a sorted list of numbers, offering a robust measure of central tendency less affected by outliers.
Median Absolute Deviation (MAD): Measures the average distance between each data point and the median, providing a robust estimation of volatility.
Supertrend-like Functionality
MadTrend utilizes the median and MAD in a manner similar to how Supertrend uses averages and volatility measures to determine trend direction and potential reversal points.
RISK-ON and RISK-OFF States
RISK-ON: Indicates favorable conditions for entering or holding a position in the current trend direction.
RISK-OFF: Suggests caution, signaling RISK-ON end and potential trend weakening or reversal.
Calculating MAD
The mad function calculates the median of the absolute deviations from the median, providing a robust measure of volatility.
// Function to calculate the Median Absolute Deviation (MAD)
mad(series float src, simple int length) =>
med = ta.median(src, length) // Calculate median
abs_deviations = math.abs(src - med) // Calculate absolute deviations from median
ta.median(abs_deviations, length) // Return the median of the absolute deviations
MADTrend Function
The MADTrend function calculates the median and MAD-based upper (med_p) and lower (med_m) bands. It determines the trend direction based on price crossing these bands.
MADTrend(series float src, simple int length, simple float mad_mult) =>
// Calculate MAD (volatility measure)
mad_value = mad(close, length)
// Calculate the MAD-based moving average by scaling the price data with MAD
median = ta.median(close, length)
med_p = median + (mad_value * mad_mult)
med_m = median - (mad_value * mad_mult)
var direction = 0
if ta.crossover(src, med_p)
direction := 1
else if ta.crossunder(src, med_m)
direction := -1
Trend Direction and Signals
Long Position (direction = 1): When the price crosses above the upper MAD band (med_p).
Short Position (direction = -1): When the price crosses below the lower MAD band (med_m).
RISK-ON: When the price moves further in the direction of the trend (beyond median +- MAD) after the initial signal.
RISK-OFF: When the price retraces towards the median, signaling potential weakening of the trend.
RISK-ON and RISK-OFF States
RISK-ON LONG: Price moves above the upper band after a Long signal, indicating strengthening bullish momentum.
RISK-OFF LONG: Price falls back below the upper band, suggesting potential weakness in the bullish trend.
RISK-ON SHORT: Price moves below the lower band after a Short signal, indicating strengthening bearish momentum.
RISK-OFF SHORT: Price rises back above the lower band, suggesting potential weakness in the bearish trend.
Picture below show example RISK-ON periods which can be identified by “cloud”
Note: Highlighted areas on the chart indicating RISK-ON and RISK-OFF periods for both Long and Short positions.
Implementation Details
Inputs and Parameters:
Source (input_src): The price data used for calculations (e.g., close, open, high, low).
Median Length (length): The number of periods over which the median and MAD are calculated.
MAD Multiplier (mad_mult): Determines the distance of the upper and lower bands from the median.
Calculations:
Median and MAD are recalculated each period based on the specified length.
Upper (med_p) and Lower (med_m) Bands are computed by adding and subtracting the scaled MAD from the median.
Visual representation of the indicator on a price chart:
Backtesting and Performance Metrics
The MadTrend indicator includes a Backtesting Mode with a performance metrics table to evaluate its effectiveness compared to a simple buy-and-hold strategy.
Equity Calculation:
Calculates the equity curve based on the signals generated by the indicator.
Performance Metrics:
Metrics such as Mean Returns, Standard Deviation, Sharpe Ratio, Sortino Ratio, and Omega Ratio are computed.
The metrics are displayed in a table for both the strategy and the buy-and-hold approach.
Note: Due to the use of labels and plot shapes, automatic chart scaling may not function ideally in Backtest Mode.
Alerts and Notifications
MadTrend provides alert conditions to notify traders of significant events:
Trend Change Alerts
RISK-ON and RISK-OFF Alerts - Provides real-time notifications about the RISK-ON and RISK-OFF states for proactive trade management.
Customization and Calibration
Default Settings: The provided default settings are experimental and not optimized. They serve as a starting point for users.
Parameter Adjustment: Traders are encouraged to calibrate the indicator's parameters (e.g., length, mad_mult) to suit their specific trading style and the characteristics of the asset being analyzed.
Source Input: The indicator allows for different price inputs (open, high, low, close, etc.), offering flexibility in how the median and MAD are calculated.
Important Notes
Market Conditions: The effectiveness of the MadTrend indicator can vary across different market conditions. Regular calibration is recommended.
Backtest Limitations: Backtesting results are historical and do not guarantee future performance.
Risk Management: Always apply sound risk management practices when using any trading indicator.
Mean Price
^^ Plotting switched to Line.
This method of financial time series (aka bars) downsampling is literally, naturally, and thankfully the best you can do in terms of maximizing info gain. You can finally chill and feed it to your studies & eyes, and probably use nothing else anymore.
(HL2 and occ3 also have use cases, but other aggregation methods? Not really, even if they do, the use cases are ‘very’ specific). Tho in order to understand why, you gotta read the following wall, or just believe me telling you, ‘I put it on my momma’.
The true story about trading volumes and why this is all a big misdirection
Actually, you don’t need to be a quant to get there. All you gotta do is stop blindly following other people’s contextual (at best) solutions, eg OC2 aggregation xD, and start using your own brain to figure things out.
Every individual trade (basically an imprint on 1D price space that emerges when market orders hit the order book) has several features like: price, time, volume, AND direction (Up if a market buy order hits the asks, Down if a market sell order hits the bids). Now, the last two features—volume and direction—can be effectively combined into one (by multiplying volume by 1 or -1), and this is probably how every order matching engine should output data. If we’re not considering size/direction, we’re leaving data behind. Moreover, trades aren’t just one-price dots all the time. One trade can consume liquidity on several levels of the order book, so a single trade can be several ticks big on the price axis.
You may think now that there are no zero-volume ticks. Well, yes and no. It depends on how you design an exchange and whether you allow intra-spread trades/mid-spread trades (now try to Google it). Intra-spread trades could happen if implemented when a matching engine receives both buy and sell orders at the same microsecond period. This way, you can match the orders with each other at a better price for both parties without even hitting the book and consuming liquidity. Also, if orders have different sizes, the remaining part of the bigger order can be sent to the order book. Basically, this type of trade can be treated as an OTC trade, having zero volume because we never actually hit the book—there’s no imprint. Another reason why it makes sense is when we think about volume as an impact or imbalance act, and how the medium (order book in our case) responds to it, providing information. OTC and mid-spread trades are not aggressive sells or buys; they’re neutral ticks, so to say. However huge they are, sometimes many blocks on NYSE, they don’t move the price because there’s no impact on the medium (again, which is the order book)—they’re not providing information.
... Now, we need to aggregate these trades into, let’s say, 1-hour bars (remember that a trade can have either positive or negative volume). We either don’t want to do it, or we don’t have this kind of information. What we can do is take already aggregated OHLC bars and extract all the info from them. Given the market is fractal, bars & trades gotta have the same set of features:
- Highest & lowest ticks (high & low) <- by price;
- First & last ticks (open & close) <- by time;
- Biggest and smallest ticks <- by volume.*
*e.g., in the array ,
2323: biggest trade,
-1212: smallest trade.
Now, in our world, somehow nobody started to care about the biggest and smallest trades and their inclusion in OHLC data, while this is actually natural. It’s the same way as it’s done with high & low and open & close: we choose the minimum and maximum value of a given feature/axis within the aggregation period.
So, we don’t have these 2 values: biggest and smallest ticks. The best we can do is infer them, and given the fact the biggest and smallest ticks can be located with the same probability everywhere, all we can do is predict them in the middle of the bar, both in time and price axes. That’s why you can see two HL2’s in each of the 3 formulas in the code.
So, summed up absolute volumes that you see in almost every trading platform are actually just a derivative metric, something that I call Type 2 time series in my own (proprietary ‘for now’) methods. It doesn’t have much to do with market orders hitting the non-uniform medium (aka order book); it’s more like a statistic. Still wanna use VWAP? Ok, but you gotta understand you’re weighting Type 1 (natural) time series by Type 2 (synthetic) ones.
How to combine all the data in the right way (khmm khhm ‘order’)
Now, since we have 6 values for each bar, let’s see what information we have about them, what we don’t have, and what we can do about it:
- Open and close: we got both when and where (time (order) and price);
- High and low: we got where, but we don’t know when;
- Biggest & smallest trades: we know shit, we infer it the way it was described before.'
By using the location of the close & open prices relative to the high & low prices, we can make educated guesses about whether high or low was made first in a given bar. It’s not perfect, but it’s ultimately all we can do—this is the very last bit of info we can extract from the data we have.
There are 2 methods for inferring volume delta (which I call simply volume) that are presented everywhere, even here on TradingView. Funny thing is, this is actually 2 parts of the 1 method. I wonder how many folks see through it xD. The same method can be used for both inferring volume delta AND making educated guesses whether high or low was made first.
Imagine and/or find the cases on your charts to understand faster:
* Close > open means we have an up bar and probably the volume is positive, and probably high was made later than low.
* Close < open means we have a down bar and probably the volume is negative, and probably low was made later than high.
Now that’s the point when you see that these 2 mentioned methods are actually parts of the 1 method:
If close = open, we still have another clue: distance from open/close pair to high (HC), and distance from open/close pair to low (LC):
* HC < LC, probably high was made later.
* HC > LC, probably low was made later.
And only if close = open and HC = LC, only in this case we have no clue whether high or low was made earlier within a bar. We simply don’t have any more information to even guess. This bar is called a neutral bar.
At this point, we have both time (order) and price info for each of our 6 values. Now, we have to solve another weighted average problem, and that’s it. We’ll weight prices according to the order we’ve guessed. In the neutral bar case, open has a weight of 1, close has a weight of 3, and both high and low have weights of 2 since we can’t infer which one was made first. In all cases, biggest and smallest ticks are modeled with HL2 and weighted like they’re located in the middle of the bar in a time sense.
P.S.: I’ve also included a "robust" method where all the bars are treated like neutral ones. I’ve used it before; obviously, it has lesser info gain -> works a bit worse.
Cryptocurrency StrengthMulti-Currency Analysis: Monitor up to 19 different currencies simultaneously, including major pairs like USD, EUR, JPY, and GBP, as well as emerging market currencies such as CNY, INR, and BRL.
Customizable Display: Easily toggle the visibility of each currency and personalize their colors to suit your preferences, allowing for a tailored analysis experience.
Real-Time Strength Measurement: The indicator calculates and displays the relative strength of each currency in real-time, helping you identify potential trends and trading opportunities.
Clear Visual Representation: With color-coded lines and a dynamic legend, the indicator presents complex currency relationships in an easy-to-understand format.
Advantages
Comprehensive Market View: Gain insights into the broader forex market dynamics by analyzing multiple currencies at once.
Trend Identification: Quickly spot strong and weak currencies, aiding in the identification of potential trending pairs.
Divergence Detection: Use the indicator to identify divergences between currency strength and price action, potentially signaling reversals or continuation patterns.
Flexible Time Frames: Apply the indicator across various time frames to align with your trading strategy, from intraday to long-term analysis.
Enhanced Decision Making: Make more informed trading decisions by understanding the relative strength of currencies involved in your trades.
Unique Qualities
TSI-Based Calculations: Utilizes the True Strength Index for a more nuanced and responsive measure of currency strength compared to simple price-based indicators.
Adaptive Legend: The indicator features a dynamic legend that updates automatically based on the selected currencies, ensuring a clutter-free and relevant display.
Emerging Market Inclusion: Unlike many standard currency strength indicators, this tool includes a wide range of emerging market currencies, providing a truly global perspective.
Whether you're a seasoned forex trader or just starting out, this Currency Strength Indicator offers valuable insights that can complement your existing strategy and potentially improve your trading outcomes. Its combination of comprehensive analysis, customization options, and clear visualization makes it an essential tool for navigating the complex world of currency trading.
Diamonds Infiniti - Aynet FiboThe "Diamonds Infiniti - Aynet Fibo" Pine Script combines the geometric visualization of diamond patterns with Fibonacci retracement levels to create an innovative technical indicator for analyzing market trends and potential reversal points. Below is a detailed explanation of the code and its functionality:
Key Features
Dynamic Fibonacci Levels
High and Low Points: The script calculates the highest high and lowest low over a user-defined lookback period (lookback) to establish a price range.
Fibonacci Price Levels: Using the defined price range, the script calculates the Fibonacci retracement levels (0%, 23.6%, 38.2%, 50%, 61.8%, 100%) relative to the low point.
Trend Change Detection
Crossovers and Crossunders: The script monitors whether the closing price crosses over or under the calculated Fibonacci levels. This detection is encapsulated in the isTrendChange function.
Trend Signal: If a trend change occurs at any of the Fibonacci levels (23.6%, 38.2%, 50%, 61.8%), the script flags it as a trend change and stores the bar index of the last signal.
Diamond Pattern Visualization
Diamond Construction: The drawDiamond function draws a diamond shape at a given bar index using a central price, a top price, and a bottom price.
Trigger for Drawing Diamonds: When a trend change is detected, the script draws two diamonds—one on the left and one on the right—connected by a central line. The diamonds are based on the calculated price range (price_range) and a user-defined pattern height (patternHeight).
Fibonacci Level Visualization
Overlay of Fibonacci Levels: The script plots the calculated Fibonacci levels (23.6%, 38.2%, 50%, 61.8%) on the chart as dotted lines for easier visualization.
Scientific and Trading Use Cases
Trend Visualization:
The diamond pattern visually highlights trend changes around key Fibonacci retracement levels, providing traders with clear indicators of potential reversal zones.
Support and Resistance Zones:
Fibonacci retracement levels are widely recognized as key support and resistance zones. Overlaying these levels helps traders anticipate price behavior in these areas.
Adaptive Trading:
By dynamically recalculating Fibonacci levels and diamond patterns based on the most recent price range, the script adapts to changing market conditions.
Possible Enhancements
Multi-Timeframe Support:
Extend the script to calculate Fibonacci levels and diamond patterns across multiple timeframes for broader market analysis.
Alerts:
Add alerts for when the price crosses specific Fibonacci levels or when a new diamond pattern is drawn.
Additional Patterns:
Include other geometric patterns like triangles or rectangles for further trend analysis.
This script is a powerful visualization tool that combines Fibonacci retracement with unique diamond patterns. It simplifies complex price movements into easily interpretable signals, making it highly effective for both novice and experienced traders.
Universal Estimated Funding RateDescription:
This indicator calculates an estimated funding rate for perpetual futures contracts on Binance. The funding rate is derived from the premium index, reflecting the difference between the perpetual futures price and the spot market price, with an assumed constant interest rate.
Key Features:
Dynamic Symbol Detection: Automatically adapts to the base and quote currencies of the current chart, making it compatible with most Binance trading pairs that support both spot and perpetual markets.
Customizable Timeframes: Supports multiple timeframes, with a default recommendation of 4 hours to align with Binance's funding intervals.
Real-Time Data: Fetches live spot and perpetual prices to calculate the premium index and estimate funding rates in real time.
Error Handling: Displays alerts and highlights invalid data if the pair lacks spot or perpetual market information, ensuring clarity for the user.
Use Case:
This indicator is designed to help traders:
Track market sentiment through funding rates.
Identify opportunities for arbitrage or hedging between spot and perpetual markets.
Monitor trends in funding rates to complement technical analysis and refine entry/exit decisions.
How It Works:
The script dynamically identifies the spot and perpetual futures symbols for the selected chart.
It calculates the premium index as the percentage difference between the perpetual and spot prices.
Combines the premium index with an assumed interest rate (default: 0.01% per 8 hours) to estimate the funding rate.
How to Use:
Apply the indicator to any Binance trading pair chart.
Set the timeframe to align with your trading strategy (e.g., 4-hour for swing trading or 5-minute for scalping).
Observe the plotted funding rate to assess market sentiment:
Positive values indicate a long bias (longs pay shorts).
Negative values indicate a short bias (shorts pay longs).
Important Notes:
This is an estimated funding rate based on available data. For exact values, refer to Binance directly.
Funding rates are updated every 8 hours on Binance, so aligning with 4-hour charts is optimal.
Ensure both spot and perpetual data are available for the chosen pair.
This indicator is open-source and serves as a valuable tool for traders seeking deeper insights into funding dynamics on Binance. Happy trading! 🚀
HMA Gaussian Volatility AdjustedOverview
The "HMA Gaussian Volatility Adjusted" indicator introduces a unique combination of HMA smoothing with a Gaussian filter and two components to measure volatility (Average True Range (ATR) and Standard Deviation (SD)). This tool provides traders with a stable and accurate measure of price trends by integrating a Gaussian Filter smoothed using HMA with a customized calculation of volatility. This innovative approach allows for enhanced sensitivity to market fluctuations while filtering out short-term price noise.
Technical Composition and Calculation
The "HMA Gaussian Volatility Adjusted" indicator incorporates HMA smoothing and dynamic standard deviation calculations to build upon traditional volatility measures.
HMA & Gaussian Smoothing:
HMA Calculation (HMA_Length): The script applies a Hull Moving Average (HMA) to smooth the price data over a user-defined period, reducing noise and helping focus on broader market trends.
Gaussian Filter Calculation (Length_Gaussian): The smoothed HMA data is further refined by putting it into a Gaussian filter to incorporate a normal distribution.
Volatility Measurement:
ATR Calculation (ATR_Length, ATR_Factor): The indicator incorporates the Average True Range (ATR) to measure market volatility. The user-defined ATR multiplier is applied to this value to calculate upper and lower trend bands around the Gaussian, providing a dynamic measure of potential price movement based on recent volatility.
Standard Deviation Calculation (SD_Length): The script calculates the standard deviation of the price over a user-defined length, providing another layer of volatility measurement. The upper and lower standard deviation bands (SDD, SDU) act as additional indicators of price extremes.
Momentum Calculation & Scoring
When the indicator signals SHORT:
Diff = Price - Upper Boundary of the Standard Deviation (calculated on a Gaussian filter).
When the indicator signals LONG:
Diff = Price - Upper Boundary of the ATR (calculated on a Gaussian filter).
The calculated Diff signals how close the indicator is to changing trends. An EMA is applied to the Diff to smooth the data. Positive momentum occurs when the Diff is above the EMA, and negative momentum occurs when the Diff is below the EMA.
Trend Detection
Trend Logic: The indicator uses the calculated bands to identify whether the price is moving within or outside the standard deviation and ATR bands. Crosses above or below these bands, combined with positive/negative momentum, signals potential uptrends or downtrends, offering traders a clear view of market direction.
Features and User Inputs
The "HMA Gaussian Volatility Adjusted" script offers a variety of user inputs to customize the indicator to suit traders' styles and market conditions:
HMA Length: Allows traders to adjust the sensitivity of the HMA smoothing to control the amount of noise filtered from the price data.
Gaussian Length: Users can define the length at which the Gaussian filter is applied.
ATR Length and Multiplier: These inputs let traders fine-tune the ATR calculation, affecting the size of the dynamic upper and lower bands to adjust for price volatility.
Standard Deviation Length: Controls how the standard deviation is calculated, allowing further customization in detecting price volatility.
EMA Confluence: This input lets traders determine the length of the EMA used to calculate price momentum.
Type of Plot Setting: Allows users to determine how the indicator signal is plotted on the chart (Background color, Trend Lines, BOTH (backgroung color and Trend Lines)).
Transparency: Provides users with customization of the background color's transparency.
Color Long/Short: Offers users the option to choose their preferred colors for both long and short signals.
Summary and Usage Tips
The "HMA Gaussian Volatility Adjusted" indicator is a powerful tool for traders looking to refine their analysis of market trends and volatility. Its combination of HMA smoothing, Gaussian filtering, and standard deviation analysis provides a nuanced view of market movements by incorporating various metrics to determine direction, momentum, and volatility. This helps traders make better-informed decisions. It's recommended to experiment with the various input parameters to optimize the indicator for specific needs.
Fibonacci Renko Trend - AynetThe "Fibonacci Renko Trend - Aynet" Pine Script combines the Renko charting technique with Fibonacci retracement levels to create a highly customizable and adaptive trend-following tool. Below is a detailed explanation of the script and its components:
Scientific and Trading Applications
Noise Reduction:
By using Renko charts, the script filters out time-based noise and focuses solely on price movement, making it ideal for trend-following strategies.
Adaptability:
The ATR-based box size ensures that the Renko blocks automatically adjust to market volatility, making the tool versatile for different market conditions and asset classes.
Fibonacci-Based Decision Making:
The integration of Fibonacci retracement levels provides a structured framework for identifying key support and resistance levels. Traders can use these levels to anticipate price reversals or continuations.
Visualization:
The color-coded Renko blocks allow traders to quickly identify trends and potential reversals without additional indicators, improving decision-making efficiency.
Possible Improvements
Signal Generation:
Add entry and exit signals when price crosses significant Fibonacci levels or when a trend reversal is detected.
Multi-Timeframe Support:
Extend the script to compute Renko levels and Fibonacci ratios for multiple timeframes simultaneously.
Alerts:
Implement alert notifications for key events, such as trend changes or Fibonacci level breaches.
This script is a robust tool for traders looking to combine the simplicity of Renko charts with the analytical power of Fibonacci retracement levels. It offers a clear visualization of price trends and potential reversal points, making it suitable for both novice and experienced traders.
Average High-Low Multi Time Frame Lines SunilTitle: Multi-Timeframe Average High-Low Levels with Custom Timeframes
Description:
This indicator calculates the average of high and low prices across up to four customizable timeframes. By default, it includes 30 minutes, 1 hour, 3 hours, and 1 day, but you can modify these directly in the input settings to suit your trading strategy.
Features:
Plots average high-low levels for selected timeframes with distinct colors.
Highlights buy zones (green) when the price is above all levels and sell zones (red) when the price is below all levels.
Marks areas where all levels align with a subtle blue background.
Use this tool to identify key levels and potential trading opportunities across multiple timeframes at a glance!
ATR-based TP/SL with Dynamic RREnglish
This indicator combines the power of the Average True Range (ATR) with dynamic calculations for Take Profit (TP) and Stop Loss (SL) levels, offering a clear visualization of trading opportunities and their respective Risk-Reward Ratios (RRR).
Features:
Dynamic TP/SL Calculation:
TP and SL levels are derived using user-defined ATR multipliers for precise positioning.
Multipliers are flexible, allowing traders to adjust according to their strategies.
Risk-Reward Ratio (RRR):
Automatically calculates and displays the RRR for each trade signal.
Helps traders quickly assess if a trade aligns with their risk management plan.
Entry Conditions:
Buy signals occur when the closing price crosses above the 20-period Simple Moving Average (SMA).
Sell signals occur when the closing price crosses below the 20-period SMA.
Visual Aids:
Red and green lines indicate Stop Loss and Take Profit levels.
Blue and orange labels show the RRR for long and short trades, respectively.
How It Works:
The indicator uses the ATR to calculate TP and SL levels:
TP: Adjusted based on the desired Risk-Reward Ratio (RR).
SL: Proportional to the ATR multiplier.
Entry signals are plotted with "BUY" or "SELL" markers, while the respective TP/SL levels are drawn as horizontal lines.
Why Use This Indicator?
Perfect for traders who value precise risk management.
Helps identify trades with favorable RRR (e.g., greater than 1.5 or 2.0).
Ideal for swing traders, day traders, and scalpers looking to automate their decision-making process.
Customization:
ATR Length: Control the sensitivity of ATR-based calculations.
ATR Multipliers: Set the TP and SL distances relative to the ATR.
Desired RRR: Define the risk/reward ratio you aim to achieve.
Important Notes:
The indicator does not place trades automatically; it is for visual and analytical purposes.
Always backtest and combine it with additional analysis for best results.
French
Cet indicateur combine la puissance de l’Average True Range (ATR) avec des calculs dynamiques pour les niveaux de Take Profit (TP) et de Stop Loss (SL), tout en offrant une visualisation claire des opportunités de trading et de leurs Ratios Risque/Rendement (RRR).
Fonctionnalités :
Calcul Dynamique des TP/SL :
Les niveaux de TP et SL sont calculés à l'aide de multiplicateurs ATR définis par l’utilisateur pour une position précise.
Les multiplicateurs sont personnalisables pour s'adapter à votre stratégie de trading.
Ratio Risque/Rendement (RRR) :
Calcule et affiche automatiquement le ratio RRR pour chaque signal de trade.
Permet aux traders d’évaluer rapidement si un trade correspond à leur plan de gestion des risques.
Conditions d'Entrée :
Les signaux d'achat apparaissent lorsque le prix de clôture traverse au-dessus de la moyenne mobile simple (SMA) à 20 périodes.
Les signaux de vente apparaissent lorsque le prix de clôture traverse en dessous de la SMA à 20 périodes.
Aides Visuelles :
Lignes rouges et vertes pour indiquer les niveaux de Stop Loss et de Take Profit.
Étiquettes bleues et orange pour afficher le RRR des trades longs et courts, respectivement.
Comment Cela Fonctionne :
L'indicateur utilise l’ATR pour calculer les niveaux TP et SL :
TP : Calculé dynamiquement en fonction du ratio risque/rendement souhaité (RRR).
SL : Proportionnel au multiplicateur ATR défini par l’utilisateur.
Les signaux d’entrée sont représentés par des étiquettes "BUY" ou "SELL", tandis que les niveaux de TP/SL sont tracés sous forme de lignes horizontales.
Pourquoi Utiliser Cet Indicateur ?
Idéal pour les traders soucieux d’une gestion rigoureuse des risques.
Identifie les opportunités de trades avec des RRR favorables (par exemple, supérieurs à 1.5 ou 2.0).
Convient aux swing traders, day traders et scalpeurs souhaitant automatiser leur processus de décision.
Personnalisation :
Longueur de l’ATR : Contrôlez la sensibilité des calculs basés sur l’ATR.
Multiplicateurs ATR : Ajustez les distances TP et SL par rapport à l’ATR.
Ratio RRR souhaité : Définissez le ratio risque/rendement que vous visez.
Remarques Importantes :
Cet indicateur n’exécute pas de trades automatiquement ; il est destiné à un usage visuel et analytique uniquement.
Toujours backtester et combiner avec une analyse supplémentaire pour de meilleurs résultats.
parametre par type de trading:
1. Pour les Scalpers :
Style de trading : Trades rapides sur de petites variations de prix, souvent sur des unités de temps courtes (1 min, 5 min).
Recommandations de paramètres :
ATR Length : 7 (plus court pour réagir rapidement à la volatilité).
Multiplicateur SL : 1.0 (Stop Loss proche pour limiter les pertes).
RR souhaité : 1.5 à 2.0 (bon équilibre entre risque et récompense).
Résultat attendu : Des trades fréquents, avec une probabilité raisonnable de toucher le TP tout en limitant les pertes.
2. Pour les Day Traders :
Style de trading : Trades qui durent plusieurs heures dans la journée, souvent sur des unités de temps moyennes (15 min, 1h).
Recommandations de paramètres :
ATR Length : 14 (standard pour capturer une volatilité modérée).
Multiplicateur SL : 1.5 (Stop Loss à distance raisonnable pour supporter les fluctuations intrajournalières).
RR souhaité : 2.0 à 3.0 (ciblez une bonne récompense par rapport au risque).
Résultat attendu : Moins de trades, mais un RR élevé pour compenser les pertes potentielles.
3. Pour les Swing Traders :
Style de trading : Trades qui durent plusieurs jours, souvent sur des unités de temps longues (4h, 1 jour).
Recommandations de paramètres :
ATR Length : 20 (pour capturer des mouvements de volatilité plus larges).
Multiplicateur SL : 2.0 (Stop Loss large pour supporter des fluctuations importantes).
RR souhaité : 3.0 ou plus (ciblez de gros mouvements de prix).
Résultat attendu : Des trades moins fréquents mais potentiellement très lucratifs.
4. Pour les Actifs Volatils (Crypto, Commodités) :
Problème spécifique : Les actifs volatils ont souvent des mouvements brusques.
Recommandations de paramètres :
ATR Length : 7 ou 10 (plus court pour suivre rapidement les variations).
Multiplicateur SL : 1.5 à 2.0 (assez large pour ne pas être déclenché prématurément).
RR souhaité : 1.5 à 2.0 (favorisez des récompenses réalistes sur des mouvements volatils).
Résultat attendu : Trades qui s’adaptent à la volatilité sans sortir trop tôt.
5. Pour les Marchés Stables (Indices, Actions Blue Chip) :
Problème spécifique : Les mouvements sont souvent lents et prévisibles.
Recommandations de paramètres :
ATR Length : 14 ou 20 (capture une volatilité modérée).
Multiplicateur SL : 1.0 à 1.5 (Stop Loss serré pour maximiser l’efficacité).
RR souhaité : 2.0 à 3.0 (ciblez des ratios plus élevés sur des mouvements moins fréquents).
Résultat attendu : Maximisation des profits sur des tendances claires.
Recommandation Générale :
Si vous ne savez pas par où commencer, utilisez ces paramètres par défaut :
ATR Length : 14
Multiplicateur SL : 1.5
RR souhaité : 2.0
FibRatiosLibrary "FibRatios"
Library with calculation logic for fib retracement, extension and ratios
retracement(a, b, ratio, logScale, precision)
Calculates the retracement for points a, b with given ratio and scale
Parameters:
a (float) : Starting point a
b (float) : Second point b
ratio (float) : Ratio for which we need to calculate retracement c
logScale (bool) : Flag to get calculations in log scale. Default is false
precision (int) : rounding precision. If set to netagive number, round_to_mintick is applied. Default is -1
Returns: retracement point c for points a,b with given ratio and scale
retracementRatio(a, b, c, logScale, precision)
Calculates the retracement ratio for points a, b, c with given scale
Parameters:
a (float) : Starting point a
b (float) : Second point b
c (float) : Retracement point. c should be placed between a and b
logScale (bool) : Flag to get calculations in log scale. Default is false
precision (int) : rounding precision. If set to netagive number, round_to_mintick is applied. Default is 3
Returns: retracement ratio for points a,b,c on given scale
extension(a, b, c, ratio, logScale, precision)
Calculates the extensions for points a, b, c with given ratio and scale
Parameters:
a (float) : Starting point a
b (float) : Second point b
c (float) : Retracement point. c should be placed between a and b
ratio (float) : Ratio for which we need to calculate extension d
logScale (bool) : Flag to get calculations in log scale. Default is false
precision (int) : rounding precision. If set to netagive number, round_to_mintick is applied. Default is -1
Returns: extensoin point d for points a,b,c with given ratio and scale
extensionRatio(a, b, c, d, logScale, precision)
Calculates the extension ratio for points a, b, c, d with given scale
Parameters:
a (float) : Starting point a
b (float) : Second point b
c (float) : Retracement point. c should be placed between a and b
d (float) : Extension point. d should be placed beyond a, c. But, can be with b,c or beyond b
logScale (bool) : Flag to get calculations in log scale. Default is false
precision (int) : rounding precision. If set to netagive number, round_to_mintick is applied. Default is 3
Returns: extension ratio for points a,b,c,d on given scale
Currency StrengthThis innovative Currency Strength Indicator is a powerful tool for forex traders, offering a comprehensive and visually intuitive way to analyze the relative strength of multiple currencies simultaneously. Here's what makes this indicator stand out:
Extensive Currency Coverage
One of the most striking features of this indicator is its extensive coverage of currencies. While many similar tools focus on just the major currencies, this indicator includes:
Major currencies: USD, EUR, JPY, GBP, CHF, CAD, AUD, NZD
Additional currencies: CNY, HKD, KRW, MXN, INR, RUB, SGD, TRY, BRL, ZAR, THB
This wide range allows traders to gain insights into a broader spectrum of the forex market, including emerging markets and less commonly traded currencies.
Unique Visual Presentation
The indicator boasts a clear and user-friendly interface:
Each currency is represented by a distinct colored line for easy identification
A legend is prominently displayed at the top of the chart, using color-coded labels for quick reference
Users can customize which currencies to display, allowing for a tailored analysis
This clean, organized presentation enables traders to quickly grasp the relative strengths of different currencies at a glance.
Robust Measurement Methodology
The indicator employs the True Strength Index (TSI) to calculate currency strength, which provides several advantages:
TSI is a momentum oscillator that shows both trend direction and overbought/oversold conditions
It uses two smoothing periods (fast and slow), which helps filter out market noise and provides more reliable signals
The indicator calculates TSI for each currency index (e.g., DXY for USD, EXY for EUR), ensuring a comprehensive strength measurement
By using TSI, this indicator offers a more nuanced and accurate representation of currency strength compared to simpler moving average-based indicators.
Customization and Flexibility
Traders can fine-tune the indicator to suit their needs:
Adjustable TSI parameters (fast and slow periods)
Ability to show/hide specific currencies
Customizable color scheme for each currency line
Practical Applications
This Currency Strength Indicator can be used for various trading strategies:
Identifying potential trend reversals when a currency reaches extreme overbought or oversold levels
Spotting divergences between currency pairs
Confirming trends across multiple timeframes
Enhancing multi-pair trading strategies
By providing a clear, comprehensive, and customizable view of currency strength across a wide range of currencies, this indicator equips traders with valuable insights for making informed trading decisions in the complex world of forex.
30-Minute Candle Strategy30-Minute Candle Trading Strategy
This strategy works on a 30-minute candle timeframe. When a new 30-minute candle opens, the following actions will take place based on the previous 30-minute candle's closing price:
Buy Trade Setup:
If the market opens above the previous 30-minute candle's closing price, a buy trade will be executed immediately at the market price.
The stop-loss will be set at the previous 30-minute candle's closing price.
There will be no fixed target.
The trade will be closed 1 minute before the current 30-minute candle closes, regardless of profit or loss.
Sell Trade Setup:
If a buy trade hits the stop-loss and the market moves below the previous 30-minute candle's closing price, a sell trade will be executed immediately at the market price.
The stop-loss for the sell trade will also be set at the previous 30-minute candle's closing price.
There will be no fixed target.
The trade will be closed 1 minute before the current 30-minute candle closes, regardless of profit or loss.
Procedure:
This process will repeat for every 30-minute candle.
If the market crosses the previous 30-minute candle's closing price to the upside, a buy trade will be executed, and the stop-loss will be set at the previous candle's closing price.
If the market crosses the previous 30-minute candle's closing price to the downside, a sell trade will be executed, and the stop-loss will also be set at the previous candle's closing price.
Each trade will be closed 1 minute before the current candle closes.
Key Points:
This strategy applies to every new 30-minute candle.
The stop-loss will always be based on the previous 30-minute candle's closing price.
If a stop-loss is hit, the strategy will automatically switch to the opposite trade (buy to sell or sell to buy) based on market movement crossing the previous candle's closing price.
This is a repetitive and systematic approach to trading, ensuring the rules are followed for every 30-minute candle.
BTC Seasonality Strategy (Weekly)This strategy identifies potential weekend opportunities in Bitcoin (BTC) markets by leveraging the concept of seasonality, entering a position at a predefined time and day, and exiting at a specified time and day.
Key Features
Customizable Time and Day Selection:
Users can select the entry and exit days and corresponding times (in EST).
Directional Flexibility:
The strategy allows traders to choose between long or short positions.
TradingView Compliance:
The script adheres to TradingView's house rules, avoids overly complex conditions, and provides clear user-configurable inputs.
How It Works
The script determines the current weekday and hour in EST, converting TradingView's UTC time for accurate comparisons.
If the current day and hour match the selected entry conditions, a trade (long or short) is opened.
The position is closed when the current day and hour match the specified exit conditions.
Theoretical Basis
Market Seasonality:
The concept of seasonality in financial markets refers to predictable patterns based on time, such as weekends or specific days of the week. Studies have shown that cryptocurrency markets exhibit unique trading behaviors during weekends due to reduced institutional activity and higher retail participation behavioral Biases**:
Retail traders often dominate weekend markets, potentially causing predictable inefficiencies .
Reverences**
Baur, D. G., Hong, K., & Lee, A. D. (2018). Bitcoin: Medium of exchange or speculative assets? Journal of International Financial Markets, Institutions and Money, 54, 177–189.
Urquhart, A. (2016). The inefficiency of Bitcoin. Economics Letters, 148, 80–82.
M200 MultiplesThis script is designed to analyze price trends using moving averages and their multiples. Here's a brief description:
The script calculates and plots:
The 200-period Simple Moving Average (M200): A commonly used indicator to identify long-term trends.
Additionally, it generates multiple lines based on multipliers of the M200 to visualize potential support and resistance levels:
2x M200: Double the 200-period average.
1.5x M200, 1.68x M200, 2.236x M200, and 2.5x M200: Various multipliers to identify intermediate zones of interest.
Visualization
M200 is plotted in blue
Multipliers of M200 are plotted in gray with varying line widths for distinction.
Use Case
Identify key support and resistance levels derived from long-term moving averages.
Combine trend-following techniques with zone-based price action analysis.
This script works well on the daily time frame.
Alans Date Range CalculatorOverview
Setting a date range for backtesting enables you to evaluate your trading strategy under various market conditions. Traders can test a strategy’s performance during specific periods, such as economic downturns, bull markets, or periods of high volatility. This helps assess the trading strategy’s robustness and adaptability across different scenarios.
Specifying years of data instead of just inputting specific start and end dates offers several advantages:
1. **Consistency**: Using a fixed number of years ensures that the testing period is consistent across different strategies or iterations. This makes it easier to compare performance metrics and draw meaningful conclusions.
2. **Flexibility**: Specifying years allows for automatic adjustment of the start date based on the current date or selected end date. This is particularly useful when new data becomes available or when testing on different assets with varying historical data lengths.
3. **Efficiency**: It simplifies updating and retesting strategies. Instead of recalculating specific start dates each time, traders can quickly adjust the number of years to process, making it easier to test strategies over different timeframes.
4. **Comprehensive Analysis**: Broader timeframes defined by years help you evaluate how your strategy performs over multiple market cycles, providing insights into long-term viability and potential weaknesses.
Defining a date range by specifying years allows for more thorough and systematic backtesting, helping traders develop more reliable and effective trading systems.
Alan's Date Range Calculator: A TradingView Pine Script Indicator
Purpose
This Pine Script indicator calculates and displays a date range for backtesting trading strategies. It allows users to specify the number of years to analyze and an end date, then calculates the corresponding start date. Most importantly, users can copy the inputs and function into their own strategies to quickly add a time span feature for backtesting.
Key Features
User-defined input for the number of years to analyze
Customizable end date with a calendar input
Automatic calculation of the start date
Visual display of both start and end dates on the chart
How It Works
User Inputs
Years of Data to Process: An integer input allowing users to specify the number of years for analysis (default: 20, range: 1-100)
End Date: A calendar input for selecting the end date of the analysis period (default: December 31, 2024)
Date Calculation
The script uses a custom function calcStartDate() to determine the start date. It subtracts the specified number of years from the end date's year and sets the start date to January 1st of that year.
Visual Output
The indicator displays two labels on the chart:
Start Date Label: Shows the calculated start date
End Date Label: Displays the user-specified end date
Both labels are positioned horizontally at the bottom of the chart, with the end date label to the right of the start date label.
Applications
This indicator is particularly useful for traders who want to:
Define specific date ranges for backtesting strategies
Quickly visualize the time span of their analysis
Ensure consistent testing periods across different strategies or assets
Customization
Users can easily adjust the analysis period by changing the number of years or selecting a different end date. This flexibility allows for testing strategies across various market conditions and time frames.
Marcel's Dynamic Profit / Loss Calculator for GoldOverview
This Dynamic Risk / Reward Tool for Gold is designed to help traders efficiently plan and manage their trades in the volatile gold market. This script provides a clear visualisation of trade levels (Entry, Stop Loss, Take Profit) while dynamically calculating potential profit and loss. It ensures gold traders can assess their positions with precision, saving time and improving risk management.
Key Features
1. Trade Level Visualisation:
Plots Entry (Blue), Stop Loss (Red), and Take Profit (Green) lines directly on the chart.
Helps you visualise and confirm trade setups quickly which is good for scalping and day trades.
2. Dynamic Risk and Reward Calculations:
Calculates potential profit and loss in real time based on user-defined inputs such as position size, leverage, and account equity.
Displays a summary panel showing risk/reward metrics directly on the chart.
3. Customisable Settings:
Allows you to adjust key parameters like account equity, position size, leverage, and specific price levels for Entry, Stop Loss, and Take Profit.
Defaults are dynamically generated for convenience but remain fully adjustable for flexibility.
How It Works
The script uses gold-specific conventions (e.g., 1 lot = 100 ounces, 1 pip = 0.01 price change) to calculate accurate risk and reward metrics.
It dynamically positions Stop Loss and Take Profit levels relative to the entry price, based on user-defined or default offsets.
A real-time summary panel is displayed in the bottom-right corner of the chart, showing:
Potential Profit: The monetary value if the Take Profit is hit.
Potential Lo
ss: The monetary value if the Stop Loss is hit.
How to Use It
1. Add the script to your chart on a gold trading pair (e.g., XAUUSD).
2. Input your:
Account equity.
Leverage.
Position size (in lots).
Desired En
try Price (default: current close price).
3. Adjust the Stop Loss and Take Profit levels to your strategy, or let the script use default offsets of:
500 pips below the Entry for Stop Loss.
1000 pips above the Entry for Take Profit.
4. Review the plotted levels and the summary panel to confirm your trade aligns with your risk/reward goals.
Why Use This Tool?
Clarity and Precision:
Provides clear trade visuals and financial metrics for confident decision-making.
Time-Saving:
Automates the calculations needed to evaluate trade risk and reward.
Improved Risk Management:
Ensures you never trade without knowing your exact potential loss and gain.
This script is particularly useful for both novice and experienced traders looking to enhance their risk management and trading discipline in the Gold market. Enjoy clearer trades at speed.