Indicator

Hidden Markov Model: Baum-Welch [UAlgo]Hidden Markov Model: Baum-Welch is a regime detection and reversal signaling indicator that applies a 3 state Hidden Markov Model to normalized log returns and continuously adapts its parameters using an online Baum Welch expectation maximization routine. The script is designed to classify the market into three latent regimes, then express that classification as real time probabilities for Bull, Range, and Bear conditions.
The indicator runs in its own pane ( overlay=false ) and outputs:
Probability curves for the three regimes
A dominant regime score scaled to 0 to 1
A regime strip visualization for quick bias reading
Adaptive background coloring based on the dominant regime and confidence
Optional regime shift markers
Optional buy and sell reversal markers driven by strict multi condition logic
The core idea is that price behavior can be modeled as transitions between hidden states that each have their own return distribution. The script fits a Gaussian emission model for each state, estimates state transition probabilities, and updates the posterior probability of each state on every bar. It retrains the full model at fixed intervals, while using a faster one step forward update between retrains for efficiency.
This implementation is not a simple threshold oscillator. It is a full mini HMM engine built in Pine with:
Scaled forward and backward algorithms
Expectation step producing gamma and xi posteriors
Maximization step updating initial distribution, transition matrix, state means, and state variances
Safeguards such as variance floors and transition floors to maintain numerical stability
The output is a regime aware probability system that can be used for bias, context, and reversal confirmation rather than simple entry signals.
Educational tool only. Not financial advice.
🔹 Features
🔸 1) Three State Hidden Markov Model Regime Engine
The model uses three hidden states and continuously estimates the probability of being in each state:
Bull regime
Range regime
Bear regime
This gives a probabilistic regime map rather than a single hard classification.
🔸 2) Baum Welch Training with Scheduled Retraining
The script retrains its parameters using an EM routine at a user defined interval in bars. Each retrain runs a configurable number of EM iterations. Between retrains, the indicator performs a one step forward Bayesian update of the posterior state probabilities.
This structure balances adaptability with performance.
🔸 3) Normalized Log Return Observations
The observation series is a z score normalized log return:
Log returns convert price changes into additive units
An EMA and rolling standard deviation normalize the series to stabilize the HMM fit
This helps the HMM learn regimes based on relative return behavior rather than raw price scale.
🔸 4) Automatic Bull, Range, and Bear Role Assignment
The model learns state means. The script then assigns roles by ranking those learned means:
The state with the lowest mean becomes the Bear state
The state with the highest mean becomes the Bull state
The remaining state is treated as Range
This keeps regime labeling consistent even as the internal state ordering shifts during training.
🔸 5) Probabilities and Dominant Regime Visualization
The script plots:
Bull probability curve
Range probability curve
Bear probability curve
It also plots an area for the dominant probability and a regime strip that makes it easy to see the dominant regime quickly without reading the full curves.
🔸 6) Regime Score Line (Bull minus Bear)
A continuous score is calculated as Bull probability minus Bear probability, then scaled to a 0 to 1 range. This score becomes the main regime momentum signal used for rebound and reversal logic.
🔸 7) Adaptive Background Coloring by Regime and Confidence
The pane background color changes based on the dominant regime. Transparency adapts according to confidence, so strong regime certainty produces a more visible background while low certainty remains subtle.
🔸 8) Strict Signal Filters for Bias and Reversal
The indicator provides bias filters:
Bull bias when Bull probability and confidence exceed thresholds and the dominant regime is Bull
Bear bias when Bear probability and confidence exceed thresholds and the dominant regime is Bear
It also provides reversal style buy and sell signals based on a multi condition framework described in the calculations section.
🔸 9) Reversal Logic Combining Extremes, Rebounds, and Transition Edge
Reversal signals are not generated by a single crossover. The script requires:
An extreme score pivot
An extreme regime probability at that pivot
A rebound trigger through predefined rebound levels
A minimum probability and confidence filter
A transition asymmetry and edge condition that favors switching toward the target regime
A momentum condition requiring Bull probability rising and Bear probability falling for buys, and the inverse for sells
A time window limit so reversals must occur within a limited number of bars after the extreme
This creates a high selectivity reversal engine.
🔸 10) Transition Matrix Insight and Switch Edge Metrics
The script computes predicted transition probabilities toward Bull and Bear using the current posterior and the transition matrix. It also measures transition asymmetry between Bull to Bear and Bear to Bull and uses these values as part of reversal confirmation.
This adds structural information that classic oscillators do not capture.
🔸 11) Anti Duplicate Reversal Signals
Once a pivot extreme has been used to generate a reversal signal, it is marked as consumed so the same pivot cannot repeatedly trigger additional buy or sell signals. This helps avoid signal repetition.
🔸 12) Full Informational Label Output
A live info label prints:
Current regime
Current signal text
Confidence
Bull, Range, Bear probabilities
Log likelihood
Key trigger thresholds
Reversal settings and edge settings
This provides transparency into what the model is currently seeing and why signals are or are not appearing.
🔹 Calculations
1) Observation Series: Normalized Log Returns
The script uses log returns:
logRet = math.log(close / nz(close , close))
Then normalizes them with an EMA mean and rolling standard deviation:
retMean = nz(ta.ema(logRet, normLength), 0.0)
retStd = math.max(nz(ta.stdev(logRet, normLength), 0.0), 1e-6)
obs = (logRet - retMean) / retStd
This creates an observation series with more stable scale properties across time.
2) Rolling Observation Window
The HMM is trained on a rolling window of length windowLen . Only the most recent processRecentBars are processed to control load:
startBar = last_bar_index - processRecentBars
activeRange = bar_index >= (startBar < 0 ? 0 : startBar)
If active, the observation is appended and the oldest one is removed:
if array.size(obsWindow) < windowLen
array.push(obsWindow, obs)
else
array.shift(obsWindow)
array.push(obsWindow, obs)
The model is ready only when the window is full.
3) Model Initialization
The script initializes a 3 state model with:
Uniform initial state probabilities
A transition matrix seeded with high persistence and equal small jump probabilities
State means initialized around zero with a configured separation
State variances initialized to a configured starting value
Key logic:
Stay probability equals initialPersistence
Jump probability equals the remaining probability split across other states
This gives the HMM a stable starting point before training.
4) Emission Model: Gaussian per State
Each state emits observations using a Gaussian density:
math.exp(-0.5 * d * d / varS) / math.sqrt(TWO_PI * varS)
Variance uses a floor:
float varS = math.max(array.get(this.vr, s), varMin)
This prevents variance collapse and numeric instability.
5) Forward Algorithm with Scaling
The script computes the forward probabilities alpha and applies scaling coefficients c to prevent underflow. It then recovers log likelihood from the scaling coefficients:
this.logLik := -sum(log(c ))
This is essential because HMM sequences quickly underflow without scaling.
6) Backward Algorithm with Scaling
The backward probabilities beta are computed using the scaling values from the forward pass, ensuring alpha and beta remain numerically stable across the entire window.
7) Expectation Step: Gamma and Xi
Gamma represents posterior probability of being in state i at time t . Xi represents posterior probability of transitioning from i to j between t and t+1 .
Xi is normalized per time step:
xij = xi_raw / denom
Gamma is computed as the sum of xi across outgoing transitions for each state:
gamma(t, i) = sum_j xi(t, i, j)
8) Maximization Step: Updating Parameters
Initial probabilities update from gamma at time 0:
pi = gamma(0, i)
Transition probabilities update from xi sums divided by gamma sums, with a transition floor and row normalization:
Each transition is clamped to transitionFloor
Each row is normalized to sum to 1
Means update as weighted averages of observations using gamma weights.
Variances update as weighted squared deviation sums with a variance floor.
9) Retraining Schedule and Online Updates
The model retrains when:
It is not initialized yet
Or the bar index matches the retrain interval
shouldRetrain = ready and (not modelInitialized or bar_index % retrainEveryBars == 0)
On retrain, Baum Welch is run for emIterations .
Between retrains, the script performs a one step forward update of the posterior:
hmm.forwardOne(posterior, obs, varianceFloor, posteriorTmp)
This provides continuous posterior updates without full retraining on every bar.
10) Role Mapping to Bull, Range, Bear
The script assigns which internal state corresponds to Bear and Bull by looking at the learned means:
Bear state is the state with the minimum mean
Bull state is the state with the maximum mean
Range is the remaining state index
This mapping updates dynamically as the model learns.
11) Regime Score and Confidence
The regime score is:
score = pBull - pBear
It is then scaled to 0 to 1:
score01 = 0.5 + 0.5 * score
Confidence is:
confidence = max(pBull, pRange, pBear)
This confidence drives background alpha and signal gating.
12) Probability Filters for Bias
Bull filter requires:
Bull probability above bullProbTrigger
Confidence above signalConfidenceMin
Bear filter requires similar conditions for Bear probability.
Bias validity adds the requirement that the dominant regime role matches the direction:
Bull bias requires dominantRole equals 1
Bear bias requires dominantRole equals minus 1
13) Extreme Pivot Logic for Reversal Candidates
The script looks for pivots in the score line:
ta.pivotlow(score01, pivotStrength, 1)
ta.pivothigh(score01, pivotStrength, 1)
It stores the most recent pivot low and pivot high along with the associated Bull or Bear probability at the pivot bar.
A low extreme is valid if:
Score at pivot is below dipScoreLevel
Bear probability at pivot exceeds extremeProbMin
A high extreme is valid if:
Score at pivot is above topScoreLevel
Bull probability at pivot exceeds extremeProbMin
14) Rebound Triggers
After an extreme, the script waits for rebound triggers:
Up rebound:
ta.crossover(score01, reboundUpLevel)
Down rebound:
ta.crossunder(score01, reboundDownLevel)
Rebound must occur within the reversal window bars from the extreme pivot.
15) Transition Edge and Asymmetry Logic
The script computes predicted probabilities of switching toward Bull or Bear using the transition matrix and current posterior. It also computes transition asymmetry between the Bull to Bear and Bear to Bull transitions.
A bullish switch condition requires:
Switch edge greater than hmmEdgeMin
Transition asymmetry favoring Bear to Bull at or above transitionAsymMin
Bull probability greater than Bear probability
A bearish switch condition uses the mirrored logic.
This adds a model based confirmation that a regime switch is plausible, not only that the score bounced.
16) Momentum Confirmation
Bull momentum requires:
Bull probability rising
Bear probability falling
Bear momentum requires the opposite.
These conditions prevent signals when probabilities are flat or conflicting.
17) Final Reversal Signal Construction
Buy reversal requires:
Valid low extreme
Not consumed
Inside reversal window
Rebound up
Bull probability and confidence filter
Bullish HMM switch condition
Bull momentum
Sell reversal requires the mirrored set of conditions.
The sell is suppressed if a buy is simultaneously true so conflicting signals do not print on the same bar.
18) Visualization Output
The script plots:
Probability curves for each regime
A dominant probability area
A thick score line colored by regime
A regime strip column plot
Fills between Bull and Bear curves and between rebound levels
Adaptive background
Optional markers for regime shifts
Reversal markers as glow plus label style plots
The info label consolidates the most important current state and threshold data for transparency. Indicator

Strategy

Indicator

Indicator

Indicator

CRT (MTF)CRT Strategy — Indicator Guide
Overlay: Yes (box, lines, and signals drawn directly on the price chart)
What Is This Indicator?
CRT Strategy is a price structure tool based on Candle Range Theory (CRT). It automatically marks the high and low of the previous candle on any selected timeframe, projects those levels forward as key reference lines, and detects when price sweeps through them — a signature institutional move that frequently precedes a sharp reversal in the opposite direction.
Unlike fixed-timeframe versions, this indicator lets you freely choose any timeframe in the settings — from 1-minute to Monthly — while keeping your chart on any other timeframe. This makes it flexible for all trading styles, from scalping to swing trading.
The Core Concept — What Is a CRT Sweep?
In Candle Range Theory, the high and low of the previous candle are treated as liquidity pools — areas where stop orders from retail traders accumulate above highs and below lows. Institutional participants frequently drive price beyond these levels to collect that liquidity before reversing sharply in the opposite direction. This move is called a sweep.
A Sweep High occurs when a candle's wick pushes above the previous high but the candle closes back below it — with the open also below it. This signals that liquidity above the high was grabbed and rejected, shifting the bias bearish.
A Sweep Low is the mirror: the wick dips below the previous low but the candle closes and opens above it, signaling that liquidity below was swept and rejected, shifting the bias bullish.
Visual Outputs
Source Box
A shaded blue rectangle drawn over the previous candle's full range on the selected timeframe — from its high to its low, spanning exactly the time boundaries of that candle. The box width automatically adjusts to match the actual duration of the selected timeframe, so it always appears correctly whether you are using a 1-hour, Daily, or Weekly reference candle.
CRH Line (Candle Range High)
A red horizontal line extending forward from the right edge of the source box, projecting the previous candle's high into the future. This is the upper liquidity level — the zone where stop orders from short sellers accumulate.
CRL Line (Candle Range Low)
A green horizontal line projecting the previous candle's low forward. This is the lower liquidity level — the zone where stop orders from long traders accumulate.
EQ Line (Equilibrium — 50%)
A dotted gray line at the exact midpoint between CRH and CRL. The equilibrium level is a common rebalancing target after a sweep — price frequently returns to the 50% level of the previous candle's range before continuing in the new direction.
Sweep Signals
A small downward triangle appears above the bar when a Sweep High is detected. A small upward triangle appears below the bar when a Sweep Low is detected. Both are black by default and kept small to avoid cluttering the chart.
Settings Reference
Timeframe (default: 240 / 4-Hour) — the most important setting. This determines which candle's high and low are used as the reference range. Set it to any timeframe higher than your chart for macro context, or the same as your chart for same-timeframe CRT analysis. Common choices are 1H, 4H, Daily, and Weekly depending on your trading style.
Show Source Box — toggles the shaded rectangle marking the previous candle's range on and off.
Show EQ (50%) — toggles the dotted midpoint line between CRH and CRL.
Show Signals (Sweep) — toggles the triangle markers that appear when a sweep is detected.
CRH Line Color — color of the projected high line (default red).
CRL Line Color — color of the projected low line (default green).
EQ Line Color — color of the dotted midpoint line (default gray).
Box Background Color — fill color of the source box (default light blue).
Signal Triangle Color — color of the sweep signal triangles (default black).
How to Use It — Trading Workflow
Step 1 — Choose your reference timeframe. Select the timeframe whose candle range you want to monitor. For day trading on a 5-minute or 15-minute chart, the 1-hour or 4-hour timeframe works well. For swing trading on a 1-hour chart, use the Daily or Weekly. For scalping, you can set the reference to the same or one timeframe above your chart.
Step 2 — Mark the key levels. At the start of each new candle on the selected timeframe, the source box and projected lines update to reflect the new previous candle's range. CRH and CRL are your two active liquidity targets for the current period.
Step 3 — Watch for a sweep. As price approaches CRH or CRL, monitor closely for a wick violation followed by a close back inside the range. The indicator will mark the event automatically with a triangle. This is the setup — not the entry signal itself, but the setup that shifts the directional bias.
Step 4 — Look for confirmation and enter. After a Sweep High triangle, the bias shifts bearish. Wait for a bearish confirmation candle, a break of a recent structure low, or any other entry trigger you use. The EQ line is the first natural target, followed by CRL. After a Sweep Low, the bias shifts bullish with EQ and then CRH as upside targets.
Step 5 — Place your stop. Use the extreme of the swept wick as your stop reference. For a short entry after a Sweep High, a stop above the wick high is logical. For a long entry after a Sweep Low, a stop below the wick low protects the trade.
Timeframe Pairing Guide
The indicator works on any chart timeframe — the reference timeframe in settings should generally be equal to or higher than your chart timeframe. Some practical pairings:
For scalping on 1-minute or 5-minute charts, set the reference to 15-minute or 1-hour. For intraday trading on 15-minute charts, use 1-hour or 4-hour as the reference. For day trading on 1-hour charts, use 4-hour or Daily. For swing trading on 4-hour charts, use Daily or Weekly.
Alert Setup
The indicator includes two built-in alerts. CRT Sweep High fires when a bearish sweep of the previous high is detected. CRT Sweep Low fires when a bullish sweep of the previous low is detected.
To activate in PulseWire, open the Alerts panel, click Create Alert, select CRT Strategy as the condition, choose either CRT Sweep High or CRT Sweep Low, set your notification method, and click Create. Repeat for the other direction.
Tips
The most powerful CRT setups occur when the sweep happens during a high-liquidity session transition — particularly at the London open or the New York open. A sweep that forms during these windows and aligns with the higher timeframe trend direction tends to produce the cleanest and fastest reversals.
The EQ line is frequently underestimated. After a confirmed sweep and reversal, price almost always rebalances to the 50% midpoint of the previous candle's range before continuing. Using EQ as a partial take-profit level improves the consistency of results.
Running two instances of the indicator simultaneously — one on a higher reference timeframe for context and one on a lower reference timeframe for precise entries — gives a powerful multi-layered view of active liquidity zones.
Limitations
The indicator always shows the single most recent completed candle on the selected timeframe. Historical sweep signals from previous candles are not stored or displayed — only the current period's levels are active. On very high reference timeframes such as Weekly or Monthly, the source box will span a large portion of the chart visually, which is normal and expected behavior. Indicator

Gaps 15s-15m Final - Forex FixedThis indicator is designed for precision scalping. It identifies liquidity gaps between two candles on the 15-second timeframe and projects them as horizontal support or resistance zones.
Fill Logic: Unlike traditional indicators, this one automatically cleans your chart.
As soon as a candle wick closes the gap, the zone and its price label disappear instantly to avoid any visual confusion.
Multi-Timeframe Visibility: Once detected in 15 seconds, the levels remain fixed and visible if you move to 1m, 5m, or 15m charts, allowing you to see institutional rebound zones on broader timeframes.
Numerical Settings (Configuration): To access these settings, click on the indicator's gear icon.
Here are the exact numbers to enter depending on what you are trading: 1.
For Indices (NASDAQ, DAX, S&P 500)
The indices move in whole points. The setting should be less sensitive than for Forex.
Parameter Recommended Value
Effect Asset Type Indices Enables point calculation mode.
Sensitivity 1.0 Detects gaps of 0.1 pip. Sensitivity (Alternative) 5.0 Only shows large gaps of 0.5 pip (more reliable). 2. For Forex (EUR/USD, GBP/USD, etc.)
Forex moves in micro-fractions (pips). Without these settings, the indicator will not be displayed. Parameter Recommended Value Effect Asset Type Forex Enables fractional pip calculation mode. Sensitivity 1.0 Detects gaps of 0.1 pip (0.00001). Sensitivity (Filter) 3.0 Detects gaps of 0.3 pip (filters out spread noise).
Quick Start Guide: On the 15-second timeframe: Use a sensitivity of 1.0.
This is where the indicator is most responsive. On the 15-minute timeframe: If you find there are too many small residual areas, increase the sensitivity to 2.0 or higher to retain only the major imbalance zones that have not yet been filled. Visual Errors: If no zones appear on EUR/USD, double-check that you have selected Forex in the indicator's dropdown menu. Indicator

Trend StructureTrend Structure is a trend-context indicator based on a configurable moving average.
It is designed to visualize directional bias by analyzing the slope of the selected smoothing method.
An optional higher timeframe (MTF) calculation can be applied.
The indicator displays a single trend line that changes color depending on whether the moving average value is increasing or decreasing.
Calculation concept
1. A user-selected moving average type is calculated. Available smoothing methods include:
SMA, EMA, WMA, HMA, VWMA, RMA, and TEMA.
2. If a higher timeframe is selected, the moving average is calculated using data from that timeframe and projected onto the current chart.
3. Directional context is determined by comparing the current value of the moving average to its previous value:
• If the value is rising, the context is considered upward.
• If the value is falling, the context is considered downward.
The color of the line reflects this directional slope.
The indicator does not attempt to predict future price movement. It describes the current directional state of the selected smoothing method.
What the indicator shows
• A single moving average line
• Color-coded directional context
• Optional higher timeframe trend alignment
The visualization focuses on trend slope rather than crossover signals or entry points.
Parameters
• Source — price input used for calculation
• Timeframe — optional higher timeframe for analysis
• Length — moving average period
• MA Type — smoothing method
• Line Width — visual thickness
• Up / Down Color — visual direction indication
Practical application
Trend Structure may be used to:
• evaluate directional context,
• align trade selection with prevailing slope,
• observe potential shifts in momentum when the slope changes direction,
• complement broader structural or volume-based analysis.
The indicator does not generate automated trading signals and does not define entry or exit levels.
It is intended as a contextual analytical tool.
Scope
This tool visualizes moving average slope and optional higher timeframe alignment to provide structural trend context.
It should be used as part of a broader analytical framework rather than as a standalone decision system. Indicator

MFI Distribution [UAlgo]MFI Distribution is a statistics focused Money Flow Index indicator that combines a live MFI oscillator with a forward projected distribution histogram and normality diagnostics. Instead of only showing the current MFI line, the script collects a rolling history of MFI values, studies their distribution over a configurable lookback period, and visualizes the result as a histogram in the oscillator pane.
The indicator is designed for traders who want to understand how MFI behaves as a distribution , not only where it is on the current bar. It provides a compact statistical framework that helps answer questions such as:
Is MFI clustering around a narrow regime or spread across the full range
Is the recent MFI behavior skewed toward strong buying or selling pressure
Does the MFI sample look approximately normal, or is it fat tailed / asymmetric
How extreme is the current reading relative to the recent distribution
To support this, the script includes:
A live MFI line with dynamic gradient coloring
Overbought and oversold visual zones with gradient fills
A histogram of MFI frequency distribution over the selected lookback
An optional Gaussian curve overlay for visual comparison
A statistical dashboard with mean, standard deviation, skewness, kurtosis, and Jarque Bera normality test results
The histogram is drawn into the future area of the pane, so it does not interfere with the live MFI trace while still remaining visually aligned to the 0 to 100 oscillator scale.
Educational tool only. Not financial advice.
🔹 Features
🔸 1) Live MFI Oscillator with Regime Aware Coloring
The script plots a standard MFI line and colors it dynamically based on level behavior:
High MFI values transition toward red tones
Low MFI values transition toward green tones
Mid range values remain purple
This makes the oscillator easier to read at a glance, especially during sustained overbought or oversold conditions.
🔸 2) Overbought and Oversold Zone Visualization
The indicator includes standard MFI reference levels at 80 and 20, then adds gradient fills that become visible when the MFI pushes into extreme zones. This provides better visual emphasis for momentum extremes without cluttering the chart.
🔸 3) Rolling MFI History Collection for Statistical Analysis
The script maintains an internal array of the latest MFI values up to the user defined lookback length. This rolling sample is used to compute all distribution statistics and histogram frequencies on the last bar.
This design keeps the indicator responsive while ensuring the displayed distribution reflects the most recent market behavior.
🔸 4) Forward Projected MFI Distribution Histogram
A histogram is drawn in the oscillator pane using bins over the fixed MFI range from 0 to 100. Each bin counts how many MFI observations fall inside that interval during the lookback window.
The histogram is projected to the right of current price action in the pane, giving users a clean distribution panel without covering the live MFI line.
🔸 5) Configurable Histogram Resolution and Width
Users can control:
Lookback period used for distribution analysis
Number of histogram bins
Visual width of the histogram in future bars
This makes the tool flexible for both high level regime reading and finer distribution inspection.
🔸 6) Optional Gaussian Curve Overlay
When enabled, the script overlays a theoretical normal distribution curve using the sample mean and sample standard deviation. The curve is normalized to the histogram height so users can visually compare the empirical MFI distribution against a bell curve shape.
This is useful for quickly spotting asymmetry, multimodal clustering, or fat tail behavior.
🔸 7) Full Statistical Summary Dashboard
A built in dashboard table displays:
Mean
Standard Deviation
Skewness
Kurtosis (excess kurtosis)
Jarque Bera statistic
Pass / Fail normality status (95% threshold logic)
This turns the indicator into a compact quantitative diagnostic panel, not only a visual oscillator.
🔸 8) Jarque Bera Normality Test Classification
The script evaluates whether the MFI sample is approximately normal using a Jarque Bera style test and a fixed chi square threshold (95% confidence, 2 degrees of freedom). It then marks the result as PASS (Normal) or FAIL (Non Normal).
This helps traders distinguish between more stable oscillator regimes and structurally distorted ones.
🔸 9) Histogram Color Theme Based on Normality Result
The histogram automatically changes style depending on the test result:
Teal themed histogram when normality test passes
Red themed histogram when normality test fails
This creates an immediate visual signal of distribution quality without needing to read the dashboard first.
🔸 10) Last Bar Only Heavy Processing for Efficiency
Statistical calculations, histogram drawing, and dashboard refresh are performed only on the last bar. This reduces object churn and improves performance while preserving real time utility.
🔸 11) Object Based Drawing Management
The script uses custom types to organize logic:
DistributionStats for statistical values and normality output
HistoDrawer for histogram bars, curve lines, and labels
This makes the code structured and easier to extend with future features such as percentiles, z scores, or alternate tests.
🔹 Calculations
1) MFI Calculation
The script computes Money Flow Index from a user selected source and length:
mfi_val = ta.mfi(mfi_src, mfi_len)
This value is plotted in the oscillator pane and colored dynamically according to level.
2) Rolling History Buffer for Distribution Sampling
Each valid MFI value is pushed into a rolling array used for statistical analysis:
if not na(mfi_val)
mfi_history.push(mfi_val)
if mfi_history.size() > lookback
mfi_history.shift()
This ensures the sample size is capped at the selected lookback and continuously refreshed with recent values.
3) Sample Variance and Standard Deviation
The script computes sample variance using the classic n minus 1 denominator:
sum_sq_diff / (n - 1)
Standard deviation is then calculated as:
stats.stdev := math.sqrt(variance_val)
Using sample variance is appropriate here because the lookback window is treated as a sample of recent market behavior.
4) Sample Skewness Calculation
Skewness is computed from standardized deviations and corrected for sample size:
(n * sum_cube_diff) / ((n - 1) * (n - 2))
Interpretation:
Positive skew suggests more mass on lower values with a right tail toward high MFI prints
Negative skew suggests more mass on higher values with a left tail toward low MFI prints
5) Excess Kurtosis Calculation
The script calculates excess kurtosis , where a normal distribution is centered around 0:
float term1 = (n * (n + 1) * sum_quad_diff) / ((n - 1) * (n - 2) * (n - 3))
float term2 = (3 * math.pow(n - 1, 2)) / ((n - 2) * (n - 3))
term1 - term2
Interpretation:
Positive excess kurtosis suggests heavier tails or more peaked behavior
Negative excess kurtosis suggests flatter distribution behavior
6) Jarque Bera Normality Test
The script uses skewness and excess kurtosis to compute the Jarque Bera statistic:
stats.jb_stat := (n / 6.0) * (math.pow(stats.skew, 2) + 0.25 * math.pow(stats.kurt, 2))
Then it compares the result against a 95 percent chi square critical value (2 degrees of freedom):
stats.is_normal := stats.jb_stat < 5.991
Important note:
The code defines a jb_p_value field in the stats type, but this version does not explicitly calculate or display a p value. The pass / fail logic is threshold based.
7) Fixed MFI Range Histogram Binning (0 to 100)
The histogram always bins data over the full MFI range:
float min_val = 0.0
float max_val = 100.0
float bin_size = (max_val - min_val) / bins
Each MFI value is mapped to a bin index:
int bin_idx = math.floor(val / bin_size)
The index is clamped so values at boundaries stay valid:
if bin_idx >= bins
bin_idx := bins - 1
if bin_idx < 0
bin_idx := 0
This makes the histogram consistent across symbols and timeframes.
8) Frequency Counting and Peak Detection
For each binned MFI observation, the script increments a frequency counter and tracks the highest bin count:
int new_count = frequencies.get(bin_idx) + 1
frequencies.set(bin_idx, new_count)
if new_count > max_freq
max_freq := new_count
The maximum frequency is later used to normalize histogram bar heights.
9) Histogram Rendering Geometry
The histogram is drawn as boxes in the oscillator pane, projected to the right of the last bar:
int start_bar = bar_index + 5
float base_y = 10.0
float available_height = 80.0
This effectively uses the MFI pane vertical range from about 10 to 90 for histogram height visualization, keeping it aligned with the oscillator scale.
Each bin is mapped to x coordinates using its MFI interval and the user selected histogram width:
int x_left = start_bar + math.round((bin_val_start / 100.0) * chart_width_bars)
int x_right = start_bar + math.round((bin_val_end / 100.0) * chart_width_bars)
Each frequency is mapped to a vertical height using:
float bar_height_val = (freq / max_freq) * available_height
10) Histogram Color Logic from Normality Result
The histogram color theme is selected from the Jarque Bera pass / fail result:
Teal palette when stats.is_normal is true
Red palette when stats.is_normal is false
This creates a direct link between statistical classification and visual presentation.
11) Gaussian Curve Overlay Calculation
The script defines a normal probability density function:
(1.0 / (sigma * math.sqrt(2.0 * math.pi))) * math.exp(-0.5 * math.pow((x - mu) / sigma, 2))
For curve plotting:
It samples points across the histogram width
Maps each x position back to an MFI value from 0 to 100
Computes the PDF at that MFI value using the sample mean and standard deviation
Scales the PDF by the theoretical peak so the curve fits the histogram height
Key normalization idea:
float pdf_peak = normal_pdf(stats.mean, stats.mean, stats.stdev)
float current_y = base_y + (pdf_val / pdf_peak) * available_height
This makes the Gaussian curve visually comparable to the empirical histogram, even though one is a density and the other is raw frequency.
12) Dashboard Table Metrics
On the last bar, the script updates a table with the computed statistics:
Mean
StdDev
Skewness
Kurtosis
Jarque Bera statistic and normality classification
The result cell color changes based on normality:
Green for PASS (Normal)
Red for FAIL (Non Normal)
This gives traders a compact quantitative summary next to the visual distribution.
13) Overbought and Oversold Gradient Fills
The script adds gradient fills that appear when MFI moves beyond standard thresholds:
fill(plot_mfi, p_ob, 100, 80, ...)
fill(plot_mfi, p_os, 20, 0, ...)
This helps contextualize whether the current MFI reading is extreme while the histogram and dashboard describe the broader behavior of the recent MFI sample. Indicator

Indicator

Indicator

Indicator

Indicator

Strategy

Strategy

BK AK-King Quazi👑 BK AK–King Quazi — Quasimodo State Machine + Projections + MTF Table 👑
🙏 All glory to G-d.
Built with standards and discipline passed down by my mentor — thank you for the relentless insistence on structure over noise, and for sharing real knowledge with generosity — no gatekeeping, no cheapness, no games.
Update / Record
A previous version of this publication was hidden due to insufficient description. This republish is a complete, self-contained explanation of what the script does, how it works, how to use it, and its limitations.
What this script does
King Quazi is a Quasimodo structure detector that turns the classic institutional sequence into a state machine:
Sweep → BOS (Break of Structure) → Retest (QM hold) → Confirm (Full QM)
…and it automatically builds:
QM / BOS / INV projection levels
optional Entry Zone buffer
optional T1 / T2 targets
invalidation / target-hit resolution
a Multi-Timeframe (MTF) table that tracks Quazi stages across up to 5 timeframes
It’s designed to stop you from guessing mid-range and force price to prove itself at the boundary.
Core logic (how it detects Quazi)
King Quazi uses a swing engine (ZigZag-like) built from rolling highs/lows over a configurable length (“ZZ length”). From those swings it evaluates two main structures:
1) PROTO (P) — Sweep + BOS (entry setup begins)
A PROTO event triggers when the script detects:
a liquidity sweep (stop run / fake-out behavior)
followed by a BOS in the opposite direction
with an optional displacement filter (candle body size in ATR terms)
Bull PROTO (P↑) = sweep down + BOS up
Bear PROTO (P↓) = sweep up + BOS down
When PROTO fires, the script stores fixed levels:
QM level (the key retest level)
BOS level (structure break)
INV level (where the thesis dies)
2) RETEST (R) — QM hold (execution zone)
After PROTO, a “RETEST” is flagged when price returns to QM and holds the correct side (touch + close logic). This is treated as the execution zone in the workflow.
3) CONFIRM (C) — Full Quasimodo completion
Confirm requires the fuller QM structure conditions to be met (the “pattern proved itself” state). This is the highest-confidence stage this tool prints.
4) INVALIDATION (X)
If price breaks the stored INV level before targets are resolved, the pattern is invalidated:
labels can switch from C/P to X
projections can be deleted OR “deadified” (grayed/dotted) depending on settings
What it draws on chart
A) Event labels
P↑ / P↓ = PROTO triggered
R↑ / R↓ = Retest detected
C↑ / C↓ = Confirm printed
X = invalidated
✓ = target hit (optional)
Label count is capped via a queue so the chart doesn’t explode.
B) Projection system (optional)
When PROTO triggers, the script can plot horizontal projection levels:
QM
BOS
INV
optional T1 / T2
optional Entry Zone (ATR buffer around QM)
You can choose:
how long projections extend (bars)
styles/widths “by meaning” (QM/BOS/INV/T targets) or unified
whether to keep projections after invalidation (turn gray) or remove them
C) Target models (optional)
Targets can be:
BOS + Prior Swing
Measured move (T1=1.0, T2=1.618 multipliers)
Neck→Head projection (H&S-style distance projection)
D) Resolution rules (optional)
You can automatically resolve the pattern when:
T1 hit or T2 hit
…and optionally remove projections/tags on resolution.
E) “Opposite PROTO” handling
If a new PROTO appears in the opposite direction while one is active, you can:
do nothing
clear projections
mark X + clear (kills the prior thesis cleanly)
Institutional tooltips (what the hover system includes)
If enabled, tooltips can include:
live distances from price to QM/BOS/INV/T1/T2
risk sizing and R:R estimates
“what now” execution guidance based on stage (P/R/C/X/HIT)
auction / trap logic text (liquidity magnets, stop pools)
optional Gann Square of 9 harmonic levels from the QM pivot
a blended EV readout (simple heuristic)
You can toggle tooltip modules (education / execution / checklist / Gann / auction / what-now / risk).
MTF BOOM Table (multi-timeframe context)
The script can scan up to 5 user-defined timeframes and display:
STATE: active stage (P↑, C↑, P↓, C↓, or neutral)
NOW: whether a PROTO/CONFIRM event happened within the last N bars (flash window)
It also computes a simple alignment count:
how many TFs are bull-staged vs bear-staged
and highlights when 3+ timeframes agree (higher conviction, less chop)
Optional alert() notifications can fire on:
PROTO bull/bear per TF
CONFIRM bull/bear per TF
How to use (practical workflow)
Start with MTF: don’t fight stacked alignment.
Wait for PROTO (P) — it defines the thesis and the levels.
Treat RETEST (R) as the preferred execution zone (QM hold).
Use CONFIRM (C) as “pattern proved itself” (add/hold/late entry logic).
INV is your line in the sand (the thesis dies there).
Manage to T1/T2 using your chosen target model and resolution settings.
Repaint / reliability notes (important)
Swing engine is dynamic: because swings are derived from rolling highs/lows, the identity of “recent swing points” can shift while structure is forming.
After a PROTO triggers, the script stores QM/BOS/INV as fixed values for that pattern, which greatly reduces “moving targets” after the event.
MTF table uses request.security(..., lookahead_off), but values on a higher timeframe can still update while that HTF candle is building. For strict confirmation, treat MTF “NOW” as most reliable on timeframe bar close.
Performance / limits
This script draws labels/lines/boxes and limits total objects with caps:
max labels / max lines
projection extension length
confirm-path limit (can clutter)
If you want a cleaner chart, disable confirm paths and/or reduce projection features.
Disclaimer
This indicator is for educational and analytical purposes only. It is not financial advice and does not guarantee outcomes. All “institutional” language refers to pattern logic and contextual heuristics, not certainty.
🙏 All glory to G-d — may He bless your discipline, patience, and execution. Indicator

Indicator

NWOG/NDOG (mskender83)A PulseWire indicator that automatically draws price gap zones at the open of each new trading week and each new trading day. These gaps — called NWOG (New Week Opening Gap) and NDOG (New Day Opening Gap) — are key concepts in ICT (Inner Circle Trader) methodology. The idea is that when price opens at a different level than the previous period's close, that unfilled gap tends to act as a magnet, drawing price back to "fill" it at some point during the session or week.
The two gap types
The NWOG draws on daily and intraday timeframes and marks the gap between Sunday's open and Friday's close — the weekly transition. The NDOG draws only on intraday timeframes and marks the gap between each day's open and the previous day's close. Both are displayed as colored boxes spanning the price range of the gap.
The 5pm–6pm gap option
Rather than using the raw daily or weekly open/close difference visible on a daily chart, there's an option to isolate specifically the 1-hour window between 5pm and 6pm New York time — the CME Globex session transition. This is the moment the futures market closes and reopens, and ICT traders consider this the "true" opening gap rather than the broader daily difference.
Bullish and bearish coloring
Each gap is evaluated at the moment it forms. If the open is above the previous close, the gap is bullish — price gapped up. If the open is below the previous close, it's bearish — price gapped down. When the bullish/bearish toggle is enabled, green is used for bullish gaps and red for bearish. When disabled, a single default color is used. This color is baked into each box permanently at creation — previous gaps retain their original directional color forever without any dimming or overriding.
C.E. — Consequent Encroachment
An optional midpoint line drawn through the center of each gap box. In ICT terminology this is the 50% level of the gap, considered the most likely target when price comes back to fill the zone.
Previous gaps
Both NWOG and NDOG keep a configurable number of historical gaps on the chart (default 4). Once the limit is exceeded the oldest box is deleted. The "Extend Previous" options push all visible gap boxes forward in time as new days or weeks progress, keeping older gaps visible and extended to the current bar.
Event Horizon
An advanced option for NWOG only. When two consecutive weekly gaps don't overlap — meaning there's empty space between them — a line is drawn at the midpoint of that void. This level is called the Event Horizon and represents the equilibrium price between two competing gap targets.
Price labels
Optional labels at the high, CE midpoint, and low of each gap box showing the exact price levels, useful for precise entries without having to hover over the boxes.
Timeframe behavior
The script is smart about which timeframe it's running on. NWOG shows on both daily and intraday charts. NDOG only shows on intraday charts since a daily gap makes no sense on a daily chart. On timeframes under 60 minutes the 5pm–6pm gap uses the 4-hour bar boundary to detect the weekly transition. Sunday NDOGs are automatically suppressed when NWOG is also enabled, since they represent the same gap event. Indicator

Indicator

Levels [BeNice]
Levels is a precision mapping tool for traders who rely on High Timeframe (HTF) levels to define their daily bias. It automates the process of marking Open, High, Low, and Equilibrium (EQ) levels across all major lookback periods.
💎 Key Functionalities
Dynamic HTF Mapping: Supports Yearly, Quarterly, Monthly, Weekly, Daily, and H4 timeframes.
Monday Range Specialist: Specifically tracks Monday's price action, a vital zone for setting the weekly narrative.
EQ (Equilibrium) Tracking: Automatically plots the mid-point of any given period, helping you identify Discount and Premium zones instantly.
Clean UI Logic: Features a built-in "anti-overlap" array system. If multiple levels occupy the same price point, the script optimizes the visuals to keep your chart professional and readable.
Full Customization: Control line styles (Solid, Dotted, Dashed), colors, text sizes, and line extensions to fit your personal chart aesthetic.
💡 Pro Trading Tip
Use these levels as Liquidity Targets or Points of Interest (POI). When price interacts with a Prev. Weekly High or a Monthly Open, look for the Reversal Pro+ SFP signals to confirm high-probability trade entries. Indicator

Indicator

Indicator
