Momentum ProfileProfile market behavior in horizontal zones
Profile Sidebar
Buckets pointing rightward indicate upward security movement in the lookahead window at that level, and buckets pointing leftward indicate downward movement in the lookahead window.
Green profile buckets indicate the security's behavior following an uptrend in the lookbehind window. Conversely, Red profile buckets show security's behavior following a downtrend in the lookbehind window. Yellow profile buckets show behavior following sideways movement.
Buckets length corelates with the amount of movement measured in that direction at that level.
Inputs
Length determines how many bars back are considered for the calculation. On most securities, this can be increased to just above 4000 without issues.
Rows determines the number of buckets that the securities range is divided into.
You can increase or decrease the threshold for which moves are considered sideways with the sideways_filter input: higher means more moves are considered sideways.
The lookbehind input determines the lookbehind window. Specifically, how many bars back are considered when determining whether a data point is considered green (uptrend), red (downtrend), or yellow (no significant trend).
The lookahead input determines how many bars after the current bar are considered when determining the length and direction of each bucket (leftward for downward moves, rightward for upward moves).
Profile_width and Profile_spacing are cosmetic choices.
Intrabar support is not current supported.
Region Highlighting
Regions highlighted green saw an upward move in the lookahead window for both lookbehind downtrends and uptrends. In other words, both red and green profile buckets pointed rightward.
Regions highlighted red saw a downward move in the lookahead window both for lookbehind downtrends and uptrends.
Regions highlighted brown indicate a reversal region: uptrends were followed by downtrends, and vice versa. These regions often indicate a chop range or sometimes support/resistance levels. On the profile, this means that green buckets pointed left, and red buckets pointed right.
Regions highlighted purple indicate that whatever direction the security was moving, it continued that way. On the profile, this means that green buckets pointed right, and red buckets pointed left in that region.
Cerca negli script per "如何用wind搜索股票的发行价和份数"
Ichimoku Clouds Strategy Long and ShortOverview:
The Ichimoku Clouds Strategy leverages the Ichimoku Kinko Hyo technique to offer traders a range of innovative features, enhancing market analysis and trading efficiency. This strategy is distinct in its combination of standard methodology and advanced customization, making it suitable for both novice and experienced traders.
Unique Features:
Enhanced Interpretation: The strategy introduces weak, neutral, and strong bullish/bearish signals, enabling detailed interpretation of the Ichimoku cloud and direct chart plotting.
Configurable Trading Periods: Users can tailor the strategy to specific market windows, adapting to different market conditions.
Dual Trading Modes: Long and Short modes are available, allowing alignment with market trends.
Flexible Risk Management: Offers three styles in each mode, combining fixed risk management with dynamic indicator states for versatile trade management.
Indicator Line Plotting: Enables plotting of Ichimoku indicator lines on the chart for visual decision-making support.
Methodology:
The strategy utilizes the standard Ichimoku Kinko Hyo model, interpreting indicator values with settings adjustable through a user-friendly menu. This approach is enhanced by TradingView's built-in strategy tester for customization and market selection.
Risk Management:
Our approach to risk management is dynamic and indicator-centric. With data from the last year, we focus on dynamic indicator states interpretations to mitigate manual setting causing human factor biases. Users still have the option to set a fixed stop loss and/or take profit per position using the corresponding parameters in settings, aligning with their risk tolerance.
Backtest Results:
Operating window: Date range of backtests is 2023.01.01 - 2024.01.04. It is chosen to let the strategy to close all opened positions.
Commission and Slippage: Includes a standard Binance commission of 0.1% and accounts for possible slippage over 5 ticks.
Maximum Single Position Loss: -6.29%
Maximum Single Profit: 22.32%
Net Profit: +10 901.95 USDT (+109.02%)
Total Trades: 119 (51.26% profitability)
Profit Factor: 1.775
Maximum Accumulated Loss: 4 185.37 USDT (-22.87%)
Average Profit per Trade: 91.67 USDT (+0.7%)
Average Trade Duration: 56 hours
These results are obtained with realistic parameters representing trading conditions observed at major exchanges such as Binance and with realistic trading portfolio usage parameters. Backtest is calculated using deep backtest option in TradingView built-in strategy tester
How to Use:
Add the script to favorites for easy access.
Apply to the desired chart and timeframe (optimal performance observed on the 1H chart, ForEx or cryptocurrency top-10 coins with quote asset USDT).
Configure settings using the dropdown choice list in the built-in menu.
Set up alerts to automate strategy positions through web hook with the text: {{strategy.order.alert_message}}
Disclaimer:
Educational and informational tool reflecting Skyrex commitment to informed trading. Past performance does not guarantee future results. Test strategies in a simulated environment before live implementation
Opening Range Gaps [TFO]This indicator displays Opening Range Gaps with an adjustable time window. Its intention is to capture the discrepancy between the close price of previous and new Real Trading Hours (RTH) sessions, i.e. yesterday's close compared to today's open. A gap will be drawn from this area with a solid line denoting its midpoint, and dashed lines denoting the upper and lower quartiles of its range. Its color is determined by whether the new session open price is above or below the previous session close.
The Gap Session parameter allows users to define the specific time window for which to capture the "gap" in price. Using U.S. index futures as an example, we can use 16:00 - 09:30 (EST) to capture the discrepancy between the previous day's close price and the current day's open price. However, this parameter is left as adjustable for users that may want to observe different markets or simply experiment with different time windows.
Show Session Delineations will draw vertical timestamps denoting the start and end times of the provided Gap Session. Track Start Price serves as a visual aid to track the initial price of the Gap Session until its end price is validated, for easy visual verification of a gap's upper and lower bounds. With both options turned off, the indicator will only display the gap boxes and lines, as shown here:
Extend Boxes will draw all gaps with an indefinite extension to the right. This can get messy with a large number of boxes, which is why we have a Keep Last parameter to limit how many sessions' drawings should be stored. Any drawings that were made beyond this number of sessions in the past will automatically be deleted.
The Timeframe Limit will dictate that the indicator as a whole will only draw objects on timeframes less than or equal to this timeframe, determined by the user. In some cases this may help users avoid resolution errors which may arise from using timeframes that are too large for a given session. For example, if a user wanted to track a Gap Session of 16:15-09:30, the Timeframe Limit should be set to 15 minutes because the close price at 16:15 cannot be observed on a 30 minute chart (or greater).
Fibonacci ClustersI was reading about Fibonacci Clusters on investopedia (www.investopedia.com) and couldn't find a script for it on tradingveiw. Apparently some people use it successfully but I found it a little chaotic. This script will mark the retracements in a window's length, and you can set this for six windows. This script isn't very pretty because it doesn't seem obviously useful and pinescript has far too many deficiencies to fully flesh this idea out. I was able to make more sense out of larger windowing times (500-4000 periods), than shorter ones (25-333). Try it out, see what it shows you. Happy trading
Markov + Monte Carlo Simulation with EVMarkov Monte Carlo Projection (MMCP) – A Probabilistic Approach to Price Forecasting
Introduction: A New Approach to Price Projection
The Markov Monte Carlo Projection (MMCP) is an advanced stochastic forecasting tool that models potential future price paths using a combination of Markov Chain transition probabilities and Monte Carlo simulations. Unlike traditional technical indicators that rely on fixed formulas, MMCP employs probability distributions and simulated price movement paths to estimate future price behavior dynamically.
This indicator is designed to adapt to changing market conditions and provides traders with a probabilistic framework rather than a fixed forecast. By incorporating volatility modeling, MMCP enables traders to size projections proportionally to recent price action, making it an adaptive and flexible forecasting tool.
Mathematical Foundations
Markov Chains: Modeling Probability of Price Movements
A Markov Chain is a stochastic process where the probability of transitioning to the next state depends only on the current state and not on past states (i.e., it is memoryless).
For price movement, MMCP analyzes the past N bars (set by the lookback window) to determine the transition probabilities of price moving up, down, or remaining the same based on past behavior:
Pup=Number of Up MovesTotal Moves
Pup=Total MovesNumber of Up Moves
Pdown=Number of Down MovesTotal Moves
Pdown=Total MovesNumber of Down Moves
Psame=1−(Pup+Pdown)
Psame=1−(Pup+Pdown)
These probabilities guide how future price movements are simulated, ensuring that projections reflect historical price behavior tendencies.
Monte Carlo Simulations: Generating Possible Futures
Monte Carlo simulations involve running many random trials to estimate possible outcomes. Each trial simulates a future price path by:
Randomly selecting a direction based on the Markov probabilities Pup,Pdown,PsamePup,Pdown,Psame.
Determining the magnitude of the price movement using a normally distributed volatility model.
Iterating this process across multiple forecast bars to simulate a range of potential price paths.
This process does not predict a single outcome, but rather generates a probability-weighted range of future price possibilities.
Volatility Modeling: Scaling Movements Proportionally
Why We Use Standard Deviation (σσ)
Price movement is inherently volatile, and the magnitude of price shifts must be scaled relative to recent volatility. MMCP calculates rolling price returns and then derives the standard deviation of those returns:
σ=stdev(price returns,lookback)
σ=stdev(price returns,lookback)
The Volatility Multiplier allows users to adjust the impact of this volatility on projected movements. This makes the indicator adaptive to different asset price ranges.
Key User Adjustments
1. Volatility Multiplier – Tuning Projections for Different Assets
The scale of the Volatility Multiplier must be tuned for each asset because it is relative to the magnitude of price action. For example:
Low-priced assets (e.g., $2.50 stocks) → A multiplier of 0.1 works best.
Mid-priced assets (e.g., $250 stocks) → A multiplier of 3 works best.
High-priced assets (e.g., Bitcoin) → A multiplier of 1000 works best.
🔹 If projections seem too extreme, decrease the multiplier.
🔹 If projections seem too flat, increase the multiplier.
The Volatility Multiplier can also be fine-tuned to make the projected signal proportionate to the immediately preceding price action.
2. Expected Value (EV) Path – Analyzing Aggregate Future Probabilities
The EV Line is a computed average of all simulated paths, giving traders an expected mean trajectory.
If you find that the EV Line is not visible, try increasing the volatility multiplier to make it more pronounced.
3. Projection Inversion – Enhancing Analysis with Paired Indicators
A unique feature of MMCP is the projection inversion toggle, designed to allow traders to run multiple instances of the indicator in tandem.
When one instance is set to normal projection and another to inverted projection, traders can pair them together using identical settings (except inversion). This setup allows for a mirrored probability perspective and enhances visualizing volatility dynamics.
Additionally, traders can use multiple sets of paired indicators, each with a different lookback window, to build a multi-layered, probability-driven market visualization. This dynamic approach provides an evolving structure of probable price movement in different time frames, offering deeper insights into potential market conditions.
How MMCP Works in Real-Time
Each new bar triggers a fresh Monte Carlo simulation, meaning that projections organically evolve with the market. This ensures that MMCP is always responding to current conditions, rather than applying static assumptions.
How to Use MMCP in Trading
✔ Identifying Potential Reversal & Continuation Zones
If most Monte Carlo paths project upward, bullish momentum is likely.
If most Monte Carlo paths project downward, bearish momentum is likely.
The Expected Value (EV) Line can help confirm the most probable trajectory.
✔ Analyzing Market Sentiment in Real Time
Use multiple instances of MMCP with different lookback windows to capture short-term vs. long-term sentiment.
Enable projection inversion to analyze potential mirrored moves.
✔ Fine-Tuning MMCP for Your Strategy
Adjust the Volatility Multiplier to match the price scale of your asset.
Increase the number of simulations to improve statistical robustness.
Use shorter lookback windows for more responsive predictions, or longer windows for more stable forecasts.
Why MMCP is a Game-Changer
✅ Dynamic & Probabilistic – Unlike fixed indicators, MMCP adapts in real-time.
✅ Fully Stochastic – MMCP embraces uncertainty using Markov models & Monte Carlo simulations.
✅ Customizable for Any Asset – Adjust the Volatility Multiplier for small or large price movements.
✅ Live Updates – The projection organically evolves with every new price bar.
✅ Multi-Perspective Analysis – Traders can run paired normal and inverted projections for deeper insights.
By tuning Volatility Multiplier, Lookback Window, and Projection Inversion, traders can customize MMCP to fit their strategy.
Final Thoughts
The Markov Monte Carlo Projection (MMCP) is not about making absolute predictions—it is about understanding probability distributions in price action.
By leveraging Monte Carlo simulations, Markov transition probabilities, and dynamic volatility modeling, MMCP gives traders a powerful probability-based edge in forecasting potential price movement.
Volume Forecasting [LuxAlgo]The Volume Forecasting indicator provides a forecast of volume by capturing and extrapolating periodic fluctuations. Historical forecasts are also provided to compare the method against volume at time t .
This script will not work on tickers that do not have volume data.
🔶 SETTINGS
Median Memory: Number of days used to compute the median and first/third quartiles.
Forecast Window: Number of bars forecasted in the future.
Auto Forecast Window: Set the forecast window so that the forecast length completes an interval.
🔶 USAGE
The periodic nature of volume on certain securities allows users to more easily forecast using historical volume. The forecast can highlight intervals where volume tends to be more important, that is where most trading activity takes place.
More pronounced periodicity will tend to return more accurate forecasts.
The historical forecast can also highlight intervals where high/low volume is not expected.
The interquartile range is also highlighted, giving an area where we can expect the volume to lie.
🔶 DETAILS
This forecasting method is similar to the time series decomposition method used to obtain the seasonal component.
We first segment the chart over equidistant intervals. Each interval is delimited by a change in the daily timeframe.
To forecast volume at time t+1 we see where the current bar lies in the interval, if the bar is the 78th in interval then the forecast on the next bar is made by taking the median of the 79th bar over N intervals, where N is the median memory.
This method ensures capturing the periodic fluctuation of volume.
Bill Williams SystemBill Williams System combine all indicators of Mr. Bill Williams into one window with detail below:
1. Top of window:
Display Fractals with shape triangle down is bottom fractal and shape triangle up is top fractal
2. Bottom of window:
Display Alligator Trend Flat with trend defined as below:
* Up trend: Lips value shift 3 bars greater than Teeth value shift 5 bars. And Teeth value shift 5 bars greater than Jaws value shift 8 bars. By default up trend is green square.
* Down trend: Lips value shift 3 bars less than Teeth value shift 5 bars. And Teeth value shift 5 bars less than Jaws value shift 8 bars. By default down trend is red square.
* Choppy: not up trend and not down trend. By default choppy is gray square.
3. Moving around zero line
* Awesome Oscillator is circles.
* Accelerator Oscillator is columns.
* Gator Oscillator is area.
OHLCVRangeXThe OHLCVRange library provides modular range-building utilities for Pine Script v6 based on custom conditions like time, price, volatility, volume, and pattern detection. Each function updates a persistent range (OHLCVRange) passed in from the calling script, based on live streaming candles.
This library is designed to support dynamic windowing over incoming OHLCV bars, with all persistent state handled externally (in the indicator or strategy). The library merely acts as a filter and updater, appending or clearing candles according to custom logic.
📦
export type OHLCVRange
OHLCV.OHLCV candles // Sliding window of candles
The OHLCVRange is a simple container holding an array of OHLCV.OHLCV structures.
This structure should be declared in the indicator using var to ensure persistence across candles.
🧩 Range Updater Functions
Each function follows this pattern:
export updateXxxRange(OHLCVRange r, OHLCV.OHLCV current, ...)
r is the range to update.
current is the latest OHLCV candle (typically from your indicator).
Additional parameters control the behavior of the range filter.
🔁 Function List
1. Fixed Lookback Range
export updateFixedRange(OHLCVRange r, OHLCV.OHLCV current, int barsBack)
Keeps only the last barsBack candles.
Sliding window based purely on number of bars.
2. Session Time Range
export updateSessionRange(OHLCVRange r, OHLCV.OHLCV current, int minuteStart, int minuteEnd)
Keeps candles within the [minuteStart, minuteEnd) intraday session.
Clears the range once out of session bounds.
3. Price Zone Range
export updatePriceZoneRange(OHLCVRange r, OHLCV.OHLCV current, float minP, float maxP)
Retains candles within the vertical price zone .
Clears when a candle exits the zone.
4. Consolidation Range
export updateConsolidationRange(OHLCVRange r, OHLCV.OHLCV current, float thresh)
Stores candles as long as the candle range (high - low) is less than or equal to thresh.
Clears on volatility breakout.
5. Volume Spike Range
export updateVolumeSpikeRange(OHLCVRange r, OHLCV.OHLCV current, float avgVol, float mult, int surround)
Triggers a new range when a volume spike ≥ avgVol * mult occurs.
Adds candles around the spike (total surround * 2 + 1).
Can be used to zoom in around anomalies.
6. Engulfing Pattern Range
export updateEngulfingRange(OHLCVRange r, OHLCV.OHLCV current, int windowAround)
Detects bullish or bearish engulfing candles.
Stores 2 * windowAround + 1 candles centered around the pattern.
Clears if no valid engulfing pattern is found.
7. HTF-Aligned Range
export updateHTFAlignedRange(OHLCVRange r, OHLCV.OHLCV current, OHLCV.OHLCV prevHtf)
Used when aligning lower timeframe candles to higher timeframe bars.
Clears and restarts the range on HTF bar transition (compare prevHtf.bar_index with current).
Requires external management of HTF candle state.
💡 Usage Notes
All OHLCVRange instances should be declared as var in the indicator to preserve state:
var OHLCVRange sessionRange = OHLCVRange.new()
sessionRange := OHLCVRange.updateSessionRange(sessionRange, current, 540, 900)
All OHLCV data should come from the OHLCVData library (v15 or later):
import userId/OHLCVData/15 as OHLCV
OHLCV.OHLCV current = OHLCV.getCurrentChartOHLCV()
This library does not use var internally to enforce clean separation of logic and persistence.
📅 Planned Enhancements
Fib zone ranges: capture candles within custom Fibonacci levels.
Custom event ranges: combine multiple filters (e.g., pattern + volume spike).
Trend-based ranges: windowing based on moving average or trend breaks.
Clustering Volatility (ATR-ADR-ChaikinVol) [Sam SDF-Solutions]The Clustering Volatility indicator is designed to evaluate market volatility by combining three widely used measures: Average True Range (ATR), Average Daily Range (ADR), and the Chaikin Oscillator.
Each indicator is normalized using one of the available methods (MinMax, Rank, or Z-score) to create a unified metric called the Score. This Score is further smoothed with an Exponential Moving Average (EMA) to reduce noise and provide a clearer view of market conditions.
Key Features:
Multi-Indicator Integration: Combines ATR, ADR, and the Chaikin Oscillator into a single Score that reflects overall market volatility.
Flexible Normalization: (Supports three normalization methods)
MinMax: Scales values between the observed minimum and maximum.
Rank: Normalizes based on the relative rank within a moving window.
Z-score: Standardizes values using mean and standard deviation.
Dynamic Window Selection: Offers an automatic window selection option based on a specified lookback period, or a fixed window size can be used.
Customizable Weights: Allows the user to assign individual weights to ATR, ADR, and the Chaikin Oscillator. Optionally, weights can be normalized to sum to 1.
Score Smoothing: Applies an EMA to the computed Score to smooth out short-term fluctuations and reduce market noise.
Cluster Visualization: Divides the smoothed Score into a number of clusters, each represented by a distinct color. These colors can be applied to the price bars (if enabled) for an immediate visual indication of the current volatility regime.
How It Works:
Input & Window Setup: Users set parameters for indicator periods, normalization methods, weights, and window size. The indicator can automatically determine the analysis window based on the number of lookback days.
Calculation of Metrics: The indicator computes the ATR, ADR (as the average of bar ranges), and the Chaikin Oscillator (based on the difference between short and long EMAs of the Accumulation/Distribution line).
Normalization & Scoring: Each indicator’s value is normalized and then weighted to form a raw Score. This raw Score is scaled to a range using statistics from the chosen window.
Smoothing & Clustering: The raw Score is smoothed using an EMA. The resulting smoothed Score is then multiplied by the number of clusters to assign a cluster index, which is used to choose a color for visual signals.
Visualization: The smoothed Score is plotted on the chart with a color that changes based on its value (e.g., lime for low, red for high, yellow for intermediate values). Optionally, the price bars are colored according to the assigned cluster.
_____________
This indicator is ideal for traders seeking a quick and clear assessment of market volatility. By integrating multiple volatility measures into one comprehensive Score, it simplifies analysis and aids in making more informed trading decisions.
For more detailed instructions, please refer to the guide here:
Weighted Fourier Transform: Spectral Gating & Main Frequency🙏🏻 This drop has 2 purposes:
1) to inform every1 who'd ever see it that Weighted Fourier Tranform does exist, while being available nowhere online, not even in papers, yet there's nothing incredibly complicated about it, and it can/should be used in certain cases;
2) to show TradingView users how they can use it now in dem endevours, to show em what spectral filtering is, and what can they do with all of it in diy mode.
... so we gonna have 2 sections in the description
Section 1: Weighted Fourier Transform
It's quite easy to include weights in Fourier analysis: you just premultiply each datapoint by its corresponding weight -> feed to direct Fourier Transform, and then divide by weights after inverse Fourier transform. Alternatevely, in direct transform you just multiply contributions of each data point to the real and imaginary parts of the Fourier transform by corresponding weights (in accumulation phase), and in inverse transform you divide by weights instead during the accumulation phase. Everything else stays the same just like in non-weighted version.
If you're from the first target group let's say, you prolly know a thing or deux about how to code & about Fourier Transform, so you can just check lines of code to see the implementation of Weighted Discrete version of Fourier Transform, and port it to to any technology you desire. Pine Script is a developing technology that is incredibly comfortable in use for quant-related tasks and anything involving time series in general. While also using Python for research and C++ for development, every time I can do what I want in Pine Script, I reach for it and never touch matlab, python, R, or anything else.
Weighted version allows you to explicetly include order/time information into the operation, which is essential with every time series, although not widely used in mainstream just as many other obvious and right things. If you think deeply, you'll understand that you can apply a usual non-weighted Fourier to any 2d+ data you can (even if none of these dimensions represent time), because this is a geometric tool in essence. By applying linearly decaying weights inside Fourier transform, you're explicetly saying, "one of these dimensions is Time, and weights represent the order". And obviously you can combine multiple weightings, eg time and another characteristic of each datum, allows you to include another non-spatial dimension in your model.
By doing that, on properly processed (not only stationary but Also centered around zero data), you can get some interesting results that you won't be able to recreate without weights:
^^ A sine wave, centered around zero, period of 16. Gray line made by: DWFT (direct weighted Fourier transform) -> spectral gating -> IWFT (inverse weighted Fourier transform) -> plotting the last value of gated reconstructed data, all applied to expanding window. Look how precisely it follows the original data (the sine wave) with no lag at all. This can't be done by using non-weighted version of Fourier transform.
^^ spectral filtering applied to the whole dataset, calculated on the latest data update
And you should never forget about Fast Fourier Transform, tho it needs recursion...
Section 2: About use cases for quant trading, about this particular implementaion in Pine Script 6 (currently the latest version as of Friday 13, December 2k24).
Given the current state of things, we have certain limits on matrix size on TradingView (and we need big dope matrixes to calculate polynomial regression -> detrend & center our data before Fourier), and recursion is not yet available in Pine Script, so the script works on short datasets only, and requires some time.
A note on detrending. For quality results, Fourier Transform should be applied to not only stationary but also centered around zero data. The rightest way to do detrending of time series
is to fit Cumulative Weighted Moving Polynomial Regression (known as WLSMA in some narrow circles xD) and calculate the deltas between datapoint at time t and this wonderful fit at time t. That's exactly what you see on the main chart of script description: notice the distances between chart and WLSMA, now look lower and see how it matches the distances between zero and purple line in WFT study. Using residuals of one regression fit of the whole dataset makes less sense in time series context, we break some 'time' and order rules in a way, tho not many understand/cares abouit it in mainstream quant industry.
Two ways of using the script:
Spectral Gating aka Spectral filtering. Frequency domain filtering is quite responsive and for a greater computational cost does not introduce a lag the way it works with time-domain filtering. Works this way: direct Fourier transform your data to get frequency & phase info -> compute power spectrum out of it -> zero out all dem freqs that ain't hit your threshold -> inverse Fourier tranform what's left -> repeat at each datapoint plotting the very first value of reconstructed array*. With this you can watch for zero crossings to make appropriate trading decisions.
^^ plot Freq pass to use the script this way, use Level setting to control the intensity of gating. These 3 only available values: -1, 0 and 1, are the general & natural ones.
* if you turn on labels in script's style settings, you see the gray dots perfectly fitting your data. They get recalculated (for the whole dataset) at each update. You call it repainting, this is for analytical & aesthetic purposes. Included for demonstration only.
Finding main/dominant frequency & period. You can use it to set up Length for your other studies, and for analytical purposes simply to understand the periodicity of your data.
^^ plot main frequency/main period to use the script this way. On the screenshot, you can see the script applied to sine wave of period 16, notice how many datapoints it took the algo to figure out the signal's period quite good in expanding window mode
Now what's the next step? You can try applying signal windowing techniques to make it all less data-driven but your ego-driven, make a weighted periodogram or autocorrelogram (check Wiener-Khinchin Theorem ), and maybe whole shiny spectrogram?
... you decide, choice is yours,
The butterfly reflect the doors ...
∞
Points of InterestIndicator for displaying a timed, intraday Range of Price as a Point of Interest (POI) that you may want to track when trading as a potential magnet for price. Quite often you will see Price return to prior days price range before continuing to move. This enables you to track specific portions of a Days Trading session to see what has been revisited and what has not yet been re traded to.
The range is tracked for each trading day between the times that you specify in the Inputs ‘POI Time’ parameter You can also set the Time zone of the Range.
It will mark the Range High and Low for the timed range with lines that can be optionally extended and can be customised in terms of colour, style and width.
It will also Plot a line showing the Equilibrium of the range which is 50% from the High to the Low point of price during the time window that you specified in the ‘POI Time’ Parameter. This can also be customised in terms of visibility, colour, style and width.
You can control an optional Label for the POI Equilibrium Line to include a combination of a user defined prefix, the Date that the POI Equilibrium Line’s range is from and the Price Level of the Equilibrium Line. The colour and size of the label is also configurable
This indicator will also track when a POI Equilibrium Line has been traded to or ‘Tapped’. The tracking can be started after a configurable number of minutes have elapsed from the end of the POI Time window. This can also be customised in terms of visibility, colour, style, extended toggle and width.
Optionally Taps of the POI Equilibrium Level can be counted as valid during specific time windows or session of the day - for example only count taps during New York Morning Trading session.
The indicator uses Lower Time Frame data to compute the Range and 50% / Equilibrium Level so will work accurately on Chart Timeframes up to and including Daily with The POI Time specified down to a Minute resolution.
j trader ModelAn indicator designed to trade indices using the jtrader model and ICT concepts.
jtrader Model:
Below are the key points to trade this model:
Power of 3 is the key element of this model.
Accumulation during pre NY open.NY Open represents 9:30am opening of NY Stock Exchange.
Manipulation(JUDA) immediately after NY open. Juda is a manipulated move by the indices after the session open.
Distribution as a reversal with BOS ,Heatmap preferably during Macros. Distribution is market phase where it moves towards its original expansion during macros. Macros are 20 minute time windows where indices give moves with strong force. Heatmap represent kis point of interests for the trade.
Indicator Features:
Creates a complete window of trading with key elements needed to trade The jtrader Model.
Identify and marks key points of interests (POIs).
Identify and highlights key swing points of Sessions, Days, Weeks, True open etc.
Highlights the NY Open.
Highlights the Macros.
Indicator Settings:
Enable/Disable any POI marking.
Adjust session time ranges.
Adjust enabling of model poi marking time window.
Choose color of choice for highlighting the POI.
Enable/Disable Macros.
This indicator will gradually updated with new features to trade the jtrader model. Your feedback will help us improve and enhance this indicator.
Gaussian Moving Average (GA)The Gaussian moving average (GA) is a technical analysis tool that is used to smooth out price data and identify trends. It is similar to a simple moving average (SMA), but instead of using equal weights for each value in the calculation, it uses a Gaussian distribution to assign weights. This means that the values at the edges of the calculation window have lower weights and are given less importance in the moving average calculation, while the values at the center of the window have higher weights and are given more importance. This helps to reduce the impact of noisy or outlying data points on the moving average and make it more responsive to changes in the underlying trend.
To calculate the GA, the script first defines the standard deviation of the Gaussian distribution. This is a measure of how spread out the values in the distribution are and can be adjusted to change the shape of the curve. The default value in the script is set to one quarter of the length of the calculation window, which gives a bell-shaped curve with a peak at the center of the window.
Next, the script generates an array of indices from 1 to the length of the calculation window. This is used to calculate the weights for each value in the moving average calculation. The weights are calculated using the Gaussian distribution, with the indices as the input values and the standard deviation as a parameter. This produces a set of weights that are highest at the center of the window and decrease towards the edges.
Finally, the script calculates the weighted sum of the values in the calculation window using the weights. This is divided by the sum of the weights to give the moving average value. The resulting moving average is smoother and more responsive to changes in the underlying trend than a simple moving average, making it a useful tool for technical analysis.
Overall, this script is useful for analyzing financial data and identifying trends in the data. By using the Gaussian moving average, the script can smooth out fluctuations in the data and make trends more apparent, which can help traders make more informed decisions.
WaveTrend 3D█ OVERVIEW
WaveTrend 3D (WT3D) is a novel implementation of the famous WaveTrend (WT) indicator and has been completely redesigned from the ground up to address some of the inherent shortcomings associated with the traditional WT algorithm.
█ BACKGROUND
The WaveTrend (WT) indicator has become a widely popular tool for traders in recent years. WT was first ported to PineScript in 2014 by the user @LazyBear, and since then, it has ascended to become one of the Top 5 most popular scripts on TradingView.
The WT algorithm appears to have origins in a lesser-known proprietary algorithm called Trading Channel Index (TCI), created by AIQ Systems in 1986 as an integral part of their commercial software suite, TradingExpert Pro. The software’s reference manual states that “TCI identifies changes in price direction” and is “an adaptation of Donald R. Lambert’s Commodity Channel Index (CCI)”, which was introduced to the world six years earlier in 1980. Interestingly, a vestige of this early beginning can still be seen in the source code of LazyBear’s script, where the final EMA calculation is stored in an intermediate variable called “tci” in the code.
█ IMPLEMENTATION DETAILS
WaveTrend 3D is an alternative implementation of WaveTrend that directly addresses some of the known shortcomings of the indicator, including its unbounded extremes, susceptibility to whipsaw, and lack of insight into other timeframes.
In the canonical WT approach, an exponential moving average (EMA) for a given lookback window is used to assess the variability between price and two other EMAs relative to a second lookback window. Since the difference between the average price and its associated EMA is essentially unbounded, an arbitrary scaling factor of 0.015 is typically applied as a crude form of rescaling but still fails to capture 20-30% of values between the range of -100 to 100. Additionally, the trigger signal for the final EMA (i.e., TCI) crossover-based oscillator is a four-bar simple moving average (SMA), which further contributes to the net lag accumulated by the consecutive EMA calculations in the previous steps.
The core idea behind WT3D is to replace the EMA-based crossover system with modern Digital Signal Processing techniques. By assuming that price action adheres approximately to a Gaussian distribution, it is possible to sidestep the scaling nightmare associated with unbounded price differentials of the original WaveTrend method by focusing instead on the alteration of the underlying Probability Distribution Function (PDF) of the input series. Furthermore, using a signal processing filter such as a Butterworth Filter, we can eliminate the need for consecutive exponential moving averages along with the associated lag they bring.
Ideally, it is convenient to have the resulting probability distribution oscillate between the values of -1 and 1, with the zero line serving as a median. With this objective in mind, it is possible to borrow a common technique from the field of Machine Learning that uses a sigmoid-like activation function to transform our data set of interest. One such function is the hyperbolic tangent function (tanh), which is often used as an activation function in the hidden layers of neural networks due to its unique property of ensuring the values stay between -1 and 1. By taking the first-order derivative of our input series and normalizing it using the quadratic mean, the tanh function performs a high-quality redistribution of the input signal into the desired range of -1 to 1. Finally, using a dual-pole filter such as the Butterworth Filter popularized by John Ehlers, excessive market noise can be filtered out, leaving behind a crisp moving average with minimal lag.
Furthermore, WT3D expands upon the original functionality of WT by providing:
First-class support for multi-timeframe (MTF) analysis
Kernel-based regression for trend reversal confirmation
Various options for signal smoothing and transformation
A unique mode for visualizing an input series as a symmetrical, three-dimensional waveform useful for pattern identification and cycle-related analysis
█ SETTINGS
This is a summary of the settings used in the script listed in roughly the order in which they appear. By default, all default colors are from Google's TensorFlow framework and are considered to be colorblind safe.
Source: The input series. Usually, it is the close or average price, but it can be any series.
Use Mirror: Whether to display a mirror image of the source series; for visualizing the series as a 3D waveform similar to a soundwave.
Use EMA: Whether to use an exponential moving average of the input series.
EMA Length: The length of the exponential moving average.
Use COG: Whether to use the center of gravity of the input series.
COG Length: The length of the center of gravity.
Speed to Emphasize: The target speed to emphasize.
Width: The width of the emphasized line.
Display Kernel Moving Average: Whether to display the kernel moving average of the signal. Like PCA, an unsupervised Machine Learning technique whereby neighboring vectors are projected onto the Principal Component.
Display Kernel Signal: Whether to display the kernel estimator for the emphasized line. Like the Kernel MA, it can show underlying shifts in bias within a more significant trend by the colors reflected on the ribbon itself.
Show Oscillator Lines: Whether to show the oscillator lines.
Offset: The offset of the emphasized oscillator plots.
Fast Length: The length scale factor for the fast oscillator.
Fast Smoothing: The smoothing scale factor for the fast oscillator.
Normal Length: The length scale factor for the normal oscillator.
Normal Smoothing: The smoothing scale factor for the normal frequency.
Slow Length: The length scale factor for the slow oscillator.
Slow Smoothing: The smoothing scale factor for the slow frequency.
Divergence Threshold: The number of bars for the divergence to be considered significant.
Trigger Wave Percent Size: How big the current wave should be relative to the previous wave.
Background Area Transparency Factor: Transparency factor for the background area.
Foreground Area Transparency Factor: Transparency factor for the foreground area.
Background Line Transparency Factor: Transparency factor for the background line.
Foreground Line Transparency Factor: Transparency factor for the foreground line.
Custom Transparency: Transparency of the custom colors.
Total Gradient Steps: The maximum amount of steps supported for a gradient calculation is 256.
Fast Bullish Color: The color of the fast bullish line.
Normal Bullish Color: The color of the normal bullish line.
Slow Bullish Color: The color of the slow bullish line.
Fast Bearish Color: The color of the fast bearish line.
Normal Bearish Color: The color of the normal bearish line.
Slow Bearish Color: The color of the slow bearish line.
Bullish Divergence Signals: The color of the bullish divergence signals.
Bearish Divergence Signals: The color of the bearish divergence signals.
█ ACKNOWLEDGEMENTS
@LazyBear - For authoring the original WaveTrend port on TradingView
@PineCoders - For the beautiful color gradient framework used in this indicator
@veryfid - For the inspiration of using mirrored signals for cycle analysis and using multiple lookback windows as proxies for other timeframes
Singular and Cumulative Volume Delta (SVD+CVD)This a Volume Delta indicator with Cumulative Volume Delta.
I have been studying Volume Delta and CVD trading strategies and indicator styles.
This implementation was developed to test a basic trailing window / oscillator approach.
Script has been republished as public and searchable.
Changelog from private era follows.
Jun 9 (2022)
Release Notes:
Added option to use EMA/SMA based cumulation. This will not scale well with singular data, so default view is still SUM.
Jun 9 (2022)
Release Notes:
Outdated comment correction.
Jun 9 (2022)
Release Notes:
Added default option to normalilze visual scale of MA cumulation types. The averaging creates a singular value sized results, instead of a range-sums. This multiples that candle result by the range length to get a range-sum sized result.
Added option to scale the cumulation size relative to the volume size. 1-to-1 scaling creates singular deltas that can be hard to see with all options on. This allows you to beef them up for visual or weighting purposes.
Jun 15 (2022)
Release Notes: * Added break even level for current delta. Tells where current delta must land for cumulative delta to stay flat.
* Added comparison of historical cumulative levels to current level. The historical levels are the initial values going into current accumulation window.
* Changed title of indicator to be more generic, clear, and searchable.
Jun 15 (2022)
Release Notes: * Added option to have the cumulation cutoff line AFTER or OVER the end of the cumulation window. This change is to ensure the indicator clearly documents it's behavior and avoids confusion on this / last cumulation window semantics.
* Bugfix: Initial levels were pulled from cumulation line which was AFTER end of window. This has been changed to the initial values INSIDE the cumulation window.
* Code cleanup.
June 17th (2022)
Release Notes: Marked as beta because TV confirmed they no longer allow private scripts to be changed to public. (Despite lingering documentation that says otherwise.
June 17th (2022)
Re-published as public.
Rescaled RangeRescaled Range is an implementation of the fractal rescaled ranges developed by Harold Edwin Hurst and Benoit Mandlebrot.
Settings include:
“Window Size” - the number of time periods in a window over which price changes are analyzed. This will generally correspond to your trading horizon and defaults to 15.
“Number of Windows” - the number of “Window Size” intervals to average the rescaled range value over. By looking at a number of such periods, the study captures potential volatility that may have occurred in the recent past. This should be set long enough to capture the current trend (defaults to 63), but not so long to include volatility regimes no longer in play.
Each window in the average is offset by 1 time period from the the others - like a moving average.
This study plots two lines - “Rescaled Range High” which indicates overbought conditions when the price moves above it and “Rescaled Range Low” which indicates oversold conditions when the price moves below it.
This study builds upon the bridge range work of Joe Catanzaro (joecat808) and Caleb Sandfort (calebsandfort). Bridge ranges are used to position the rescaled range with respect to the closing price.
Note: Your time series must have (Window Size + Number of Windows) or more periods of data to complete this study. For example, using the defaults, your time series should have (15+63) = 78 periods or more of data.
Markov Chain [3D] | FractalystWhat exactly is a Markov Chain?
This indicator uses a Markov Chain model to analyze, quantify, and visualize the transitions between market regimes (Bull, Bear, Neutral) on your chart. It dynamically detects these regimes in real-time, calculates transition probabilities, and displays them as animated 3D spheres and arrows, giving traders intuitive insight into current and future market conditions.
How does a Markov Chain work, and how should I read this spheres-and-arrows diagram?
Think of three weather modes: Sunny, Rainy, Cloudy.
Each sphere is one mode. The loop on a sphere means “stay the same next step” (e.g., Sunny again tomorrow).
The arrows leaving a sphere show where things usually go next if they change (e.g., Sunny moving to Cloudy).
Some paths matter more than others. A more prominent loop means the current mode tends to persist. A more prominent outgoing arrow means a change to that destination is the usual next step.
Direction isn’t symmetric: moving Sunny→Cloudy can behave differently than Cloudy→Sunny.
Now relabel the spheres to markets: Bull, Bear, Neutral.
Spheres: market regimes (uptrend, downtrend, range).
Self‑loop: tendency for the current regime to continue on the next bar.
Arrows: the most common next regime if a switch happens.
How to read: Start at the sphere that matches current bar state. If the loop stands out, expect continuation. If one outgoing path stands out, that switch is the typical next step. Opposite directions can differ (Bear→Neutral doesn’t have to match Neutral→Bear).
What states and transitions are shown?
The three market states visualized are:
Bullish (Bull): Upward or strong-market regime.
Bearish (Bear): Downward or weak-market regime.
Neutral: Sideways or range-bound regime.
Bidirectional animated arrows and probability labels show how likely the market is to move from one regime to another (e.g., Bull → Bear or Neutral → Bull).
How does the regime detection system work?
You can use either built-in price returns (based on adaptive Z-score normalization) or supply three custom indicators (such as volume, oscillators, etc.).
Values are statistically normalized (Z-scored) over a configurable lookback period.
The normalized outputs are classified into Bull, Bear, or Neutral zones.
If using three indicators, their regime signals are averaged and smoothed for robustness.
How are transition probabilities calculated?
On every confirmed bar, the algorithm tracks the sequence of detected market states, then builds a rolling window of transitions.
The code maintains a transition count matrix for all regime pairs (e.g., Bull → Bear).
Transition probabilities are extracted for each possible state change using Laplace smoothing for numerical stability, and frequently updated in real-time.
What is unique about the visualization?
3D animated spheres represent each regime and change visually when active.
Animated, bidirectional arrows reveal transition probabilities and allow you to see both dominant and less likely regime flows.
Particles (moving dots) animate along the arrows, enhancing the perception of regime flow direction and speed.
All elements dynamically update with each new price bar, providing a live market map in an intuitive, engaging format.
Can I use custom indicators for regime classification?
Yes! Enable the "Custom Indicators" switch and select any three chart series as inputs. These will be normalized and combined (each with equal weight), broadening the regime classification beyond just price-based movement.
What does the “Lookback Period” control?
Lookback Period (default: 100) sets how much historical data builds the probability matrix. Shorter periods adapt faster to regime changes but may be noisier. Longer periods are more stable but slower to adapt.
How is this different from a Hidden Markov Model (HMM)?
It sets the window for both regime detection and probability calculations. Lower values make the system more reactive, but potentially noisier. Higher values smooth estimates and make the system more robust.
How is this Markov Chain different from a Hidden Markov Model (HMM)?
Markov Chain (as here): All market regimes (Bull, Bear, Neutral) are directly observable on the chart. The transition matrix is built from actual detected regimes, keeping the model simple and interpretable.
Hidden Markov Model: The actual regimes are unobservable ("hidden") and must be inferred from market output or indicator "emissions" using statistical learning algorithms. HMMs are more complex, can capture more subtle structure, but are harder to visualize and require additional machine learning steps for training.
A standard Markov Chain models transitions between observable states using a simple transition matrix, while a Hidden Markov Model assumes the true states are hidden (latent) and must be inferred from observable “emissions” like price or volume data. In practical terms, a Markov Chain is transparent and easier to implement and interpret; an HMM is more expressive but requires statistical inference to estimate hidden states from data.
Markov Chain: states are observable; you directly count or estimate transition probabilities between visible states. This makes it simpler, faster, and easier to validate and tune.
HMM: states are hidden; you only observe emissions generated by those latent states. Learning involves machine learning/statistical algorithms (commonly Baum–Welch/EM for training and Viterbi for decoding) to infer both the transition dynamics and the most likely hidden state sequence from data.
How does the indicator avoid “repainting” or look-ahead bias?
All regime changes and matrix updates happen only on confirmed (closed) bars, so no future data is leaked, ensuring reliable real-time operation.
Are there practical tuning tips?
Tune the Lookback Period for your asset/timeframe: shorter for fast markets, longer for stability.
Use custom indicators if your asset has unique regime drivers.
Watch for rapid changes in transition probabilities as early warning of a possible regime shift.
Who is this indicator for?
Quants and quantitative researchers exploring probabilistic market modeling, especially those interested in regime-switching dynamics and Markov models.
Programmers and system developers who need a probabilistic regime filter for systematic and algorithmic backtesting:
The Markov Chain indicator is ideally suited for programmatic integration via its bias output (1 = Bull, 0 = Neutral, -1 = Bear).
Although the visualization is engaging, the core output is designed for automated, rules-based workflows—not for discretionary/manual trading decisions.
Developers can connect the indicator’s output directly to their Pine Script logic (using input.source()), allowing rapid and robust backtesting of regime-based strategies.
It acts as a plug-and-play regime filter: simply plug the bias output into your entry/exit logic, and you have a scientifically robust, probabilistically-derived signal for filtering, timing, position sizing, or risk regimes.
The MC's output is intentionally "trinary" (1/0/-1), focusing on clear regime states for unambiguous decision-making in code. If you require nuanced, multi-probability or soft-label state vectors, consider expanding the indicator or stacking it with a probability-weighted logic layer in your scripting.
Because it avoids subjectivity, this approach is optimal for systematic quants, algo developers building backtested, repeatable strategies based on probabilistic regime analysis.
What's the mathematical foundation behind this?
The mathematical foundation behind this Markov Chain indicator—and probabilistic regime detection in finance—draws from two principal models: the (standard) Markov Chain and the Hidden Markov Model (HMM).
How to use this indicator programmatically?
The Markov Chain indicator automatically exports a bias value (+1 for Bullish, -1 for Bearish, 0 for Neutral) as a plot visible in the Data Window. This allows you to integrate its regime signal into your own scripts and strategies for backtesting, automation, or live trading.
Step-by-Step Integration with Pine Script (input.source)
Add the Markov Chain indicator to your chart.
This must be done first, since your custom script will "pull" the bias signal from the indicator's plot.
In your strategy, create an input using input.source()
Example:
//@version=5
strategy("MC Bias Strategy Example")
mcBias = input.source(close, "MC Bias Source")
After saving, go to your script’s settings. For the “MC Bias Source” input, select the plot/output of the Markov Chain indicator (typically its bias plot).
Use the bias in your trading logic
Example (long only on Bull, flat otherwise):
if mcBias == 1
strategy.entry("Long", strategy.long)
else
strategy.close("Long")
For more advanced workflows, combine mcBias with additional filters or trailing stops.
How does this work behind-the-scenes?
TradingView’s input.source() lets you use any plot from another indicator as a real-time, “live” data feed in your own script (source).
The selected bias signal is available to your Pine code as a variable, enabling logical decisions based on regime (trend-following, mean-reversion, etc.).
This enables powerful strategy modularity : decouple regime detection from entry/exit logic, allowing fast experimentation without rewriting core signal code.
Integrating 45+ Indicators with Your Markov Chain — How & Why
The Enhanced Custom Indicators Export script exports a massive suite of over 45 technical indicators—ranging from classic momentum (RSI, MACD, Stochastic, etc.) to trend, volume, volatility, and oscillator tools—all pre-calculated, centered/scaled, and available as plots.
// Enhanced Custom Indicators Export - 45 Technical Indicators
// Comprehensive technical analysis suite for advanced market regime detection
//@version=6
indicator('Enhanced Custom Indicators Export | Fractalyst', shorttitle='Enhanced CI Export', overlay=false, scale=scale.right, max_labels_count=500, max_lines_count=500)
// |----- Input Parameters -----| //
momentum_group = "Momentum Indicators"
trend_group = "Trend Indicators"
volume_group = "Volume Indicators"
volatility_group = "Volatility Indicators"
oscillator_group = "Oscillator Indicators"
display_group = "Display Settings"
// Common lengths
length_14 = input.int(14, "Standard Length (14)", minval=1, maxval=100, group=momentum_group)
length_20 = input.int(20, "Medium Length (20)", minval=1, maxval=200, group=trend_group)
length_50 = input.int(50, "Long Length (50)", minval=1, maxval=200, group=trend_group)
// Display options
show_table = input.bool(true, "Show Values Table", group=display_group)
table_size = input.string("Small", "Table Size", options= , group=display_group)
// |----- MOMENTUM INDICATORS (15 indicators) -----| //
// 1. RSI (Relative Strength Index)
rsi_14 = ta.rsi(close, length_14)
rsi_centered = rsi_14 - 50
// 2. Stochastic Oscillator
stoch_k = ta.stoch(close, high, low, length_14)
stoch_d = ta.sma(stoch_k, 3)
stoch_centered = stoch_k - 50
// 3. Williams %R
williams_r = ta.stoch(close, high, low, length_14) - 100
// 4. MACD (Moving Average Convergence Divergence)
= ta.macd(close, 12, 26, 9)
// 5. Momentum (Rate of Change)
momentum = ta.mom(close, length_14)
momentum_pct = (momentum / close ) * 100
// 6. Rate of Change (ROC)
roc = ta.roc(close, length_14)
// 7. Commodity Channel Index (CCI)
cci = ta.cci(close, length_20)
// 8. Money Flow Index (MFI)
mfi = ta.mfi(close, length_14)
mfi_centered = mfi - 50
// 9. Awesome Oscillator (AO)
ao = ta.sma(hl2, 5) - ta.sma(hl2, 34)
// 10. Accelerator Oscillator (AC)
ac = ao - ta.sma(ao, 5)
// 11. Chande Momentum Oscillator (CMO)
cmo = ta.cmo(close, length_14)
// 12. Detrended Price Oscillator (DPO)
dpo = close - ta.sma(close, length_20)
// 13. Price Oscillator (PPO)
ppo = ta.sma(close, 12) - ta.sma(close, 26)
ppo_pct = (ppo / ta.sma(close, 26)) * 100
// 14. TRIX
trix_ema1 = ta.ema(close, length_14)
trix_ema2 = ta.ema(trix_ema1, length_14)
trix_ema3 = ta.ema(trix_ema2, length_14)
trix = ta.roc(trix_ema3, 1) * 10000
// 15. Klinger Oscillator
klinger = ta.ema(volume * (high + low + close) / 3, 34) - ta.ema(volume * (high + low + close) / 3, 55)
// 16. Fisher Transform
fisher_hl2 = 0.5 * (hl2 - ta.lowest(hl2, 10)) / (ta.highest(hl2, 10) - ta.lowest(hl2, 10)) - 0.25
fisher = 0.5 * math.log((1 + fisher_hl2) / (1 - fisher_hl2))
// 17. Stochastic RSI
stoch_rsi = ta.stoch(rsi_14, rsi_14, rsi_14, length_14)
stoch_rsi_centered = stoch_rsi - 50
// 18. Relative Vigor Index (RVI)
rvi_num = ta.swma(close - open)
rvi_den = ta.swma(high - low)
rvi = rvi_den != 0 ? rvi_num / rvi_den : 0
// 19. Balance of Power (BOP)
bop = (close - open) / (high - low)
// |----- TREND INDICATORS (10 indicators) -----| //
// 20. Simple Moving Average Momentum
sma_20 = ta.sma(close, length_20)
sma_momentum = ((close - sma_20) / sma_20) * 100
// 21. Exponential Moving Average Momentum
ema_20 = ta.ema(close, length_20)
ema_momentum = ((close - ema_20) / ema_20) * 100
// 22. Parabolic SAR
sar = ta.sar(0.02, 0.02, 0.2)
sar_trend = close > sar ? 1 : -1
// 23. Linear Regression Slope
lr_slope = ta.linreg(close, length_20, 0) - ta.linreg(close, length_20, 1)
// 24. Moving Average Convergence (MAC)
mac = ta.sma(close, 10) - ta.sma(close, 30)
// 25. Trend Intensity Index (TII)
tii_sum = 0.0
for i = 1 to length_20
tii_sum += close > close ? 1 : 0
tii = (tii_sum / length_20) * 100
// 26. Ichimoku Cloud Components
ichimoku_tenkan = (ta.highest(high, 9) + ta.lowest(low, 9)) / 2
ichimoku_kijun = (ta.highest(high, 26) + ta.lowest(low, 26)) / 2
ichimoku_signal = ichimoku_tenkan > ichimoku_kijun ? 1 : -1
// 27. MESA Adaptive Moving Average (MAMA)
mama_alpha = 2.0 / (length_20 + 1)
mama = ta.ema(close, length_20)
mama_momentum = ((close - mama) / mama) * 100
// 28. Zero Lag Exponential Moving Average (ZLEMA)
zlema_lag = math.round((length_20 - 1) / 2)
zlema_data = close + (close - close )
zlema = ta.ema(zlema_data, length_20)
zlema_momentum = ((close - zlema) / zlema) * 100
// |----- VOLUME INDICATORS (6 indicators) -----| //
// 29. On-Balance Volume (OBV)
obv = ta.obv
// 30. Volume Rate of Change (VROC)
vroc = ta.roc(volume, length_14)
// 31. Price Volume Trend (PVT)
pvt = ta.pvt
// 32. Negative Volume Index (NVI)
nvi = 0.0
nvi := volume < volume ? nvi + ((close - close ) / close ) * nvi : nvi
// 33. Positive Volume Index (PVI)
pvi = 0.0
pvi := volume > volume ? pvi + ((close - close ) / close ) * pvi : pvi
// 34. Volume Oscillator
vol_osc = ta.sma(volume, 5) - ta.sma(volume, 10)
// 35. Ease of Movement (EOM)
eom_distance = high - low
eom_box_height = volume / 1000000
eom = eom_box_height != 0 ? eom_distance / eom_box_height : 0
eom_sma = ta.sma(eom, length_14)
// 36. Force Index
force_index = volume * (close - close )
force_index_sma = ta.sma(force_index, length_14)
// |----- VOLATILITY INDICATORS (10 indicators) -----| //
// 37. Average True Range (ATR)
atr = ta.atr(length_14)
atr_pct = (atr / close) * 100
// 38. Bollinger Bands Position
bb_basis = ta.sma(close, length_20)
bb_dev = 2.0 * ta.stdev(close, length_20)
bb_upper = bb_basis + bb_dev
bb_lower = bb_basis - bb_dev
bb_position = bb_dev != 0 ? (close - bb_basis) / bb_dev : 0
bb_width = bb_dev != 0 ? (bb_upper - bb_lower) / bb_basis * 100 : 0
// 39. Keltner Channels Position
kc_basis = ta.ema(close, length_20)
kc_range = ta.ema(ta.tr, length_20)
kc_upper = kc_basis + (2.0 * kc_range)
kc_lower = kc_basis - (2.0 * kc_range)
kc_position = kc_range != 0 ? (close - kc_basis) / kc_range : 0
// 40. Donchian Channels Position
dc_upper = ta.highest(high, length_20)
dc_lower = ta.lowest(low, length_20)
dc_basis = (dc_upper + dc_lower) / 2
dc_position = (dc_upper - dc_lower) != 0 ? (close - dc_basis) / (dc_upper - dc_lower) : 0
// 41. Standard Deviation
std_dev = ta.stdev(close, length_20)
std_dev_pct = (std_dev / close) * 100
// 42. Relative Volatility Index (RVI)
rvi_up = ta.stdev(close > close ? close : 0, length_14)
rvi_down = ta.stdev(close < close ? close : 0, length_14)
rvi_total = rvi_up + rvi_down
rvi_volatility = rvi_total != 0 ? (rvi_up / rvi_total) * 100 : 50
// 43. Historical Volatility
hv_returns = math.log(close / close )
hv = ta.stdev(hv_returns, length_20) * math.sqrt(252) * 100
// 44. Garman-Klass Volatility
gk_vol = math.log(high/low) * math.log(high/low) - (2*math.log(2)-1) * math.log(close/open) * math.log(close/open)
gk_volatility = math.sqrt(ta.sma(gk_vol, length_20)) * 100
// 45. Parkinson Volatility
park_vol = math.log(high/low) * math.log(high/low)
parkinson = math.sqrt(ta.sma(park_vol, length_20) / (4 * math.log(2))) * 100
// 46. Rogers-Satchell Volatility
rs_vol = math.log(high/close) * math.log(high/open) + math.log(low/close) * math.log(low/open)
rogers_satchell = math.sqrt(ta.sma(rs_vol, length_20)) * 100
// |----- OSCILLATOR INDICATORS (5 indicators) -----| //
// 47. Elder Ray Index
elder_bull = high - ta.ema(close, 13)
elder_bear = low - ta.ema(close, 13)
elder_power = elder_bull + elder_bear
// 48. Schaff Trend Cycle (STC)
stc_macd = ta.ema(close, 23) - ta.ema(close, 50)
stc_k = ta.stoch(stc_macd, stc_macd, stc_macd, 10)
stc_d = ta.ema(stc_k, 3)
stc = ta.stoch(stc_d, stc_d, stc_d, 10)
// 49. Coppock Curve
coppock_roc1 = ta.roc(close, 14)
coppock_roc2 = ta.roc(close, 11)
coppock = ta.wma(coppock_roc1 + coppock_roc2, 10)
// 50. Know Sure Thing (KST)
kst_roc1 = ta.roc(close, 10)
kst_roc2 = ta.roc(close, 15)
kst_roc3 = ta.roc(close, 20)
kst_roc4 = ta.roc(close, 30)
kst = ta.sma(kst_roc1, 10) + 2*ta.sma(kst_roc2, 10) + 3*ta.sma(kst_roc3, 10) + 4*ta.sma(kst_roc4, 15)
// 51. Percentage Price Oscillator (PPO)
ppo_line = ((ta.ema(close, 12) - ta.ema(close, 26)) / ta.ema(close, 26)) * 100
ppo_signal = ta.ema(ppo_line, 9)
ppo_histogram = ppo_line - ppo_signal
// |----- PLOT MAIN INDICATORS -----| //
// Plot key momentum indicators
plot(rsi_centered, title="01_RSI_Centered", color=color.purple, linewidth=1)
plot(stoch_centered, title="02_Stoch_Centered", color=color.blue, linewidth=1)
plot(williams_r, title="03_Williams_R", color=color.red, linewidth=1)
plot(macd_histogram, title="04_MACD_Histogram", color=color.orange, linewidth=1)
plot(cci, title="05_CCI", color=color.green, linewidth=1)
// Plot trend indicators
plot(sma_momentum, title="06_SMA_Momentum", color=color.navy, linewidth=1)
plot(ema_momentum, title="07_EMA_Momentum", color=color.maroon, linewidth=1)
plot(sar_trend, title="08_SAR_Trend", color=color.teal, linewidth=1)
plot(lr_slope, title="09_LR_Slope", color=color.lime, linewidth=1)
plot(mac, title="10_MAC", color=color.fuchsia, linewidth=1)
// Plot volatility indicators
plot(atr_pct, title="11_ATR_Pct", color=color.yellow, linewidth=1)
plot(bb_position, title="12_BB_Position", color=color.aqua, linewidth=1)
plot(kc_position, title="13_KC_Position", color=color.olive, linewidth=1)
plot(std_dev_pct, title="14_StdDev_Pct", color=color.silver, linewidth=1)
plot(bb_width, title="15_BB_Width", color=color.gray, linewidth=1)
// Plot volume indicators
plot(vroc, title="16_VROC", color=color.blue, linewidth=1)
plot(eom_sma, title="17_EOM", color=color.red, linewidth=1)
plot(vol_osc, title="18_Vol_Osc", color=color.green, linewidth=1)
plot(force_index_sma, title="19_Force_Index", color=color.orange, linewidth=1)
plot(obv, title="20_OBV", color=color.purple, linewidth=1)
// Plot additional oscillators
plot(ao, title="21_Awesome_Osc", color=color.navy, linewidth=1)
plot(cmo, title="22_CMO", color=color.maroon, linewidth=1)
plot(dpo, title="23_DPO", color=color.teal, linewidth=1)
plot(trix, title="24_TRIX", color=color.lime, linewidth=1)
plot(fisher, title="25_Fisher", color=color.fuchsia, linewidth=1)
// Plot more momentum indicators
plot(mfi_centered, title="26_MFI_Centered", color=color.yellow, linewidth=1)
plot(ac, title="27_AC", color=color.aqua, linewidth=1)
plot(ppo_pct, title="28_PPO_Pct", color=color.olive, linewidth=1)
plot(stoch_rsi_centered, title="29_StochRSI_Centered", color=color.silver, linewidth=1)
plot(klinger, title="30_Klinger", color=color.gray, linewidth=1)
// Plot trend continuation
plot(tii, title="31_TII", color=color.blue, linewidth=1)
plot(ichimoku_signal, title="32_Ichimoku_Signal", color=color.red, linewidth=1)
plot(mama_momentum, title="33_MAMA_Momentum", color=color.green, linewidth=1)
plot(zlema_momentum, title="34_ZLEMA_Momentum", color=color.orange, linewidth=1)
plot(bop, title="35_BOP", color=color.purple, linewidth=1)
// Plot volume continuation
plot(nvi, title="36_NVI", color=color.navy, linewidth=1)
plot(pvi, title="37_PVI", color=color.maroon, linewidth=1)
plot(momentum_pct, title="38_Momentum_Pct", color=color.teal, linewidth=1)
plot(roc, title="39_ROC", color=color.lime, linewidth=1)
plot(rvi, title="40_RVI", color=color.fuchsia, linewidth=1)
// Plot volatility continuation
plot(dc_position, title="41_DC_Position", color=color.yellow, linewidth=1)
plot(rvi_volatility, title="42_RVI_Volatility", color=color.aqua, linewidth=1)
plot(hv, title="43_Historical_Vol", color=color.olive, linewidth=1)
plot(gk_volatility, title="44_GK_Volatility", color=color.silver, linewidth=1)
plot(parkinson, title="45_Parkinson_Vol", color=color.gray, linewidth=1)
// Plot final oscillators
plot(rogers_satchell, title="46_RS_Volatility", color=color.blue, linewidth=1)
plot(elder_power, title="47_Elder_Power", color=color.red, linewidth=1)
plot(stc, title="48_STC", color=color.green, linewidth=1)
plot(coppock, title="49_Coppock", color=color.orange, linewidth=1)
plot(kst, title="50_KST", color=color.purple, linewidth=1)
// Plot final indicators
plot(ppo_histogram, title="51_PPO_Histogram", color=color.navy, linewidth=1)
plot(pvt, title="52_PVT", color=color.maroon, linewidth=1)
// |----- Reference Lines -----| //
hline(0, "Zero Line", color=color.gray, linestyle=hline.style_dashed, linewidth=1)
hline(50, "Midline", color=color.gray, linestyle=hline.style_dotted, linewidth=1)
hline(-50, "Lower Midline", color=color.gray, linestyle=hline.style_dotted, linewidth=1)
hline(25, "Upper Threshold", color=color.gray, linestyle=hline.style_dotted, linewidth=1)
hline(-25, "Lower Threshold", color=color.gray, linestyle=hline.style_dotted, linewidth=1)
// |----- Enhanced Information Table -----| //
if show_table and barstate.islast
table_position = position.top_right
table_text_size = table_size == "Tiny" ? size.tiny : table_size == "Small" ? size.small : size.normal
var table info_table = table.new(table_position, 3, 18, bgcolor=color.new(color.white, 85), border_width=1, border_color=color.gray)
// Headers
table.cell(info_table, 0, 0, 'Category', text_color=color.black, text_size=table_text_size, bgcolor=color.new(color.blue, 70))
table.cell(info_table, 1, 0, 'Indicator', text_color=color.black, text_size=table_text_size, bgcolor=color.new(color.blue, 70))
table.cell(info_table, 2, 0, 'Value', text_color=color.black, text_size=table_text_size, bgcolor=color.new(color.blue, 70))
// Key Momentum Indicators
table.cell(info_table, 0, 1, 'MOMENTUM', text_color=color.purple, text_size=table_text_size, bgcolor=color.new(color.purple, 90))
table.cell(info_table, 1, 1, 'RSI Centered', text_color=color.purple, text_size=table_text_size)
table.cell(info_table, 2, 1, str.tostring(rsi_centered, '0.00'), text_color=color.purple, text_size=table_text_size)
table.cell(info_table, 0, 2, '', text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 1, 2, 'Stoch Centered', text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 2, 2, str.tostring(stoch_centered, '0.00'), text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 0, 3, '', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 1, 3, 'Williams %R', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 2, 3, str.tostring(williams_r, '0.00'), text_color=color.red, text_size=table_text_size)
table.cell(info_table, 0, 4, '', text_color=color.orange, text_size=table_text_size)
table.cell(info_table, 1, 4, 'MACD Histogram', text_color=color.orange, text_size=table_text_size)
table.cell(info_table, 2, 4, str.tostring(macd_histogram, '0.000'), text_color=color.orange, text_size=table_text_size)
table.cell(info_table, 0, 5, '', text_color=color.green, text_size=table_text_size)
table.cell(info_table, 1, 5, 'CCI', text_color=color.green, text_size=table_text_size)
table.cell(info_table, 2, 5, str.tostring(cci, '0.00'), text_color=color.green, text_size=table_text_size)
// Key Trend Indicators
table.cell(info_table, 0, 6, 'TREND', text_color=color.navy, text_size=table_text_size, bgcolor=color.new(color.navy, 90))
table.cell(info_table, 1, 6, 'SMA Momentum %', text_color=color.navy, text_size=table_text_size)
table.cell(info_table, 2, 6, str.tostring(sma_momentum, '0.00'), text_color=color.navy, text_size=table_text_size)
table.cell(info_table, 0, 7, '', text_color=color.maroon, text_size=table_text_size)
table.cell(info_table, 1, 7, 'EMA Momentum %', text_color=color.maroon, text_size=table_text_size)
table.cell(info_table, 2, 7, str.tostring(ema_momentum, '0.00'), text_color=color.maroon, text_size=table_text_size)
table.cell(info_table, 0, 8, '', text_color=color.teal, text_size=table_text_size)
table.cell(info_table, 1, 8, 'SAR Trend', text_color=color.teal, text_size=table_text_size)
table.cell(info_table, 2, 8, str.tostring(sar_trend, '0'), text_color=color.teal, text_size=table_text_size)
table.cell(info_table, 0, 9, '', text_color=color.lime, text_size=table_text_size)
table.cell(info_table, 1, 9, 'Linear Regression', text_color=color.lime, text_size=table_text_size)
table.cell(info_table, 2, 9, str.tostring(lr_slope, '0.000'), text_color=color.lime, text_size=table_text_size)
// Key Volatility Indicators
table.cell(info_table, 0, 10, 'VOLATILITY', text_color=color.yellow, text_size=table_text_size, bgcolor=color.new(color.yellow, 90))
table.cell(info_table, 1, 10, 'ATR %', text_color=color.yellow, text_size=table_text_size)
table.cell(info_table, 2, 10, str.tostring(atr_pct, '0.00'), text_color=color.yellow, text_size=table_text_size)
table.cell(info_table, 0, 11, '', text_color=color.aqua, text_size=table_text_size)
table.cell(info_table, 1, 11, 'BB Position', text_color=color.aqua, text_size=table_text_size)
table.cell(info_table, 2, 11, str.tostring(bb_position, '0.00'), text_color=color.aqua, text_size=table_text_size)
table.cell(info_table, 0, 12, '', text_color=color.olive, text_size=table_text_size)
table.cell(info_table, 1, 12, 'KC Position', text_color=color.olive, text_size=table_text_size)
table.cell(info_table, 2, 12, str.tostring(kc_position, '0.00'), text_color=color.olive, text_size=table_text_size)
// Key Volume Indicators
table.cell(info_table, 0, 13, 'VOLUME', text_color=color.blue, text_size=table_text_size, bgcolor=color.new(color.blue, 90))
table.cell(info_table, 1, 13, 'Volume ROC', text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 2, 13, str.tostring(vroc, '0.00'), text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 0, 14, '', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 1, 14, 'EOM', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 2, 14, str.tostring(eom_sma, '0.000'), text_color=color.red, text_size=table_text_size)
// Key Oscillators
table.cell(info_table, 0, 15, 'OSCILLATORS', text_color=color.purple, text_size=table_text_size, bgcolor=color.new(color.purple, 90))
table.cell(info_table, 1, 15, 'Awesome Osc', text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 2, 15, str.tostring(ao, '0.000'), text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 0, 16, '', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 1, 16, 'Fisher Transform', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 2, 16, str.tostring(fisher, '0.000'), text_color=color.red, text_size=table_text_size)
// Summary Statistics
table.cell(info_table, 0, 17, 'SUMMARY', text_color=color.black, text_size=table_text_size, bgcolor=color.new(color.gray, 70))
table.cell(info_table, 1, 17, 'Total Indicators: 52', text_color=color.black, text_size=table_text_size)
regime_color = rsi_centered > 10 ? color.green : rsi_centered < -10 ? color.red : color.gray
regime_text = rsi_centered > 10 ? "BULLISH" : rsi_centered < -10 ? "BEARISH" : "NEUTRAL"
table.cell(info_table, 2, 17, regime_text, text_color=regime_color, text_size=table_text_size)
This makes it the perfect “indicator backbone” for quantitative and systematic traders who want to prototype, combine, and test new regime detection models—especially in combination with the Markov Chain indicator.
How to use this script with the Markov Chain for research and backtesting:
Add the Enhanced Indicator Export to your chart.
Every calculated indicator is available as an individual data stream.
Connect the indicator(s) you want as custom input(s) to the Markov Chain’s “Custom Indicators” option.
In the Markov Chain indicator’s settings, turn ON the custom indicator mode.
For each of the three custom indicator inputs, select the exported plot from the Enhanced Export script—the menu lists all 45+ signals by name.
This creates a powerful, modular regime-detection engine where you can mix-and-match momentum, trend, volume, or custom combinations for advanced filtering.
Backtest regime logic directly.
Once you’ve connected your chosen indicators, the Markov Chain script performs regime detection (Bull/Neutral/Bear) based on your selected features—not just price returns.
The regime detection is robust, automatically normalized (using Z-score), and outputs bias (1, -1, 0) for plug-and-play integration.
Export the regime bias for programmatic use.
As described above, use input.source() in your Pine Script strategy or system and link the bias output.
You can now filter signals, control trade direction/size, or design pairs-trading that respect true, indicator-driven market regimes.
With this framework, you’re not limited to static or simplistic regime filters. You can rigorously define, test, and refine what “market regime” means for your strategies—using the technical features that matter most to you.
Optimize your signal generation by backtesting across a universe of meaningful indicator blends.
Enhance risk management with objective, real-time regime boundaries.
Accelerate your research: iterate quickly, swap indicator components, and see results with minimal code changes.
Automate multi-asset or pairs-trading by integrating regime context directly into strategy logic.
Add both scripts to your chart, connect your preferred features, and start investigating your best regime-based trades—entirely within the TradingView ecosystem.
References & Further Reading
Ang, A., & Bekaert, G. (2002). “Regime Switches in Interest Rates.” Journal of Business & Economic Statistics, 20(2), 163–182.
Hamilton, J. D. (1989). “A New Approach to the Economic Analysis of Nonstationary Time Series and the Business Cycle.” Econometrica, 57(2), 357–384.
Markov, A. A. (1906). "Extension of the Limit Theorems of Probability Theory to a Sum of Variables Connected in a Chain." The Notes of the Imperial Academy of Sciences of St. Petersburg.
Guidolin, M., & Timmermann, A. (2007). “Asset Allocation under Multivariate Regime Switching.” Journal of Economic Dynamics and Control, 31(11), 3503–3544.
Murphy, J. J. (1999). Technical Analysis of the Financial Markets. New York Institute of Finance.
Brock, W., Lakonishok, J., & LeBaron, B. (1992). “Simple Technical Trading Rules and the Stochastic Properties of Stock Returns.” Journal of Finance, 47(5), 1731–1764.
Zucchini, W., MacDonald, I. L., & Langrock, R. (2017). Hidden Markov Models for Time Series: An Introduction Using R (2nd ed.). Chapman and Hall/CRC.
On Quantitative Finance and Markov Models:
Lo, A. W., & Hasanhodzic, J. (2009). The Heretics of Finance: Conversations with Leading Practitioners of Technical Analysis. Bloomberg Press.
Patterson, S. (2016). The Man Who Solved the Market: How Jim Simons Launched the Quant Revolution. Penguin Press.
TradingView Pine Script Documentation: www.tradingview.com
TradingView Blog: “Use an Input From Another Indicator With Your Strategy” www.tradingview.com
GeeksforGeeks: “What is the Difference Between Markov Chains and Hidden Markov Models?” www.geeksforgeeks.org
What makes this indicator original and unique?
- On‑chart, real‑time Markov. The chain is drawn directly on your chart. You see the current regime, its tendency to stay (self‑loop), and the usual next step (arrows) as bars confirm.
- Source‑agnostic by design. The engine runs on any series you select via input.source() — price, your own oscillator, a composite score, anything you compute in the script.
- Automatic normalization + regime mapping. Different inputs live on different scales. The script standardizes your chosen source and maps it into clear regimes (e.g., Bull / Bear / Neutral) without you micromanaging thresholds each time.
- Rolling, bar‑by‑bar learning. Transition tendencies are computed from a rolling window of confirmed bars. What you see is exactly what the market did in that window.
- Fast experimentation. Switch the source, adjust the window, and the Markov view updates instantly. It’s a rapid way to test ideas and feel regime persistence/switch behavior.
Integrate your own signals (using input.source())
- In settings, choose the Source . This is powered by input.source() .
- Feed it price, an indicator you compute inside the script, or a custom composite series.
- The script will automatically normalize that series and process it through the Markov engine, mapping it to regimes and updating the on‑chart spheres/arrows in real time.
Credits:
Deep gratitude to @RicardoSantos for both the foundational Markov chain processing engine and inspiring open-source contributions, which made advanced probabilistic market modeling accessible to the TradingView community.
Special thanks to @Alien_Algorithms for the innovative and visually stunning 3D sphere logic that powers the indicator’s animated, regime-based visualization.
Disclaimer
This tool summarizes recent behavior. It is not financial advice and not a guarantee of future results.
Price Tracker/galgoomThis indicator is designed for Renko chart traders who want to combine price action relative to a key line (qLine) with Moneyball buy/sell signals as a confirmation. It helps filter trades so you only get signals when both conditions align within a chosen time window.
How It Works
First Event – Price Trigger
Detects when the Renko close crosses above/below your selected qLine plot from the qPro indicator.
You can choose between:
Cross – only triggers on an actual crossover/crossunder.
State (Close) – triggers whenever price closes above/below qLine.
Second Event – Moneyball Confirmation
Waits for Moneyball’s Buy Signal (for long) or Bear/Sell Signal (for short) plot to fire.
You select the exact Moneyball plot from the source menu.
You can specify how the Moneyball signal is interpreted (== 1, >= 1, or any nonzero value).
Sequential Logic
The Moneyball signal must occur within N Renko bricks after the price event.
The final buy/sell signal is printed on the Moneyball bar.
Key Features
Works natively on Renko charts.
Adjustable confirmation window (0–5 bricks).
Flexible detection for both qLine and Moneyball signals.
Customizable label sizes, arrow display, and alerts.
Alerts fire for both buy and sell conditions:
BUY: qLine ➜ Moneyball Buy
SELL: qLine ➜ Moneyball Sell
Inputs
qLine Source – Pick the qPro qLine plot.
Price Event Type – Cross or State.
Moneyball Buy/Sell Signal Plots – Select the correct plots from your Moneyball indicator.
Confirmation Window – Bars allowed between events.
Visual Settings – Label size, arrow visibility, etc.
Use Case
Ideal for traders who:
Want a double-confirmation entry system.
Use Renko charts for cleaner trend detection.
Already have qPro and Moneyball loaded, but want an automated, rule-based confluence check.
38 minutes ago
Release Notes
This indicator is designed for Renko chart traders who want to combine price action relative to a key line (qLine) with Moneyball buy/sell signals as a confirmation. It helps filter trades so you only get signals when both conditions align within a chosen time window.
How It Works
First Event – Price Trigger
Detects when the Renko close crosses above/below your selected qLine plot from the qPro indicator.
You can choose between:
Cross – only triggers on an actual crossover/crossunder.
State (Close) – triggers whenever price closes above/below qLine.
Second Event – Moneyball Confirmation
Waits for Moneyball’s Buy Signal (for long) or Bear/Sell Signal (for short) plot to fire.
You select the exact Moneyball plot from the source menu.
You can specify how the Moneyball signal is interpreted (== 1, >= 1, or any nonzero value).
Sequential Logic
The Moneyball signal must occur within N Renko bricks after the price event.
The final buy/sell signal is printed on the Moneyball bar.
Key Features
Works natively on Renko charts.
Adjustable confirmation window (0–5 bricks).
Flexible detection for both qLine and Moneyball signals.
Customizable label sizes, arrow display, and alerts.
Alerts fire for both buy and sell conditions:
BUY: qLine ➜ Moneyball Buy
SELL: qLine ➜ Moneyball Sell
Inputs
qLine Source – Pick the qPro qLine plot.
Price Event Type – Cross or State.
Moneyball Buy/Sell Signal Plots – Select the correct plots from your Moneyball indicator.
Confirmation Window – Bars allowed between events.
Visual Settings – Label size, arrow visibility, etc.
Use Case
Ideal for traders who:
Want a double-confirmation entry system.
Use Renko charts for cleaner trend detection.
Already have qPro and Moneyball loaded, but want an automated, rule-based confluence check.
Opening-Range BreakoutNote: Default trading date range looks mediocre. Set date range to "Entire History" to see full effect of the strategy. 50.91% profitable trades, 1.178 profit factor, steady profits and limited drawdown. Total P&L: $154,141.18, Max Drawdown: $18,624.36. High R^2
█ Overview
The Opening-Range Breakout strategy is a mechanical, session‑based day‑trading system designed to capture the initial burst of directional momentum immediately following the market open. It defines a user‑configurable “opening range” window, measures its high and low boundaries, then places breakout stop orders at those levels once the range closes. Built‑in filters on minimum range width, reward‑to‑risk ratios, and optional reversal logic help refine entries and manage risk dynamically.
█ How It Works
Opening‑Range Formation
Between 9:30–10:15 AM ET (configurable), the script tracks the highest high and lowest low to form the day’s opening range box.
On the first bar after the range window closes, the range high (OR_high) and low (OR_low) are “locked in.”
Range‑Width Filter
To avoid false breakouts in low‑volatility mornings, the range must be at least X% of the current price (default 0.35%).
If the measured opening-range width < minimum threshold, no orders are placed that day.
Entry & Order Placement
Long: a stop‑buy order at the opening‑range high.
Short: a stop‑sell order at the opening‑range low.
Only one side can trigger (or both if reverse logic is enabled after a losing trade).
Risk Management
Once triggered, each trade uses an ATR‑style stop-loss defined as a percentage retracement of the range (default 50% of range width).
Profit target is set at a configurable Reward/Risk Ratio (default 1.1×).
Optional: Reverse on Stop‑Loss – if the initial breakout loses, immediately reverse into the opposite side on the same day.
Session Exit
Any open positions are closed at the end of the regular trading day (default 3:45 PM ET window end, with hard flat at session close).
Visual cues are provided via green (range high) and red (range low) step‑line plots directly on the chart, allowing you to see the range box and breakout triggers in real time.
█ Why It Works
Early Momentum Capture: The first 15 – 60 minutes of trading encapsulate overnight news digestion and institutional order flow, creating a well‑defined volatility “range.”
Mechanical Discipline: Clear, rule‑based entries and exits remove emotional guesswork, ensuring consistency.
Volatility Filtering: By requiring a minimum range width, the system avoids choppy, low‑range days where false breakouts are common.
Dynamic Sizing: Stops and targets scale with the opening range, adapting automatically to each day’s volatility environment.
█ How to Use
Set Your Instruments & Timeframe
-Apply to any futures contract on a 1‑ to 5‑minute chart.
-Ensure chart timezone is set to America/New_York.
Configure Inputs
-Opening‑Range Window: e.g. “0930-1015” for a 45‑minute range.
-Min. OR Width (%): e.g. 0.35 for 0.35% of current price.
-Reward/Risk Ratio: e.g. 1.1 for a modest profit target above your stop.
-Max OR Retracement %: e.g. 50 to set stop at 50% of range width.
-One Trade Per Day: toggle to limit to a single breakout.
-Reverse on Stop Loss: toggle to flip direction after a losing breakout.
Monitor the Chart
-Watch the green and red range boundaries form during the session open.
-Orders will automatically submit on the first bar after the range window closes, conditioned on your filters.
Review & Adjust
-Backtest across multiple months to validate performance on your preferred contract.
-Tweak range duration, minimum width, and R/R multiple to fit your risk tolerance and desired win‑rate vs. expectancy balance.
█ Settings Reference
Input Defaults
Opening‑Range Window - Time window to form OR (HHMM-HHMM) - 0930–1015
Regular Trading Day - Full session for EOD flat (HHMM-HHMM) - 0930–1545
Min. OR Width (%) - Minimum OR size as % of close to trigger orders - 0.35
Reward/Risk Ratio - Profit target multiple of stop‑loss distance - 1.1
Max OR Retracement (%) - % of OR width to use as stop‑loss distance - 50
One Trade Per Day - Limit to a single breakout order per day - false
Reverse on Stop Loss - Reverse direction immediately after a losing trade - true
Disclaimer
This strategy description and any accompanying code are provided for educational purposes only and do not constitute financial advice or a solicitation to trade. Futures trading involves substantial risk, including possible loss of capital. Past performance is not indicative of future results. Traders should assess their own risk tolerance and conduct thorough backtesting and forward-testing before committing real capital.
The VoVix Experiment The VoVix Experiment
The VoVix Experiment is a next-generation, regime-aware, volatility-adaptive trading strategy for futures, indices, and more. It combines a proprietary VoVix (volatility-of-volatility) anomaly detector with price structure clustering and critical point logic, only trading when multiple independent signals align. The system is designed for robustness, transparency, and real-world execution.
Logic:
VoVix Regime Engine: Detects pre-move volatility anomalies using a fast/slow ATR ratio, normalized by Z-score. Only trades when a true regime spike is detected, not just random volatility.
Cluster & Critical Point Filters: Price structure and volatility clustering must confirm the VoVix signal, reducing false positives and whipsaws.
Adaptive Sizing: Position size scales up for “super-spikes” and down for normal events, always within user-defined min/max.
Session Control: Trades only during user-defined hours and days, avoiding illiquid or high-risk periods.
Visuals: Aurora Flux Bands (From another Original of Mine (Options Flux Flow): glow and change color on signals, with a live dashboard, regime heatmap, and VoVix progression bar for instant insight.
Backtest Settings
Initial capital: $10,000
Commission: Conservative, realistic roundtrip cost:
15–20 per contract (including slippage per side) I set this to $25
Slippage: 3 ticks per trade
Symbol: CME_MINI:NQ1!
Timeframe: 15 min (but works on all timeframes)
Order size: Adaptive, 1–2 contracts
Session: 5:00–15:00 America/Chicago (default, fully adjustable)
Why these settings?
These settings are intentionally strict and realistic, reflecting the true costs and risks of live trading. The 10,000 account size is accessible for most retail traders. 25/contract including 3 ticks of slippage are on the high side for MNQ, ensuring the strategy is not curve-fit to perfect fills. If it works here, it will work in real conditions.
Forward Testing: (This is no guarantee. I've provided these results to show that executions perform as intended. Test were done on Tradovate)
ALL TRADES
Gross P/L: $12,907.50
# of Trades: 64
# of Contracts: 186
Avg. Trade Time: 1h 55min 52sec
Longest Trade Time: 55h 46min 53sec
% Profitable Trades: 59.38%
Expectancy: $201.68
Trade Fees & Comm.: $(330.95)
Total P/L: $12,576.55
Winning Trades: 59.38%
Breakeven Trades: 3.12%
Losing Trades: 37.50%
Link: www.dropbox.com
Inputs & Tooltips
VoVix Regime Execution: Enable/disable the core VoVix anomaly detector.
Volatility Clustering: Require price/volatility clusters to confirm VoVix signals.
Critical Point Detector: Require price to be at a statistically significant distance from the mean (regime break).
VoVix Fast ATR Length: Short ATR for fast volatility detection (lower = more sensitive).
VoVix Slow ATR Length: Long ATR for baseline regime (higher = more stable).
VoVix Z-Score Window: Lookback for Z-score normalization (higher = smoother, lower = more reactive).
VoVix Entry Z-Score: Minimum Z-score for a VoVix spike to trigger a trade.
VoVix Exit Z-Score: Z-score below which the regime is considered decayed (exit).
VoVix Local Max Window: Bars to check for local maximum in VoVix (higher = stricter).
VoVix Super-Spike Z-Score: Z-score for “super” regime events (scales up position size).
Min/Max Contracts: Adaptive position sizing range.
Session Start/End Hour: Only trade between these hours (exchange time).
Allow Weekend Trading: Enable/disable trading on weekends.
Session Timezone: Timezone for session filter (e.g., America/Chicago for CME).
Show Trade Labels: Show/hide entry/exit labels on chart.
Flux Glow Opacity: Opacity of Aurora Flux Bands (0–100).
Flux Band EMA Length: EMA period for band center.
Flux Band ATR Multiplier: Width of bands (higher = wider).
Compliance & Transparency
* No hidden logic, no repainting, no pyramiding.
* All signals, sizing, and exits are fully explained and visible.
* Backtest settings are stricter than most real accounts.
* All visuals are directly tied to the strategy logic.
* This is not a mashup or cosmetic overlay; every component is original and justified.
Disclaimer
Trading is risky. This script is for educational and research purposes only. Do not trade with money you cannot afford to lose. Past performance is not indicative of future results. Always test in simulation before live trading.
Proprietary Logic & Originality Statement
This script, “The VoVix Experiment,” is the result of original research and development. All core logic, algorithms, and visualizations—including the VoVix regime detection engine, adaptive execution, volatility/divergence bands, and dashboard—are proprietary and unique to this project.
1. VoVix Regime Logic
The concept of “volatility of volatility” (VoVix) is an original quant idea, not a standard indicator. The implementation here (fast/slow ATR ratio, Z-score normalization, local max logic, super-spike scaling) is custom and not found in public TradingView scripts.
2. Cluster & Critical Point Logic
Volatility clustering and “critical point” detection (using price distance from a rolling mean and standard deviation) are general quant concepts, but the way they are combined and filtered here is unique to this script. The specific logic for “clustered chop” and “critical point” is not a copy of any public indicator.
3. Adaptive Sizing
The adaptive sizing logic (scaling contracts based on regime strength) is custom and not a standard TradingView feature or public script.
4. Time Block/Session Control
The session filter is a common feature in many strategies, but the implementation here (with timezone and weekend control) is written from scratch.
5. Aurora Flux Bands (From another Original of Mine (Options Flux Flow)
The “glowing” bands are inspired by the idea of volatility bands (like Bollinger Bands or Keltner Channels), but the visual effect, color logic, and integration with regime signals are original to this script.
6. Dashboard, Watermark, and Metrics
The dashboard, real-time Sharpe/Sortino, and VoVix progression bar are all custom code, not copied from any public script.
What is “standard” or “common quant practice”?
Using ATR, EMA, and Z-score are standard quant tools, but the way they are combined, filtered, and visualized here is unique. The structure and logic of this script are original and not a mashup of public code.
This script is 100% original work. All logic, visuals, and execution are custom-coded for this project. No code or logic is directly copied from any public or private script.
Use with discipline. Trade your edge.
— Dskyz, for DAFE Trading Systems
AllCandlestickPatternsLibraryAll Candlestick Patterns Library
The Candlestick Patterns Library is a Pine Script (version 6) library extracted from the All Candlestick Patterns indicator. It provides a comprehensive set of functions to calculate candlestick properties, detect market trends, and identify various candlestick patterns (bullish, bearish, and neutral). The library is designed for reusability, enabling TradingView users to incorporate pattern detection into their own scripts, such as indicators or strategies.
The library is organized into three main sections:
Trend Detection: Functions to determine market trends (uptrend or downtrend) based on user-defined rules.
Candlestick Property Calculations: A function to compute core properties of a candlestick, such as body size, shadow lengths, and doji characteristics.
Candlestick Pattern Detection: Functions to detect specific candlestick patterns, each returning a tuple with detection status, pattern name, type, and description.
Library Structure
1. Trend Detection
This section includes the detectTrend function, which identifies whether the market is in an uptrend or downtrend based on user-specified rules, such as the relationship between the closing price and Simple Moving Averages (SMAs).
Function: detectTrend
Parameters:
downTrend (bool): Initial downtrend condition.
upTrend (bool): Initial uptrend condition.
trendRule (string): The rule for trend detection ("SMA50" or "SMA50, SMA200").
p_close (float): Current closing price.
sma50 (float): Simple Moving Average over 50 periods.
sma200 (float): Simple Moving Average over 200 periods.
Returns: A tuple indicating the detected trend.
Logic:
If trendRule is "SMA50", a downtrend is detected when p_close < sma50, and an uptrend when p_close > sma50.
If trendRule is "SMA50, SMA200", a downtrend is detected when p_close < sma50 and sma50 < sma200, and an uptrend when p_close > sma50 and sma50 > sma200.
2. Candlestick Property Calculations
This section includes the calculateCandleProperties function, which computes essential properties of a candlestick based on OHLC (Open, High, Low, Close) data and configuration parameters.
Function: calculateCandleProperties
Parameters:
p_open (float): Candlestick open price.
p_close (float): Candlestick close price.
p_high (float): Candlestick high price.
p_low (float): Candlestick low price.
bodyAvg (float): Average body size (e.g., from EMA of body sizes).
shadowPercent (float): Minimum shadow size as a percentage of body size.
shadowEqualsPercent (float): Tolerance for equal shadows in doji detection.
dojiBodyPercent (float): Maximum body size as a percentage of range for doji detection.
Returns: A tuple containing 17 properties:
C_BodyHi (float): Higher of open or close price.
C_BodyLo (float): Lower of open or close price.
C_Body (float): Body size (difference between C_BodyHi and C_BodyLo).
C_SmallBody (bool): True if body size is below bodyAvg.
C_LongBody (bool): True if body size is above bodyAvg.
C_UpShadow (float): Upper shadow length (p_high - C_BodyHi).
C_DnShadow (float): Lower shadow length (C_BodyLo - p_low).
C_HasUpShadow (bool): True if upper shadow exceeds shadowPercent of body.
C_HasDnShadow (bool): True if lower shadow exceeds shadowPercent of body.
C_WhiteBody (bool): True if candle is bullish (p_open < p_close).
C_BlackBody (bool): True if candle is bearish (p_open > p_close).
C_Range (float): Candlestick range (p_high - p_low).
C_IsInsideBar (bool): True if current candle body is inside the previous candle's body.
C_BodyMiddle (float): Midpoint of the candle body.
C_ShadowEquals (bool): True if upper and lower shadows are equal within shadowEqualsPercent.
C_IsDojiBody (bool): True if body size is small relative to range (C_Body <= C_Range * dojiBodyPercent / 100).
C_Doji (bool): True if the candle is a doji (C_IsDojiBody and C_ShadowEquals).
Purpose: These properties are used by pattern detection functions to evaluate candlestick formations.
3. Candlestick Pattern Detection
This section contains functions to detect specific candlestick patterns, each returning a tuple . The patterns are categorized as bullish, bearish, or neutral, and include detailed descriptions for use in tooltips or alerts.
Supported Patterns
The library supports the following candlestick patterns, grouped by type:
Bullish Patterns:
Rising Window: A two-candle continuation pattern in an uptrend with a price gap between the first candle's high and the second candle's low.
Rising Three Methods: A five-candle continuation pattern with a long green candle, three short red candles, and another long green candle.
Tweezer Bottom: A two-candle reversal pattern in a downtrend with nearly identical lows.
Upside Tasuki Gap: A three-candle continuation pattern in an uptrend with a gap between the first two green candles and a red candle closing partially into the gap.
Doji Star (Bullish): A two-candle reversal pattern in a downtrend with a long red candle followed by a doji gapping down.
Morning Doji Star: A three-candle reversal pattern with a long red candle, a doji gapping down, and a long green candle.
Piercing: A two-candle reversal pattern in a downtrend with a red candle followed by a green candle closing above the midpoint of the first.
Hammer: A single-candle reversal pattern in a downtrend with a small body and a long lower shadow.
Inverted Hammer: A single-candle reversal pattern in a downtrend with a small body and a long upper shadow.
Morning Star: A three-candle reversal pattern with a long red candle, a short candle gapping down, and a long green candle.
Marubozu White: A single-candle pattern with a long green body and minimal shadows.
Dragonfly Doji: A single-candle reversal pattern in a downtrend with a doji where open and close are at the high.
Harami Cross (Bullish): A two-candle reversal pattern in a downtrend with a long red candle followed by a doji inside its body.
Harami (Bullish): A two-candle reversal pattern in a downtrend with a long red candle followed by a small green candle inside its body.
Long Lower Shadow: A single-candle pattern with a long lower shadow indicating buyer strength.
Three White Soldiers: A three-candle reversal pattern with three long green candles in a downtrend.
Engulfing (Bullish): A two-candle reversal pattern in a downtrend with a small red candle followed by a larger green candle engulfing it.
Abandoned Baby (Bullish): A three-candle reversal pattern with a long red candle, a doji gapping down, and a green candle gapping up.
Tri-Star (Bullish): A three-candle reversal pattern with three doji candles in a downtrend, with gaps between them.
Kicking (Bullish): A two-candle reversal pattern with a bearish marubozu followed by a bullish marubozu gapping up.
Bearish Patterns:
On Neck: A two-candle continuation pattern in a downtrend with a long red candle followed by a short green candle closing near the first candle's low.
Falling Window: A two-candle continuation pattern in a downtrend with a price gap between the first candle's low and the second candle's high.
Falling Three Methods: A five-candle continuation pattern with a long red candle, three short green candles, and another long red candle.
Tweezer Top: A two-candle reversal pattern in an uptrend with nearly identical highs.
Dark Cloud Cover: A two-candle reversal pattern in an uptrend with a green candle followed by a red candle opening above the high and closing below the midpoint.
Downside Tasuki Gap: A three-candle continuation pattern in a downtrend with a gap between the first two red candles and a green candle closing partially into the gap.
Evening Doji Star: A three-candle reversal pattern with a long green candle, a doji gapping up, and a long red candle.
Doji Star (Bearish): A two-candle reversal pattern in an uptrend with a long green candle followed by a doji gapping up.
Hanging Man: A single-candle reversal pattern in an uptrend with a small body and a long lower shadow.
Shooting Star: A single-candle reversal pattern in an uptrend with a small body and a long upper shadow.
Evening Star: A three-candle reversal pattern with a long green candle, a short candle gapping up, and a long red candle.
Marubozu Black: A single-candle pattern with a long red body and minimal shadows.
Gravestone Doji: A single-candle reversal pattern in an uptrend with a doji where open and close are at the low.
Harami Cross (Bearish): A two-candle reversal pattern in an uptrend with a long green candle followed by a doji inside its body.
Harami (Bearish): A two-candle reversal pattern in an uptrend with a long green candle followed by a small red candle inside its body.
Long Upper Shadow: A single-candle pattern with a long upper shadow indicating seller strength.
Three Black Crows: A three-candle reversal pattern with three long red candles in an uptrend.
Engulfing (Bearish): A two-candle reversal pattern in an uptrend with a small green candle followed by a larger red candle engulfing it.
Abandoned Baby (Bearish): A three-candle reversal pattern with a long green candle, a doji gapping up, and a red candle gapping down.
Tri-Star (Bearish): A three-candle reversal pattern with three doji candles in an uptrend, with gaps between them.
Kicking (Bearish): A two-candle reversal pattern with a bullish marubozu followed by a bearish marubozu gapping down.
Neutral Patterns:
Doji: A single-candle pattern with a very small body, indicating indecision.
Spinning Top White: A single-candle pattern with a small green body and long upper and lower shadows, indicating indecision.
Spinning Top Black: A single-candle pattern with a small red body and long upper and lower shadows, indicating indecision.
Pattern Detection Functions
Each pattern detection function evaluates specific conditions based on candlestick properties (from calculateCandleProperties) and trend conditions (from detectTrend). The functions return:
detected (bool): True if the pattern is detected.
name (string): The name of the pattern (e.g., "On Neck").
type (string): The pattern type ("Bullish", "Bearish", or "Neutral").
description (string): A detailed description of the pattern for use in tooltips or alerts.
For example, the detectOnNeckBearish function checks for a bearish On Neck pattern by verifying a downtrend, a long red candle followed by a short green candle, and specific price relationships.
Usage Example
To use the library in a TradingView indicator, you can import it and call its functions as shown below:
//@version=6
indicator("Candlestick Pattern Detector", overlay=true)
import CandlestickPatternsLibrary as cp
// Calculate SMA for trend detection
sma50 = ta.sma(close, 50)
sma200 = ta.sma(close, 200)
= cp.detectTrend(true, true, "SMA50", close, sma50, sma200)
// Calculate candlestick properties
bodyAvg = ta.ema(math.max(close, open) - math.min(close, open), 14)
= cp.calculateCandleProperties(open, close, high, low, bodyAvg, 5.0, 100.0, 5.0)
// Detect a pattern (e.g., On Neck Bearish)
= cp.detectOnNeckBearish(downTrend, blackBody, longBody, whiteBody, open, close, low, bodyAvg, smallBody, candleRange)
if onNeckDetected
label.new(bar_index, low, onNeckName, style=label.style_label_up, color=color.red, textcolor=color.white, tooltip=onNeckDesc)
// Detect another pattern (e.g., Piercing Bullish)
= cp.detectPiercingBullish(downTrend, blackBody, longBody, whiteBody, open, low, close, bodyMiddle)
if piercingDetected
label.new(bar_index, low, piercingName, style=label.style_label_up, color=color.blue, textcolor=color.white, tooltip=piercingDesc)
Steps in the Example
Import the Library: Use import CandlestickPatternsLibrary as cp to access the library's functions.
Calculate Trend: Use detectTrend to determine the market trend based on SMA50 or SMA50/SMA200 rules.
Calculate Candlestick Properties: Use calculateCandleProperties to compute properties like body size, shadow lengths, and doji status.
Detect Patterns: Call specific pattern detection functions (e.g., detectOnNeckBearish, detectPiercingBullish) and use the returned values to display labels or alerts.
Visualize Patterns: Use label.new to display detected patterns on the chart with their names, types, and descriptions.
Key Features
Modularity: The library is designed as a standalone module, making it easy to integrate into other Pine Script projects.
Comprehensive Pattern Coverage: Supports over 40 candlestick patterns, covering bullish, bearish, and neutral formations.
Detailed Documentation: Each function includes comments with @param and @returns annotations for clarity.
Reusability: Can be used in indicators, strategies, or alerts by importing the library and calling its functions.
Extracted from All Candlestick Patterns: The library is derived from the All Candlestick Patterns indicator, ensuring it inherits a well-tested foundation for pattern detection.
Notes for Developers
Pine Script Version: The library uses Pine Script version 6, as specified by //@version=6.
Parameter Naming: Parameters use prefixes like p_ (e.g., p_open, p_close) to avoid conflicts with built-in variables.
Error Handling: The library has been fixed to address issues like undeclared identifiers (C_SmallBody, C_Range), unused arguments (factor), and improper comment formatting.
Testing: Developers should test the library in TradingView to ensure patterns are detected correctly under various market conditions.
Customization: Users can adjust parameters like bodyAvg, shadowPercent, shadowEqualsPercent, and dojiBodyPercent in calculateCandleProperties to fine-tune pattern detection sensitivity.
Conclusion
The Candlestick Patterns Library, extracted from the All Candlestick Patterns indicator, is a powerful tool for traders and developers looking to implement candlestick pattern detection in TradingView. Its modular design, comprehensive pattern support, and detailed documentation make it an ideal choice for building custom indicators or strategies. By leveraging the library's functions, users can analyze market trends, compute candlestick properties, and detect a wide range of patterns to inform their trading decisions.
Johnny's Machine Learning Moving Average (MLMA) w/ Trend Alerts📖 Overview
Johnny's Machine Learning Moving Average (MLMA) w/ Trend Alerts is a powerful adaptive moving average indicator designed to capture market trends dynamically. Unlike traditional moving averages (e.g., SMA, EMA, WMA), this indicator incorporates volatility-based trend detection, Bollinger Bands, ADX, and RSI, offering a comprehensive view of market conditions.
The MLMA is "machine learning-inspired" because it adapts dynamically to market conditions using ATR-based windowing and integrates multiple trend strength indicators (ADX, RSI, and volatility bands) to provide an intelligent moving average calculation that learns from recent price action rather than being static.
🛠 How It Works
1️⃣ Adaptive Moving Average Selection
The MLMA automatically selects one of four different moving averages:
📊 EMA (Exponential Moving Average) – Reacts quickly to price changes.
🔵 HMA (Hull Moving Average) – Smooth and fast, reducing lag.
🟡 WMA (Weighted Moving Average) – Gives recent prices more importance.
🔴 VWAP (Volume Weighted Average Price) – Accounts for volume impact.
The user can select which moving average type to use, making the indicator customizable based on their strategy.
2️⃣ Dynamic Trend Detection
ATR-Based Adaptive Window 📏
The Average True Range (ATR) determines the window size dynamically.
When volatility is high, the moving average window expands, making the MLMA more stable.
When volatility is low, the window shrinks, making the MLMA more responsive.
Trend Strength Filters 📊
ADX (Average Directional Index) > 25 → Indicates a strong trend.
RSI (Relative Strength Index) > 70 or < 30 → Identifies overbought/oversold conditions.
Price Position Relative to Upper/Lower Bands → Determines bullish vs. bearish momentum.
3️⃣ Volatility Bands & Dynamic Support/Resistance
Bollinger Bands (BB) 📉
Uses standard deviation-based bands around the MLMA to detect overbought and oversold zones.
Upper Band = Resistance, Lower Band = Support.
Helps traders identify breakout potential.
Adaptive Trend Bands 🔵🔴
The MLMA has built-in trend envelopes.
When price breaks the upper band, bullish momentum is confirmed.
When price breaks the lower band, bearish momentum is confirmed.
4️⃣ Visual Enhancements
Dynamic Gradient Fills 🌈
The trend strength (ADX-based) determines the gradient intensity.
Stronger trends = More vivid colors.
Weaker trends = Lighter colors.
Trend Reversal Arrows 🔄
🔼 Green Up Arrow: Bullish reversal signal.
🔽 Red Down Arrow: Bearish reversal signal.
Trend Table Overlay 🖥
Displays ADX, RSI, and Trend State dynamically on the chart.
📢 Trading Signals & How to Use It
1️⃣ Bullish Signals 📈
✅ Conditions for a Long (Buy) Trade:
The MLMA crosses above the lower band.
The ADX is above 25 (confirming trend strength).
RSI is above 55, indicating positive momentum.
Green trend reversal arrow appears (confirmation of a bullish reversal).
🔹 How to Trade It:
Enter a long trade when the MLMA turns bullish.
Set stop-loss below the lower Bollinger Band.
Target previous resistance levels or use the upper band as take-profit.
2️⃣ Bearish Signals 📉
✅ Conditions for a Short (Sell) Trade:
The MLMA crosses below the upper band.
The ADX is above 25 (confirming trend strength).
RSI is below 45, indicating bearish pressure.
Red trend reversal arrow appears (confirmation of a bearish reversal).
🔹 How to Trade It:
Enter a short trade when the MLMA turns bearish.
Set stop-loss above the upper Bollinger Band.
Target the lower band as take-profit.
💡 What Makes This a Machine Learning Moving Average?
📍 1️⃣ Adaptive & Self-Tuning
Unlike static moving averages that rely on fixed parameters, this MLMA automatically adjusts its sensitivity to market conditions using:
ATR-based dynamic windowing 📏 (Expands/contracts based on volatility).
Adaptive smoothing using EMA, HMA, WMA, or VWAP 📊.
Multi-indicator confirmation (ADX, RSI, Volatility Bands) 🏆.
📍 2️⃣ Intelligent Trend Confirmation
The MLMA "learns" from recent price movements instead of blindly following a fixed-length average.
It incorporates ADX & RSI trend filtering to reduce noise & false signals.
📍 3️⃣ Dynamic Color-Coding for Trend Strength
Strong trends trigger more vivid colors, mimicking confidence levels in machine learning models.
Weaker trends appear faded, suggesting uncertainty.
🎯 Why Use the MLMA?
✅ Pros
✔ Combines multiple trend indicators (MA, ADX, RSI, BB).
✔ Automatically adjusts to market conditions.
✔ Filters out weak trends, making it more reliable.
✔ Visually intuitive (gradient colors & reversal arrows).
✔ Works across all timeframes and assets.
⚠️ Cons
❌ Not a standalone strategy → Best used with volume confirmation or candlestick analysis.
❌ Can lag slightly in fast-moving markets (due to smoothing).
CDZV Enhanced Coppock CurveThis indicator is a part of the CDZV toolkit (backtesting and automation)
The Enhanced Coppock Curve is an upgraded version of the classic Coppock Curve indicator. It incorporates several additional features for greater flexibility and analysis capabilities. This indicator is used to analyze market trends by plotting a weighted moving average (WMA) of the sum of two Rate of Change (ROC) values.
Key Features of the Indicator:
Base Calculation of the Coppock Curve:
The Coppock Curve is calculated as a weighted moving average (WMA) of the sum of two ROC values (long and short periods).
The source for the calculation is customizable (default is close).
Added Custom Moving Average:
The indicator supports three types of moving averages:
EMA (Exponential Moving Average),
SMA (Simple Moving Average),
HMA (Hull Moving Average).
Users can choose the type and length of the moving average via input settings.
The selected moving average values are displayed in the Data Window for easier analysis.
Dynamic Coloring of the Coppock Curve:
The Coppock Curve line changes color based on its value:
Green if the value is positive,
Red if the value is negative.
The line's color is also displayed in the Data Window as a numeric value:
1 for green (positive),
-1 for red (negative).
Data Window Output:
The values of the selected moving average are displayed in the Data Window.
The Coppock Curve line's color state (1 or -1) is also shown in the Data Window.
Visual Representation:
The Coppock Curve is plotted with dynamic color coding.
The selected moving average is overlaid on the Coppock Curve for deeper trend analysis.
Usage Instructions:
Add the indicator to your chart on TradingView.
Configure the inputs:
Smoothing length for the Coppock Curve,
Long and short periods for ROC,
Type and length of the moving average.
Analyze the chart:
A green Coppock Curve line indicates a bullish trend, while a red line signals a bearish trend.
The selected moving average helps further filter and confirm signals.
Use the Data Window to view numeric values for the moving average and the Coppock Curve line color.
Applications:
This indicator is ideal for assessing trend direction and strength. The added customization options and additional data make it a versatile tool for traders, enabling them to tailor the Coppock Curve to their strategies.