Moneyball EMA-MACD indicator [VinnieTheFish]Summary of the Moneyball EMA-MACD Indicator Script
Author: VinnieTheFish
Purpose:
This indicator helps traders identify trend direction, momentum shifts, and potential trade signals based on EMA and MACD crossovers.
This Pine Script is a custom indicator that combines Exponential Moving Averages (EMAs) and MACD (Moving Average Convergence Divergence) to analyze price trends and momentum. The script uses a custom 9/50 MACD with a 16 smoothing period. The script is written in a way that you can create your own custom MACD settings and create alerts based on those parameters. The chart bars are color coded based on the relative position of the MACD and Signal line primarily for bullish long trade setups.
Bar color coding helps the trader spot potential reversals based on where the price currently resides in relation to the custom 9/50 EMA based MACD and the 16 period smoothing period for the signal line. Indicator also has custom alerts to notify the trader when a potential trade setup exists that correspond with the bar color change.
Question: So why is this called the Moneywell EMA-MACD Indicator?
Answer: In the movie Moneyball the Oakland A's broke down how to win a championship based on data. To make the playoffs you needed so many wins, then broken down by runs and then broken down to base hits. A base hit was good as a walk. With trading often times we look too often for home runs and ignore the importance of getting on base with small wins. This indicator was designed on shorter timeframes to identify those base hits, but can also be adapted to higher timeframes for swing trading.
Key Features:
User Inputs:
Configurable fast and slow lengths for MACD calculation.
Choice between SMA and EMA for oscillator and signal line smoothing.
Customizable signal smoothing length.
EMA Calculation:
Computes 3 EMA, 9 EMA, 20 EMA, and 50 EMA to track short-term and long-term trends.
MACD Calculation:
Computes MACD using either SMA or EMA based on user selection.
Generates the MACD signal line for comparison.
Crossover Conditions:
Detects MACD and Signal line crossovers above and below the zero line.
Identifies price momentum shifts.
Bar Coloring Logic:
Green: MACD is above 0 and above the signal line.
White: MACD is below the signal line.
Orange: MACD is below 0 but above the signal line.
Fuchsia: Bullish EMA 3/9 cross but price is still below the 20/50 EMA.
Alerts for Key Trading Signals:
MACD crossing above/below the zero line.
Signal line crossing above/below the zero line.
MACD reaching new highs/lows.
Alerts for colored bar conditions.
Educational
Candlestick Color Change AlertIt is an alert for change of candlestick color.
Identifies Candle Type
A candle is bullish if the closing price is higher than the opening price.
A candle is bearish if the closing price is lower than the opening price.
Detects a Color Change
The script checks if the current candle is bullish while the previous candle was bearish, or vice versa.
If a change is detected, an alert is triggered.
Triggers an Alert
Users receive an alert notification whenever a candlestick color change occurs.
Alerts can be set for popup, email, mobile push, or webhook notifications.
Visual Highlighting (Optional)
The script can also apply a background color (blue) on the chart to visually mark color changes.
Blackflag FTS (1H Trailing) + MSB-OB FibThis indicator combines a 1-hour trailing stop system with multi-timeframe Fibonacci retracement levels and ZigZag structure detection to assist traders in identifying trend direction and potential reversal zones.
Features:
✅ 1-Hour Trailing Stop: Uses an ATR-based trailing stop mechanism to track trend direction and dynamic support/resistance.
✅ Multi-Timeframe Approach: The trailing stop is calculated on the 1-hour timeframe, while the ZigZag and Fibonacci retracement levels are based on the 15-minute chart.
✅ ZigZag Structure Detection: Helps filter market swings and trend reversals dynamically.
✅ Fibonacci Levels (0.5 & 0.786): Key retracement levels to watch for price reactions.
✅ Alerts for Key Levels: Get notified when the price crosses important levels (1H trailing stop, Fib 0.5, Fib 0.786).
How It Works:
The trailing stop adapts dynamically based on ATR values and determines trend direction.
ZigZag detection filters out minor price movements to highlight major swing points.
Fibonacci levels are calculated based on ZigZag swings, helping traders spot potential reversal zones.
This tool is useful for trend-following traders, breakout traders, and Fibonacci-based strategies.
Let me know if you'd like any modifications! 🚀
Candle Momentum ExhaustionCandle Momentum Exhaustion
The Candle Momentum Exhaustion indicator is designed to help traders spot potential turning points in a trend by identifying when the prevailing momentum may be “running on empty.” The indicator works by comparing the size of each candle’s body (the absolute difference between the open and close) to the average body size over a recent period. When a candle’s body exceeds a user‐defined multiple of this average, it is flagged as an “exhaustion” candle.
• A bullish exhaustion (shown with a red down–facing triangle above the bar) occurs when a very large bullish candle (close > open) is detected, suggesting that buyers may have pushed the price too far and the rally could be near its end.
• A bearish exhaustion (shown with a green up–facing triangle below the bar) occurs when a very large bearish candle (close < open) is detected, implying that selling pressure might be overdone.
These signals can alert you to a potential reversal or consolidation point. The script also includes alert conditions so that you can set up notifications whenever an exhaustion signal is generated.
How It Works
1. Average Candle Body:
The script computes a simple moving average (SMA) of the absolute candle bodies over a user-defined period (default is 14 bars).
2. Exhaustion Candidate:
A candle is flagged as an exhaustion candidate if its body size exceeds the average by more than the set multiplier (default is 2.0).
3. Signal Identification:
• If the exhaustion candle is bullish (close > open), it is marked with a red down–facing triangle above the bar.
• If it is bearish (close < open), it is marked with a green up–facing triangle below the bar.
4. Alerts:
The built-in alertcondition() calls allow you to set alerts (via TradingView’s alert system) so that you can be notified when an exhaustion event occurs.
Risk Disclaimer:
This indicator is provided for educational and informational purposes only and does not constitute financial, investment, or trading advice. Trading and investing involve significant risk, and you should not rely solely on this indicator when making any trading decisions. Past performance is not indicative of future results. Always perform your own due diligence and consult with a qualified financial advisor before making any financial decisions. The creator of this indicator shall not be held responsible for any losses incurred through its use.
US vs EU Interest Rate SpreadThis script plots the difference (Spread) between the US-Interest Rate (Symbol USINTR) and the EU Interest Rate (Symbol: EUINTR) and plots it in a seperate pane. Areas where the background is green are times were the spread was positive (US interest rate higher than EU interest rate), a red background indicates a higher EU interest rate than US interest rate.
OAT Multiple Alert ConditionsOverview:
The OAT Multiple Alert Conditions indicator is designed to enhance TradingView’s alert functionality by allowing users to set multiple conditions for webhook-based alerts. This script enables traders to define up to four independent conditions using different event types (e.g., crossing, greater than, rising, etc.), making it ideal for automated trading strategies and webhook integrations.
Features:
✅ Supports up to 4 independent conditions.
✅ Multiple event types: Crossing, Crossing Up, Crossing Down, Greater Than, Less Than, Rising, Falling.
✅ Choose between value-based or source-based conditions.
✅ Custom timeframes for each condition.
✅ Optional session filtering and expiration settings.
✅ Visual markers for triggered conditions.
✅ Alerts for individual conditions or all conditions being met.
How It Works:
Configure each condition by selecting the event type and input values.
Define whether the alert should trigger on bar close or real-time.
Enable session filtering to limit alerts to specific trading hours.
Set an expiration date for alerts if needed.
Alerts can be sent via TradingView’s webhook feature for automated execution.
Intended Use:
This script is a utility tool for traders using automated strategies with the Options Auto Trader. It does not generate trading signals or provide financial advice. It is designed to enhance alert flexibility and efficiency for trading through webhooks.
License & Compliance:
This script is published under the Mozilla Public License 2.0 and follows TradingView’s guidelines. It does not execute trades but simply provides an enhanced alerting mechanism.
Live Economic CalendarLive Economic Calendar
This TradingView indicator provides real-time economic news events directly on your charts, helping traders stay informed about key market-moving data. Built on the original Forex Factory utility by toodegrees, this version enhances functionality with customizable alerts and improved visualizations.
Key Features:
Real-Time Economic News: Displays upcoming economic events from Forex Factory, categorized by impact level (High, Medium, Low, Holiday).
Custom Alerts: Set alerts before and after news events to stay prepared for market volatility.
Timezone Adjustments: Adjust news event times to match your local timezone for accurate scheduling.
Currency-Specific News: Automatically filters news based on the currency pair you’re viewing, with manual options for specific currencies.
Flexible Display Options: Choose to display news for today, this week, or a custom period. Customize labels, lines, and tables directly on the chart.
Impact Visualization: Visual cues (lines, labels, background shading) for different impact levels to highlight significant market events.
Credits:
• Original Forex Factory Utility by toodegrees
• Alerts and enhancements by Nachodog
This Pine Script™ code is licensed under the Mozilla Public License 2.0: mozilla.org
Dynamic SL - 1 Pip (Up and Down)The Dynamic SL - 1 Pip Up and Down indicator creates two dynamic lines that follow the price at a distance of 1 pip above and below the closing price. This feature can be particularly useful for traders who want to visualize small stop-loss (SL) levels or track price movement in a highly responsive manner.
Unlike traditional stop-loss indicators, this script ensures that the lines only last for 5 seconds, keeping the chart clean and focusing only on the most relevant price movement.
Key Features
✔ Dynamic Stop-Loss Visualization:
The script draws a green line above the price (+1 pip).
A red line below the price (-1 pip) is also drawn.
✔ Auto-Clearing for a Clean Chart:
Each line lasts for 5 seconds only before automatically disappearing.
This prevents unnecessary clutter on the chart and ensures only the latest price movements are visualized.
✔ Adaptable to Multiple Assets:
Automatically calculates the pip size based on the instrument type:
Forex → Uses 0.0001 per pip.
Futures & Stocks → Uses the minimum tick size.
✔ Ideal for High-Frequency Traders & Scalpers:
Designed for 1-minute (M1) or lower timeframes where traders need to monitor price action closely.
Helps visualize ultra-tight stop-loss levels in scalping strategies.
BTC Future Gamma-Weighted Momentum Model (BGMM)The BTC Future Gamma-Weighted Momentum Model (BGMM) is a quantitative trading strategy that utilizes the Gamma-weighted average price (GWAP) in conjunction with a momentum-based approach to predict price movements in the Bitcoin futures market. The model combines the concept of weighted price movements with trend identification, where the Gamma factor amplifies the weight assigned to recent prices. It leverages the idea that historical price trends and weighting mechanisms can be utilized to forecast future price behavior.
Theoretical Background:
1. Momentum in Financial Markets:
Momentum is a well-established concept in financial market theory, referring to the tendency of assets to continue moving in the same direction after initiating a trend. Any observed market return over a given time period is likely to continue in the same direction, a phenomenon known as the “momentum effect.” Deviations from a mean or trend provide potential trading opportunities, particularly in highly volatile assets like Bitcoin.
Numerous empirical studies have demonstrated that momentum strategies, based on price movements, especially those correlating long-term and short-term trends, can yield significant returns (Jegadeesh & Titman, 1993). Given Bitcoin’s volatile nature, it is an ideal candidate for momentum-based strategies.
2. Gamma-Weighted Price Strategies:
Gamma weighting is an advanced method of applying weights to price data, where past price movements are weighted by a Gamma factor. This weighting allows for the reinforcement or reduction of the influence of historical prices based on an exponential function. The Gamma factor (ranging from 0.5 to 1.5) controls how much emphasis is placed on recent data: a value closer to 1 applies an even weighting across periods, while a value closer to 0 diminishes the influence of past prices.
Gamma-based models are used in financial analysis and modeling to enhance a model’s adaptability to changing market dynamics. This weighting mechanism is particularly advantageous in volatile markets such as Bitcoin futures, as it facilitates quick adaptation to changing market conditions (Black-Scholes, 1973).
Strategy Mechanism:
The BTC Future Gamma-Weighted Momentum Model (BGMM) utilizes an adaptive weighting strategy, where the Bitcoin futures prices are weighted according to the Gamma factor to calculate the Gamma-Weighted Average Price (GWAP). The GWAP is derived as a weighted average of prices over a specific number of periods, with more weight assigned to recent periods. The calculated GWAP serves as a reference value, and trading decisions are based on whether the current market price is above or below this level.
1. Long Position Conditions:
A long position is initiated when the Bitcoin price is above the GWAP and a positive price movement is observed over the last three periods. This indicates that an upward trend is in place, and the market is likely to continue in the direction of the momentum.
2. Short Position Conditions:
A short position is initiated when the Bitcoin price is below the GWAP and a negative price movement is observed over the last three periods. This suggests that a downtrend is occurring, and a continuation of the negative price movement is expected.
Backtesting and Application to Bitcoin Futures:
The model has been tested exclusively on the Bitcoin futures market due to Bitcoin’s high volatility and strong trend behavior. These characteristics make the market particularly suitable for momentum strategies, as strong upward or downward movements are often followed by persistent trends that can be captured by a momentum-based approach.
Backtests of the BGMM on the Bitcoin futures market indicate that the model achieves above-average returns during periods of strong momentum, especially when the Gamma factor is optimized to suit the specific dynamics of the Bitcoin market. The high volatility of Bitcoin, combined with adaptive weighting, allows the model to respond quickly to price changes and maximize trading opportunities.
Scientific Citations and Sources:
• Jegadeesh, N., & Titman, S. (1993). Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency. The Journal of Finance, 48(1), 65–91.
• Black, F., & Scholes, M. (1973). The Pricing of Options and Corporate Liabilities. Journal of Political Economy, 81(3), 637–654.
• Fama, E. F., & French, K. R. (1992). The Cross-Section of Expected Stock Returns. The Journal of Finance, 47(2), 427–465.
GWAP (Gamma Weighted Average Price)Gamma Weighted Average Price (GWAP) Indicator
The Gamma Weighted Average Price (GWAP) is a dynamic financial indicator that applies exponentially decaying weights to historical prices to calculate a weighted average. The method leverages the exponential decay function, controlled by a gamma factor, to prioritize recent price data while gradually diminishing the influence of older observations. This approach builds upon techniques commonly found in time-series analysis, including Exponentially Weighted Moving Averages (EWMA), which are extensively used in financial modeling (Campbell, Lo & MacKinlay, 1997).
Theoretical Context and Justification
The gamma-weighted approach follows principles similar to those in Exponentially Weighted Moving Averages (EWMA), often used in volatility modeling, where weights decay exponentially over time. The exponential decay model can improve signal responsiveness compared to simple moving averages (Hyndman & Athanasopoulos, 2018). This design helps capture recent market dynamics without ignoring past trends, a common requirement in high-frequency trading systems (Bandi & Russell, 2006).
Practical Applications
1. Trend Detection:
The GWAP can help identify bullish and bearish trends:
• When the price is above GWAP, the market exhibits bullish momentum.
• Conversely, when the price is below GWAP, bearish momentum prevails.
2. Volatility Filtering:
Because of the gamma weighting mechanism, GWAP reduces the noise commonly seen in volatile markets, making it a useful tool for traders looking to smooth price fluctuations while retaining actionable signals.
3. Crossovers for Trade Signals:
Similar to moving average strategies, traders can use price crossovers with the GWAP as trade signals:
• Buy Signal: When the price crosses above the GWAP.
• Sell Signal: When the price crosses below the GWAP.
4. Adaptive Gamma Weighting:
The gamma factor allows for further customization.
• Higher gamma values (>1) place greater emphasis on older data, suitable for long-term trend analysis.
• Lower gamma values (<1) heavily weight recent price movements, ideal for fast-moving markets.
Example Use Case
A trader analyzing the S&P 500 may use a gamma factor of 0.92 with a 14-period GWAP to detect shifts in market sentiment during periods of heightened volatility. When the index price crosses above the GWAP, this could signal a potential recovery, prompting a buy entry. Conversely, when the price moves below the GWAP during a correction, it may suggest a short-selling opportunity.
Scientific References
• Campbell, J. Y., Lo, A. W., & MacKinlay, A. C. (1997). The Econometrics of Financial Markets. Princeton University Press.
• Hyndman, R. J., & Athanasopoulos, G. (2018). Forecasting: Principles and Practice. OTexts.
• Bandi, F. M., & Russell, J. R. (2006). Microstructure Noise, Realized Variance, and Optimal Sampling. Econometrica.
Multiple Candlestick Patterns - AlgomaxxA comprehensive candlestick pattern detection indicator that identifies seven major Japanese candlestick patterns in real-time. This indicator helps traders identify potential reversal and continuation patterns with customizable visual alerts and labels.
Features
Detects 7 major candlestick patterns:
Doji
Hammer
Shooting Star
Bullish Engulfing
Bearish Engulfing
Morning Star
Evening Star
Color-coded candlesticks for easy pattern identification
Customizable pattern indicators above/below candles
Optional pattern labels with adjustable position
Alert conditions for each pattern
Grouped settings for easy customization
Settings
General Settings
Lookback Period: Number of candles to analyze (default: 20)
Body Size Threshold: Minimum relative size for candle body (default: 0.6)
Pattern Settings
Toggle visibility for each pattern type:
Doji Pattern
Hammer Pattern
Shooting Star Pattern
Bullish Engulfing Pattern
Bearish Engulfing Pattern
Morning Star Pattern
Evening Star Pattern
Label Settings
Show Labels: Toggle pattern labels on/off
Label Text Color: Customize label color
Label Position: Choose between Left/Center/Right alignment
Label Offset: Adjust distance of labels from candles
Pattern Descriptions
Doji: Shows indecision when open and close prices are very close
Yellow color
Cross symbol below candle
Hammer: Potential bullish reversal with long lower shadow
Green color
Triangle up symbol below candle
Shooting Star: Potential bearish reversal with long upper shadow
Red color
Triangle down symbol above candle
Bullish Engulfing: Bullish reversal pattern where current green candle completely engulfs previous red candle
Light green color
Triangle up symbol below candle
Bearish Engulfing: Bearish reversal pattern where current red candle completely engulfs previous green candle
Light red color
Triangle down symbol above candle
Morning Star: Three-candle bullish reversal pattern
Seafoam green color
Triangle up symbol below candle
Evening Star: Three-candle bearish reversal pattern
Pink red color
Triangle down symbol above candle
How to Use
Add the indicator to your chart
Customize the settings based on your preferences:
Enable/disable specific patterns you want to monitor
Adjust label settings for better visibility
Set up alerts for patterns you want to be notified about
Pattern Recognition:
Watch for color changes in candlesticks indicating pattern formation
Look for shape indicators above/below candles
Read pattern labels for quick pattern identification
Trading Suggestions:
Use in conjunction with other technical indicators
Consider overall trend and support/resistance levels
Confirm patterns with volume and price action
Wait for pattern completion before making trading decisions
Tips
Patterns work best when used with multiple timeframes
Combine with trend lines and support/resistance levels
Use volume to confirm pattern strength
Consider market context and overall trend
Larger timeframes typically produce more reliable signals
Use alerts to avoid missing important pattern formations
Disclaimer
This indicator is for informational and educational purposes only. No guarantee is made regarding the accuracy of pattern detection or potential future price movements. Always use proper risk management and consider multiple factors before making trading decisions.
Ultimate Volatility Scanner by NHBprod - Requested by Client!Hey Everyone!
I created another script to add to my growing library of strategies and indicators that I use for automated crypto and stock trading! This strategy is for BITCOIN but can be used on any stock or crypto. This was requested by a client so I thought I should create it and hopefully build off of it and build variants!
This script gets and compares the 14-day volatility using the ATR percentage for a list of cryptocurrencies and stocks. Cryptocurrencies are preloaded into the script, and the script will show you the TOP 5 coins in terms of volatility, and then compares it to the Bitcoin volatility as a reference. It updates these values once per day using daily timeframe data from TradingView. The coins are then sorted in descending order by their volatility.
If you don't want to use the preloaded set of coins, you have the option of inputting your own coins AND/OR stocks!
Let me know your thoughts.
Volatility Arbitrage Spread Oscillator Model (VASOM)The Volatility Arbitrage Spread Oscillator Model (VASOM) is a systematic approach to capitalizing on price inefficiencies in the VIX futures term structure. By analyzing the differential between front-month and second-month VIX futures contracts, we employ a momentum-based oscillator (Relative Strength Index, RSI) to signal potential market reversion opportunities. Our research builds upon existing financial literature on volatility risk premia and contango/backwardation dynamics in the volatility markets (Zhang & Zhu, 2006; Alexander & Korovilas, 2012).
Volatility derivatives have become essential tools for managing risk and engaging in speculative trades (Whaley, 2009). The Chicago Board Options Exchange (CBOE) Volatility Index (VIX) measures the market’s expectation of 30-day forward-looking volatility derived from S&P 500 option prices (CBOE, 2018). Term structures in VIX futures often exhibit contango or backwardation, depending on macroeconomic and market conditions (Alexander & Korovilas, 2012).
This strategy seeks to exploit the spread between the front-month and second-month VIX futures as a proxy for term structure dynamics. The spread’s momentum, quantified by the RSI, serves as a signal for entry and exit points, aligning with empirical findings on mean reversion in volatility markets (Zhang & Zhu, 2006).
• Entry Signal: When RSI_t falls below the user-defined threshold (e.g., 30), indicating a potential undervaluation in the spread.
• Exit Signal: When RSI_t exceeds a threshold (e.g., 70), suggesting mean reversion has occurred.
Empirical Justification
The strategy aligns with findings that suggest predictable patterns in volatility futures spreads (Alexander & Korovilas, 2012). Furthermore, the use of RSI leverages insights from momentum-based trading models, which have demonstrated efficacy in various asset classes, including commodities and derivatives (Jegadeesh & Titman, 1993).
References
• Alexander, C., & Korovilas, D. (2012). The Hazards of Volatility Investing. Journal of Alternative Investments, 15(2), 92-104.
• CBOE. (2018). The VIX White Paper. Chicago Board Options Exchange.
• Jegadeesh, N., & Titman, S. (1993). Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency. The Journal of Finance, 48(1), 65-91.
• Zhang, C., & Zhu, Y. (2006). Exploiting Predictability in Volatility Futures Spreads. Financial Analysts Journal, 62(6), 62-72.
• Whaley, R. E. (2009). Understanding the VIX. The Journal of Portfolio Management, 35(3), 98-105.
Buyable Gap Ups (BGU) ScreenerBuyable Gap Ups (BGU) Screener
This custom indicator detects Buyable Gap Ups (BGU), designed to identify stocks with significant price movements driven by gap-ups, often signaling strong bullish momentum. It helps traders spot potential opportunities where a stock has gapped up above the previous day's high with increased volume, suggesting the possibility of continued price strength.
Key Features:
Gap Percentage Threshold: Set a minimum gap percentage required for a valid buyable gap-up.
Volume Change Threshold: Identifies gap-ups accompanied by a significant increase in volume compared to the 50-day average.
ATR-Based Gap Detection (Optional): Use Average True Range (ATR) to determine whether the gap is large enough, factoring in recent volatility.
Customizable Lookback Period: Adjust the number of recent bars to track the frequency of BGU occurrences.
Volume Confirmation: Only signals buyable gaps when volume surpasses a defined threshold above the 50-day average.
Input Parameters:
Gap Percentage Threshold: Adjusts the minimum percentage gap for a valid signal.
Volume Change Threshold: Determines the minimum percentage increase in volume compared to the 50-day moving average.
Use ATR Gap: Option to use ATR to determine the minimum gap size instead of the percentage gap.
ATR Multiplier for Gap: Customizes the gap size based on the ATR.
ATR Length: Adjusts the lookback period for calculating ATR.
Lookback Period for BGU: Set the number of bars over which to calculate the BGU count.
Alerts & Signals:
The script will plot signals below bars where a valid BGU condition is met.
Alerts can be set for when a BGU is detected, giving real-time notifications for potential trading opportunities.
This indicator is designed to help traders find stocks showing strong bullish momentum, especially after earnings or other market-moving events, with the potential for continued uptrend. It is ideal for those looking to incorporate gap-based strategies in their trading.
Walk Forward PatternsINTRO
In Euclidean geometry, every mathematical output has a planar projection. 'Walk Forward Patterns' can be considered a practical example of this concept. On the other hand, this indicator might also be viewed as an experiment in 'how playing with Lego as a child contributes to time series analysis' :)
OVERVIEW
This script dynamically generates the necessary optimization and testing ranges for Walk Forward Analysis based on user-defined bar count and length inputs. It performs automatic calculations for each step, offers 8 different window options depending on the inputs, and visualizes the results dynamically. I should also note that most of the window models consist of original patterns I have created.
ADDITIONAL INFO : WHAT IS WALK FORWARD ANALYSIS?
Although it is not the main focus of this indicator, providing a brief definition of Walk Forward Analysis can be helpful in correctly interpreting the results it generates. Walk Forward Analysis (WFA) is a systematic method for optimizing parameters and validating trading strategies. It involves dividing historical data into variable segments, where a strategy is first optimized on an in-sample period and then tested on an out-of-sample period. This process repeats by shifting the windows forward, ensuring that each test evaluates the strategy on unseen data, helping to assess its robustness and adaptability in real market conditions.
ORIGINALITY
There are very few studies on Walk Forward Analysis in TradingView. Even worse, there are no any open-source studies available. Someone has to start somewhere, I suppose. And in my personal opinion, determining the optimization and backtest intervals is the most challenging part of WFA. These intervals serve as a prerequisite for automated parameter optimization. I felt the need to publish this pattern module, which I use in my own WFA models, partly due to this gap on community scripts.
INDICATOR MECHANICS
To use the indicator effectively, you only need to perform four simple tasks:
Specify the total number of bars in your chart in the 'Bar Index' parameter.
Define the optimization (In-Sample Test) length.
Define the testing (Out-Of-Sample Test) length.
Finally, select the window type.
The indicator automatically models everything else (including the number of steps) based on your inputs. And the result; you now have a clear idea of which bars to use for your Walk Forward tests!
A COMMONLY USED WINDOW SELECTION METHOD: ROLLING
A more concrete definition of Walk Forward Analysis, specifically for the widely used Rolling method, can be described as follows:
Parameters that have performed well over a certain period are identified (Optimization: In-Sample).
These parameters are then tested on a shorter, subsequent period (Backtest: Out-of-Sample).
The process is repeated forward in time (At each step, the optimization and backtest periods are shifted by the backtest length).
If the cumulative percentage profit obtained from the backtest results is greater than half of the historical optimization profit, the strategy is considered "successful."
If the strategy is successful, the most recent (untested) optimization values are used for live trading.
OTHER WINDOW OPTIONS
ANCHORED: That's a pattern based on progressively expanding optimization ranges at each step. Backtest ranges move forward in a staircase-like manner.
STATIC: Optimization ranges remain fixed, while backtest ranges are shifted forward.
BLOCKED: Optimization ranges are shifted forward in groups of three blocks. Backtest ranges are also shifted in a staircase manner, even at the cost of creating gaps from the optimization end bars.
TRIANGULAR: Optimization ranges are shifted forward in triangular regions, while backtest ranges move in a staircase pattern.
RATIO: The optimization length increases by 25% of the initial step’s fixed length at each step. In other words, the length grows by 25% of the first step's length incrementally. Backtest ranges always start from the bar where the optimization ends.
FIBONACCI: A variation of the Ratio method, where the optimization shift factor is set to 0.618
RANDOM WALK
Unlike the window models explained above, we can also generate optimization and backtest ranges completely randomly—offering almost unlimited variations! When you select the "Random" option in the "Window" parameter on the indicator interface, random intervals are generated based on various trigonometric calculations. By changing the numerical value in the '🐒' parameter, you can create entirely unique patterns.
WHY THE 🐒 EMOJI?
Two reasons.
First, I think that as humanity, we are a species of tailless primates who become happy when we understand things :). At least evolutionarily. The entire history of civilization is built on the effort to express the universe in a scale we can comprehend. 'Knowledge' is an invention born from this effort, which is why we feel happiness when we 'understand'. Second, I can't think of a better metaphor for randomness than a monkey sitting at a keyboard. See: Monkey Test.
Anyway, I’m rambling :)
NOTES
The indicator generates results for up to 100 steps. As the number of steps increases, the table may extend beyond the screen—don’t forget to zoom out!
FINAL WORDS
I haven’t published a Walk Forward script yet . However, there seem to be examples that can perform parameter optimization in the true sense of the word, producing more realistic results without falling into overfitting in my library. Hopefully, I’ll have the chance to publish one in the coming weeks. Sincerely thanks to Kıvanç Özbilgiç, Robert Pardo, Kevin Davey, Ernest P. Chan for their inspiring publishments.
DISCLAIMER
That's just a script, nothing more. I hope it helps everyone. Do not forget to manage your risk. And trade as safely as possible. Best of luck!
© dg_factor
USDT.D + USDT.C ALL TIMEFRAMESThis indicator combines the dominance of USDT (USDT.D) and USDC (USDC.D) to track total stablecoin market share across all timeframes. It displays the combined dominance as candlesticks, providing a clearer view of market liquidity shifts and investor sentiment.
📌 How to Use:
Green candles indicate rising stablecoin dominance (potential risk-off sentiment).
Red candles indicate declining stablecoin dominance (potential risk-on sentiment).
Works on all timeframes, from intraday scalping to macro trend analysis.
This tool is essential for traders looking to analyze stablecoin liquidity flow, identify market turning points, and refine trading strategies based on stablecoin dominance behavior. 🚀
Optimized Dynamic SupertrendDetailed Explanation of the Optimized Dynamic Supertrend Script
This Supertrend script is designed to dynamically adapt to different market conditions using ATR expansion, volume confirmation, and trend filtering. Below is a step-by-step breakdown of how it works and its functions.
1 ATR-Based Supertrend Calculation
📌 Key Purpose:
The script calculates an adaptive ATR-based Supertrend line, which acts as a dynamic support or resistance level for trend direction.
📌 How it Works:
ATR (Average True Range) is used to measure market volatility.
A dynamic ATR multiplier is applied based on price standard deviation (instead of a fixed value).
The Supertrend is calculated as:
Upper Band: SMA(close, ATR length) + (ATR Multiplier * ATR Value)
Lower Band: SMA(close, ATR length) - (ATR Multiplier * ATR Value)
The Supertrend flips when price crosses and holds beyond the Supertrend line.
🔹 Dynamic Adjustment:
Instead of using a fixed ATR multiplier, the script adjusts it using:
pinescript
Copy
Edit
dynamicFactor = ta.stdev(close, atrLength) / ta.sma(close, atrLength)
atrMultiplier = input(1.5, title="Base ATR Multiplier") * dynamicFactor
High volatility → Wider Supertrend bands (to avoid false signals).
Low volatility → Tighter Supertrend bands (for faster detection).
2 Trend Detection Logic
📌 Key Purpose:
Determines if the market is in a bullish or bearish trend based on price action.
Uses volume sensitivity and ATR expansion to reduce false signals.
📌 How it Works:
pinescript
Copy
Edit
var float supertrend = na
supertrend := close > nz(supertrend , lowerBand) ? lowerBand : upperBand
The Supertrend value updates dynamically.
If price is above the Supertrend line, the trend is bullish (green).
If price is below the Supertrend line, the trend is bearish (red).
3 Volume Sensitivity Confirmation
📌 Key Purpose:
Avoid false trend flips by confirming with volume (approximated using a CVD proxy).
📌 How it Works:
pinescript
Copy
Edit
priceChange = close - close
volumeWeightedTrend = priceChange * volume // Approximate CVD Behavior
trendConfirmed = volumeWeightedTrend > 0 ? close > supertrend : close < supertrend
Positive price change + High volume → Confirms bullish momentum.
Negative price change + High volume → Confirms bearish momentum.
If there’s low volume, the trend change is ignored to avoid false breakouts.
4 Noise Reduction (Final Trend Confirmation)
📌 Key Purpose:
Filter out weak or choppy price movements using ATR expansion.
📌 How it Works:
pinescript
Copy
Edit
trendUp = trendConfirmed and ta.atr(atrLength) > ta.atr(atrLength)
trendDown = not trendUp
Trend only flips when confirmed by volume + ATR expansion.
If ATR is not expanding, the script ignores weak price movements.
This ensures Supertrend signals align with strong market moves.
5 Can This Be Used on All Timeframes?
✅ YES! This Supertrend is adaptive, meaning it adjusts dynamically based on:
Volatility: Uses ATR expansion to adjust for different market conditions.
Timeframe Sensitivity: Works on any timeframe (1M, 5M, 15M, 1H, 4H, 1D, 1W).
Market Structure: Confirms trend flips using volume & price movement strength.
🚀 Best Timeframes for Trading:
For Scalping (1M - 15M) → Quick execution, best with order flow confirmation.
For Swing Trading (1H - 4H - 1D) → Stronger trend signals, reduced noise.
For High Timeframes (3D - 1W) → Identifies major market shifts.
🔥 Advantages & Disadvantages in Your Trading Setup
✅ Advantages:
✔ Fully Dynamic & Adaptive → Adjusts to different timeframes & volatility.
✔ Reduces False Signals → Uses ATR expansion & volume confirmation.
✔ Precise Trend Reversals → Labels LONG & SHORT entries clearly.
✔ Works on Any Market → Crypto, Forex, Stocks, Commodities.
✔ No Extra Indicators → Pure Supertrend-based (fits your setup).
❌ Disadvantages:
⚠ Lagging Indicator → ATR & volume confirmation add slight delay.
⚠ Needs High Volume to Confirm → Weak volume → no trend flip.
⚠ Choppy Market = Late Entries → Sideways movement can cause delays.
🚀 Final Thoughts:
It’s fully dynamic & adaptive (unlike traditional static Supertrends).
No extra indicators → Uses only Supertrend logic
Refines entry points using volume & ATR confirmation (removes noise).
This ensures you get high-probability trend signals while filtering out weak breakouts! 🎯
BullDozz MA-CandlesticksBullDozz MA-Candlesticks 🏗️📊
The BullDozz MA-Candlesticks indicator transforms traditional candlesticks by replacing their Open, High, Low, and Close values with various types of Moving Averages (MAs). This helps traders visualize market trends with smoother price action, reducing noise and enhancing decision-making.
🔹 Features:
✅ Choose from multiple MA types: SMA, EMA, WMA, DEMA, TEMA, LSMA
✅ Customizable MA period for flexibility
✅ Candlestick colors based on trend: Green for bullish, Red for bearish
✅ Works on any market and timeframe
This indicator is perfect for traders who want a clearer perspective on price movement using moving average-based candlesticks. 🚀 Try it now and refine your market analysis! 📈🔥
3x Supertrend (for Vietnamese stock market and vn30f1m)The 4Vietnamese 3x Supertrend Strategy is an advanced trend-following trading system developed in Pine Script™ and designed for publication on TradingView as an open-source strategy under the Mozilla Public License 2.0. This strategy leverages three Supertrend indicators with different ATR lengths and multipliers to identify optimal trade entries and exits while dynamically managing risk.
Key Features:
Option to build and hold long term positions with entry stop order. Try this to avoid market complex movement and retain long term investment style's benefits.
Advanced Entry & Exit Optimization: Includes configurable stop-loss mechanisms, pyramiding, and exit conditions tailored for different market scenarios.
Dynamic Risk Management: Implements features like selective stop-loss activation, trade window settings, and closing conditions based on trend reversals and loss management.
This strategy is particularly suited for traders seeking a systematic and rule-based approach to trend trading. By making it open-source, we aim to provide transparency, encourage community collaboration, and help traders refine and optimize their strategies for better performance.
License:
This script is released under the Mozilla Public License 2.0, allowing modifications and redistribution while maintaining open-source integrity.
Happy trading!
Anti-Martingale Position Sizing 6500$ Trailing DrawdownReady reckoner to let you know how much to risk as a function of your drawdown when trading NQ.
Combined SmartComment & Dynamic S/R LevelsDescription:
The Combined SmartComment & Dynamic S/R Levels script is designed to provide valuable insights for traders using TradingView. It integrates dynamic support and resistance levels with a powerful Intelligent Comment system to enhance decision-making. The Intelligent Comment feature generates market commentary based on key technical indicators, delivering real-time actionable feedback that helps optimize trading strategies.
Intelligent Comment Feature:
The Intelligent Comment function continuously analyzes market conditions and offers relevant insights based on combinations of various technical indicators such as RSI, ATR, MACD, WMA, and others. These comments help traders identify potential price movements, highlighting opportunities to buy, sell, or wait.
Examples of the insights provided by the system include:
RSI in overbought/oversold and price near resistance/support: Indicates potential price reversal points.
Price above VAH and volume increasing: Suggests a strengthening uptrend.
Price near dynamic support/resistance: Alerts when price approaches critical support or resistance zones.
MACD crossovers and RSI movements: Provide signals for potential trend shifts or continuations.
Indicators Used:
RSI (Relative Strength Index)
ATR (Average True Range)
MACD (Moving Average Convergence Divergence)
WMA (Weighted Moving Average)
POC (Point of Control)
Bollinger Bands
SuperSignal
Volume
EMA (Exponential Moving Average)
Dynamic Support/Resistance Levels
How It Works:
The script performs real-time market analysis, assessing multiple technical indicators to generate Intelligent Comments. These comments provide traders with timely guidance on potential market movements, assisting with decision-making in a dynamic market environment. The script also integrates dynamic support and resistance levels to further enhance trading accuracy.
Support and Resistance all in one The Support and Resistance Indicator (v4) is designed to identify and track key price levels in financial markets. Here's how it works:
Core Functionality
Level Detection
Uses pivot points to identify significant price levels
Looks for swing highs (resistance) and swing lows (support)
Requires price action to pivot over a specified period (default 10 bars)
Dynamic Level Management
Maintains separate arrays for support and resistance levels
Limits maximum displayed levels (default 10) to prevent chart clutter
Removes oldest levels when maximum is reached
Ensures new levels are sufficiently distant from existing ones (minimum 1% separation)
Touch Detection System
Monitors price interaction with established levels
Counts when price comes within 0.1% of any level
Updates touch count and strength classification
Categories: "New" (1 touch), "Moderate" (2 touches), "Strong" (3+ touches)
Visual Representation
Draws horizontal lines at each level
Updates line width based on strength (thicker for stronger levels)
Shows labels with price and strength information
Color coding: Red (new/moderate levels), Green (strong levels)
Displays triangles (▼▲) at pivot points
Trading Applications
Support/Resistance Trading
Strong levels (3+ touches) suggest reliable trading zones
More touches indicate higher probability reversal points
Use for stop loss and target placement
Breakout Trading
Monitor breaks of strong levels
Higher touch count suggests more significant breakouts
Watch for false breakouts at weaker levels
Risk Management
Place stops beyond strong levels
Use level strength to adjust position size
Consider multiple timeframe analysis
Best Practices
Use with other indicators for confirmation
Consider market context and trend
Monitor level strength development
Don't rely solely on touch count
Watch for price reaction at levels
Customization Options
Adjust pivot length for different timeframes
Modify minimum distance between levels
Change required touches for "Strong" classification
Toggle strength labels display
Choose line style (Solid/Dashed/Dotted)
This indicator helps identify key price levels where market participants have shown interest, making it valuable for trade planning and risk management
BullDozz Fibo ZigZagFibo ZigZag - Advanced Fibonacci Retracement Tool 🔥
📌 Overview
The Fibo ZigZag indicator is a powerful tool for trend structure analysis using the ZigZag pattern and Fibonacci retracement levels. It automatically identifies swing highs & lows, draws ZigZag lines, and overlays Fibonacci levels with price labels at the right end for better readability.
This indicator is designed for traders who use price action, trend reversal strategies, and support/resistance analysis.
🛠 Features
✅ Automatic ZigZag detection with customizable depth, deviation, and backstep
✅ Fibonacci retracement levels (0%, 23.6%, 38.2%, 50%, 61.8%, 100%, 161.8%, 261.8%, 423.6%)
✅ Price labels at Fibonacci levels (placed at the right end of the levels)
✅ Alerts for new swing highs & lows
✅ Customizable line colors, text colors, and label sizes
✅ Lightweight and optimized for fast performance
📊 How It Works
1️⃣ The script detects ZigZag structure points based on price swings
2️⃣ It connects recent highs & lows with a ZigZag line
3️⃣ Fibonacci retracement levels are calculated and drawn between the last two significant swing points
4️⃣ Each Fibo level is labeled with its percentage & exact price, placed at the right end for clarity
5️⃣ Alerts trigger automatically when a new swing high or low is detected
⚙ Customization Options
🔹 ZigZag Settings: Adjust Depth, Deviation, BackStep, and Leg length
🔹 Fibonacci Levels: Modify line colors, label text colors, and visibility
🔹 Alerts: Enable/disable trend change alerts
📈 Best Use Cases
🚀 Identifying Trend Reversals – Detect key turning points using Fibonacci levels
📉 Support & Resistance Trading – Use retracement levels as entry/exit points
📊 Swing Trading & Scalping – Combine ZigZag with price action for effective strategies
🔔 Alert-Based Trading – Get notified when new swing highs/lows form
🚀 How to Use
📌 Add the indicator to your chart
📌 Adjust the settings to match your trading strategy
📌 Use the Fibonacci levels & ZigZag lines to analyze trend direction & key price zones
📌 Wait for alerts or manually enter trades based on price reaction to Fibo levels
📢 Final Thoughts
The Fibo ZigZag is an essential tool for traders who rely on price action, trend reversals, and Fibonacci levels. Whether you're a beginner or a pro, this indicator helps you spot high-probability trading opportunities with ease.
⚡ Try it now & enhance your trading strategy! 🚀
💬 Let us know your feedback & suggestions in the comments! Happy trading! 📊🔥