مؤشر

Advanced Fear & Greed Cycle (Quant Model)## Overview
The **Advanced Fear & Greed Cycle (Quant Model) v6** is a pure quantitative oscillator designed to decode market sentiment by measuring the architectural divergence between smart money accumulation and retail distribution. Fully upgraded to Pine Script v6, this script addresses standard oscillator limitations by implementing dynamic time-frequency normalization ($0-100$ fixed scale).
Unlike standard sentiment proxies, this model filters out price-action noise by isolating volume flows, directional volatility, and mean-reversion extensions simultaneously.
---
## Mathematical Architecture & Core Engines
### 1. Directional Volatility Engine
Standard models treat volatility expansions as pure panic. This algorithm isolates **Directional Volatility**:
- A 14-period Average True Range (ATR) is mathematically normalized over a dynamic 90-day rolling quarter (`lookback`).
- **Trend Filter:** Volatility is converted into the `vol_fear` metric **only** if the closing price is below its 14-period Simple Moving Average (`is_descending`). Upside expansions (bullish breakouts) are correctly filtered out to prevent false panic readings.
### 2. Normalized Volume & Flow Sentiment
Liquidity and order-flow tracking are computed via a three-layered matrix:
- Normalized Volume spikes relative to the quarterly window.
- Inside-candle Selling Pressure ( AMEX:HIGH - Close$ versus the overall candle range).
- A normalized On-Balance Volume (OBV) structure to track mathematical capital inflows and outflows.
### 3. Boundary-Proof Macro Extension (Mayer Proxy)
To track cyclical overextensions, the script calculates the asset's percentage distance from its long-term moving average (SMA 200 on Daily, SMA 40 on Weekly charts).
To solve the scale break-out issue (where different assets experience wildly different percentage extensions), a **MinMax Normalization** is applied. This compresses the structural extension into a bound $0-100\%$ scale (`extension_norm`) based on the rolling quarter's extremes.
---
## The Greed Score Synthesizer
The final plotting line is the **Greed Score**, a mathematically symmetric index calculated as:
$$\text{Greed Score} = \frac{(100 - \text{Fear Index}) + \text{Extension Norm}}{2}$$
This creates a fixed-bound oscillator ($0$ to $100$) that charts three distinct market phases:
- 🟢 **INSTITUTIONAL ACCUMULATION (Green Zone / < 20):** High systemic fear combined with compressed macro price extensions (< 25%). Smart money absorbs panicking retail order flow near historical value areas.
- ⚪ **NEUTRAL REGIME (Gray Line):** Symmetrical equilibrium where supply and demand are balanced.
- 🔴 **RETAIL FOMO / BUBBLE (Red Zone / > 80):** Zero systemic fear combined with extreme quarterly price overextensions. Retail traders buying the top driven by euphoria, highlighting distribution blocks.
---
## Display Dashboard & Custom Parameters
The top-right informational panel provides real-time diagnostic outputs of the quantitative data (Current Cycle State, Exact Greed Score, and Normalized Extension %). Traders can adjust the `Soglia Bolla Normalizzata` input to calibrate the macro-exhaustion scanner to specific asset classes (Equities, Forex, or Cryptocurrencies).
---
Disclaimer: This tool calculates mathematical probabilities based on normalized historical structures. It does not provide definitive buy/sell signals or financial advice. Always integrate sound risk management protocols. مؤشر

Unicorn Model Detector [AGPro Series]Unicorn Model Detector
Overview
The Unicorn Model Detector identifies one of the most discussed setups in Inner Circle Trader (ICT) and Smart Money Concepts literature: the Unicorn Model. A Unicorn forms when a Breaker Block and a Fair Value Gap (FVG) overlap inside the same price zone — a pocket where prior swing liquidity has been swept and an unfilled imbalance still exists at the retest. The detector scans for these overlaps, tracks every occurrence through its full lifecycle, and reports aggregate statistics in a compact on-chart panel. It is a detection and bookkeeping tool, not a trading strategy.
Unique Edge
Most breaker and FVG scripts publish either zones in isolation or require the user to eyeball the overlap. This detector does the overlap match automatically and only draws a zone when both conditions are present on the same chart area with the same directional bias. A strict causality rule is enforced — the Breaker must form first (after liquidity sweep) and the FVG must appear during or after the retest, which matches the true ICT Unicorn definition. A pairing that consumes a given breaker and FVG is removed from future candidate pools, so the chart never stacks redundant zones from the same source structure. A Loose overlap mode is also provided for users who prefer an ATR-based proximity interpretation instead of strict geometric intersection.
Methodology
1. Swing pivots are detected with a configurable left/right length using ta.pivothigh and ta.pivotlow.
2. When a confirmed pivot forms, the body range of the pivot bar is stored as the potential Breaker source zone.
3. A Breaker Block is registered when price closes through the previous-bar swing level in the opposite direction.
4. A Fair Value Gap is registered when a 3-bar formation produces an unfilled imbalance (low > high for bullish, high < low for bearish) and the gap exceeds a user-defined ATR multiple.
5. A Unicorn is spawned when a same-direction Breaker zone and FVG zone overlap vertically AND the FVG formed at or after the Breaker (causality check).
6. A configurable cooldown prevents consecutive spawns from clustering, improving signal hygiene.
7. The overlap rectangle becomes the tracked zone. Zone mid is the reference entry, the stop is placed 0.4 times the zone height beyond the structure boundary, and the target is projected at the user-defined R-multiple.
Signals & Alerts
Four independent alert conditions are exposed:
- New Unicorn Detected — a fresh bullish or bearish Unicorn has just formed.
- Unicorn Triggered — price has entered the overlap zone of a pending Unicorn.
- Target Hit — a triggered Unicorn has reached its R-multiple target.
- Stop Hit — a triggered Unicorn has been invalidated at its stop level.
All alerts fire once per bar close and include the ticker and timeframe in the payload.
Key Inputs
- Swing Pivot Length (default 7) — left/right length used for pivot confirmation.
- Breaker Lookback (default 80 bars) — maximum age for a broken swing to remain a valid Breaker.
- FVG Minimum Size (default 0.25 x ATR) — noise filter for 3-bar imbalances.
- Overlap Mode (Strict / Loose) — geometric intersection vs ATR-tolerance match.
- Reward-to-Risk Target (default 2.0) — multiple used to project the target level.
- Max Active Pending Unicorns (default 3) — chart-cleanliness cap.
- Cooldown After Signal (default 30 bars) — minimum spacing between consecutive spawns.
- Invalidate on Close Through Zone (default off) — optional tighter invalidation rule.
- Visual controls — show/hide per lifecycle state, label size, zone opacity, max recent labels.
- Panel controls — show/hide, location (6 positions), theme (Dark/Light), text size.
How to Use
1. Add the indicator to any timeframe; higher timeframes (1H, 4H, 1D) tend to produce structurally more meaningful Unicorns.
2. Watch for a new Unicorn zone to appear. Pending zones are drawn in the directional state color with a bold border; triggered ones switch to the indigo accent color; TP / SL / Expired zones fade to their respective colors with a thinner border.
3. Each zone carries a tethered flag label outside the price axis — Bullish labels below, Bearish labels above — so they never overlap candles.
4. The panel reports running counts of pending and active Unicorns, historical win rate, average R per setup, and total completed.
5. Use the displayed entry / target / stop reference lines as a structural map for your own analysis. The tool does not place orders and does not recommend position sizing.
6. Combine with higher-timeframe bias (trend, session context, HTF structure) before acting on any zone.
Limitations & Transparency
- The detector is a structural scanner, not a forecasting engine. It reports what has formed, not what will happen.
- Swing detection depends on pivot length; shorter lengths generate more noise, longer lengths miss smaller structures.
- Statistics are calculated on-chart from historical bars loaded by TradingView and will vary with timeframe, symbol and data range.
- Realtime behaviour: zones are drawn on confirmed events (bar close for breaks, 3-bar-complete for FVGs). Some invalidations are evaluated intrabar on wick touches of the stop level.
- The script is open-source under Mozilla Public License 2.0. Users are encouraged to inspect and adapt the methodology.
Risk Disclosure
This indicator is provided for educational and analytical purposes only. It is not financial advice, a trading signal service, or a strategy. Past structural patterns do not guarantee future outcomes. Trading involves substantial risk of loss; readers are solely responsible for their own decisions and risk management. مؤشر

ICT MMXL Model [UAlgo]ICT MMXL Model is a liquidity sweep and exhaustion zone indicator designed to detect reversal candidates after price raids a prior swing and fails to hold beyond it. The script tracks confirmed swing highs and swing lows, waits for price to take one of those liquidity pools, then checks whether the sweep candle closes back inside the old structure. When that rejection is strong enough and the selected filters agree, the script builds an exhaustion zone that can later be monitored for retests or invalidation.
The core logic follows a very practical structure based workflow. A bearish setup forms when price sweeps above a prior swing high, but the same sweep candle closes back below that high. A bullish setup forms when price sweeps below a prior swing low, but the same sweep candle closes back above that low. This creates a failed expansion or exhaustion event, which is then projected forward on the chart as a zone.
What makes the script more selective than a simple sweep detector is its filter stack. It can require above average volume, a meaningful wick relative to the candle body, and visible momentum fade before the sweep occurs. These filters help focus the model on conditions where displacement appears to be tiring before the market raids liquidity and rejects the move.
Once a zone is created, it remains active until price closes beyond the invalidation boundary. While active, the script extends the zone, counts retests, optionally draws a mid line, and keeps the structure visible for future interaction. This makes the indicator useful not only for spotting the original sweep event, but also for tracking how price behaves when it revisits the exhaustion area later.
In practice, ICT MMXL Model can be used for liquidity based reversal analysis, rejection zone mapping, and structured retest monitoring. It is especially useful for traders who want a rules based way to identify failed sweep behavior and keep those zones on the chart until the market either respects or invalidates them.
🔹 Features
🔸 Prior Swing Liquidity Tracking
The script continuously records confirmed swing highs and swing lows using user defined pivot settings. Only the most recent group of swings is kept in memory, which keeps the model focused on nearby liquidity rather than distant historical structure.
🔸 Bearish and Bullish Sweep Detection
A bearish MMXL candidate appears when price trades above a prior swing high but closes back below it. A bullish MMXL candidate appears when price trades below a prior swing low but closes back above it. This captures the idea of a liquidity raid followed by rejection.
🔸 Volume Confirmation Filter
An optional volume filter requires the sweep candle to trade at or above a multiple of average volume. This helps avoid weaker sweeps that occur without meaningful participation.
🔸 Wick Rejection Filter
An optional wick filter requires the rejecting wick to be large relative to the candle body. For bearish setups, the upper wick must be large enough. For bullish setups, the lower wick must be large enough. This helps focus the model on candles that visibly reject the sweep area.
🔸 Momentum Fade Filter
An optional momentum fade filter checks whether body size and ATR have both decreased over a chosen lookback. This helps identify sweeps that occur after displacement has begun losing energy.
🔸 Automatic Exhaustion Zone Construction
When all setup conditions are met, the script creates a bullish or bearish exhaustion zone using the swept prior swing and the extreme of the sweep candle. This gives the user a clearly defined reaction area rather than a single line only.
🔸 Active Zone Extension
Once a zone is formed, it extends forward in time while it remains valid. This allows the trader to monitor later interaction without manually redrawing structure.
🔸 Retest Counting
The script tracks whether price reenters an active zone. Each first fresh entry increments the retest count, which is shown inside the zone label. This gives the user quick feedback on how many times the area has been revisited.
🔸 Mid Line Support
An optional dashed mid line can be drawn through the center of each zone. This can help visualize equilibrium inside the exhaustion area and provide an extra internal reference.
🔸 Sweep Marker Visualization
An optional visual marker is placed on the original sweep candle so the user can immediately see where the liquidity raid happened.
🔸 Violation Logic
A bullish zone is invalidated if price closes below the zone bottom. A bearish zone is invalidated if price closes above the zone top. Violated zones remain visible with muted styling so the user can still see where the structure failed.
🔸 Zone Limit Control
The script can limit the number of simultaneously active zones. If the maximum is reached, the oldest active zone is removed first. This helps control visual clutter.
🔸 Alert Support
Alerts are included for:
new bearish zone formation,
new bullish zone formation,
bullish zone retest,
bearish zone retest,
and zone violation.
This makes the script suitable for both visual chart work and alert driven monitoring.
🔹 Calculations
1) Defining Swing and Zone Objects
type SwingPoint
int barIdx
float price
bool isHigh
type ExhaustionZone
float zoneTop
float zoneBot
bool isBullish
int formBar
int formTime
int retests
bool isActive
bool inZone
bool hasMomentumFade
box zoneBox
line midLine
label zoneLabel
label sweepLabel
This is the structural foundation of the script.
A SwingPoint stores a confirmed swing location. It contains the bar index, the swing price, and whether the swing is a high or a low.
An ExhaustionZone stores the full lifecycle of a bearish or bullish MMXL setup. It keeps:
the zone top,
the zone bottom,
its direction,
when it formed,
how many retests it has seen,
whether it is still active,
whether price is currently inside it,
whether momentum fade was present,
and all visual objects used to draw it.
So before any detection begins, the script already has a clean data structure for both liquidity references and live exhaustion zones.
2) Confirming Swing Highs and Swing Lows
phPrice = ta.pivothigh(high, pivLeft, pivRight)
plPrice = ta.pivotlow (low, pivLeft, pivRight)
pivBarIdx = bar_index - pivRight
pivBarTime = time
if not na(phPrice)
sp = SwingPoint.new(barIdx=pivBarIdx, price=phPrice, isHigh=true)
swingHighs.push(sp)
if swingHighs.size() > maxSwings
swingHighs.shift()
if not na(plPrice)
sp = SwingPoint.new(barIdx=pivBarIdx, price=plPrice, isHigh=false)
swingLows.push(sp)
if swingLows.size() > maxSwings
swingLows.shift()
This is the first live detection step.
The script uses ta.pivothigh and ta.pivotlow to confirm structural highs and lows. Because a pivot is only confirmed after the chosen right side bars have passed, the actual pivot bar is not the current bar. That is why the script calculates:
pivBarIdx = bar_index - pivRight
pivBarTime = time
These values point back to the actual swing location.
When a confirmed pivot high appears, it is pushed into the swingHighs array. When a confirmed pivot low appears, it is pushed into the swingLows array. Each array is capped at the selected maximum size, so only the most recent prior swings are kept.
This means the script always maintains a fresh liquidity map of nearby highs and lows that may later be swept.
3) Referencing the Actual Sweep Candle
sweepBar = bar_index - pivRight
sweepHigh = high
sweepLow = low
sweepClose = close
sweepOpen = open
sweepVol = volume
sweepTime = time
This block is very important because the MMXL setup is evaluated on the pivot confirmed candle, not on the current bar.
Since pivot confirmation happens after pivRight bars, the actual candidate sweep candle lives pivRight bars in the past. The script therefore reads all needed values from that offset:
the high,
the low,
the open,
the close,
the volume,
and the time.
This allows the model to evaluate the true sweep candle rather than mixing its logic with the current bar.
4) Volume Filter Calculation
avgVol = ta.sma(volume, volLookback)
volOk = not useVolFilter or (sweepVol >= avgVol * volMult)
This is the first optional filter.
The script calculates average volume over the chosen lookback period and then reads that average at the sweep candle offset. It then compares the sweep candle volume against a user selected multiple of that average.
If the volume filter is enabled, the sweep candle must satisfy:
sweepVol >= avgVol * volMult
If the filter is disabled, volume automatically passes.
This helps the model avoid sweep candles that occur on weak participation and focus more on events where the raid happened with notable activity.
5) Momentum Fade Filter Calculation
isMomentumFading(int offset, int lookback) =>
bodyNow = math.abs(close - open )
bodyPrev = math.abs(close - open )
atrNow = ta.atr(14)
atrPrev = ta.atr(14)
bodyFade = bodyNow < bodyPrev
atrFade = atrNow < atrPrev
bodyFade and atrFade
This function checks whether displacement was weakening before the sweep occurred.
It compares two things:
the body size of the sweep candle versus the body size from earlier in the lookback window,
and the ATR at the sweep candle versus the ATR from earlier in the same window.
For momentum to be considered fading, both conditions must be true:
current body size must be smaller than the earlier body size,
and current ATR must be smaller than the earlier ATR.
That means the filter is looking for a sweep that occurs after both candle expansion and volatility have started to cool off. This can be useful for detecting conditions where price makes one final reach into liquidity as momentum begins to fade.
6) Bearish MMXL Detection Logic
if swingHighs.size() > 0 and barstate.isconfirmed
priorHigh = swingHighs.last().price
bearSweepCondition = sweepHigh > priorHigh and sweepClose < priorHigh
sweepBody = math.abs(sweepClose - sweepOpen)
upperWick = sweepHigh - math.max(sweepClose, sweepOpen)
bearWickOk = not useWickFilter or (sweepBody == 0.0 or upperWick >= sweepBody * wickRatio)
bearMomFade = momFade
momOkBear = not useMomFilter or bearMomFade
This is the core bearish setup logic.
First, the script checks that at least one prior swing high exists. It then defines the most recent stored swing high as the liquidity reference.
A bearish sweep exists only if both conditions are true:
the sweep candle trades above the prior swing high,
and the same sweep candle closes back below that prior high.
That is the classic failed buy side liquidity raid behavior.
Then the script calculates the candle body and upper wick. If the wick filter is enabled, the upper wick must be large enough relative to the body. If the momentum fade filter is enabled, the earlier momentum fade calculation must also pass.
So a bearish MMXL zone requires:
a sweep above prior highs,
a close back below the liquidity level,
and any enabled filters to agree.
7) Bullish MMXL Detection Logic
if swingLows.size() > 0 and barstate.isconfirmed
priorLow = swingLows.last().price
bullSweepCondition = sweepLow < priorLow and sweepClose > priorLow
sweepBody = math.abs(sweepClose - sweepOpen)
lowerWick = math.min(sweepClose, sweepOpen) - sweepLow
bullWickOk = not useWickFilter or (sweepBody == 0.0 or lowerWick >= sweepBody * wickRatio)
bullMomFade = momFade
momOkBull = not useMomFilter or bullMomFade
This is the mirror image of the bearish model.
The script checks that a prior swing low exists, then defines it as the current sell side liquidity reference.
A bullish sweep exists only if:
the sweep candle trades below the prior swing low,
and the same sweep candle closes back above that prior low.
That represents a failed sell side liquidity raid.
If the wick filter is enabled, the lower wick must be large enough relative to the body. If the momentum fade filter is enabled, the sweep must also occur while body size and ATR are both fading.
So a bullish MMXL zone requires:
a sweep below prior lows,
a close back above the liquidity level,
and all enabled filters to pass.
8) Preventing Duplicate Zone Creation
alreadyExists = false
for z in zones
if z.formTime == sweepTime
alreadyExists := true
break
This small block avoids duplicate zones from the same sweep candle.
Before creating a new zone, the script checks whether a zone with the same formation time already exists. If it does, the new one is ignored.
This matters because bullish and bearish checks both run inside the script, and repeated recalculation on confirmed bars could otherwise produce duplicate objects from the same event.
9) Controlling the Maximum Number of Active Zones
activeCount = 0
for z in zones
if z.isActive
activeCount += 1
if activeCount >= maxZones
for idx = 0 to zones.size() - 1
z = zones.get(idx)
if z.isActive
z.deleteDrawings()
z.isActive := false
break
This is the script’s chart management block.
Before a new zone is added, the script counts how many zones are still active. If that count has already reached the maximum allowed level, it searches from oldest to newest and removes the first active zone it finds.
The removed zone has its drawings deleted and its active state turned off.
This keeps the chart readable and prevents unlimited zone accumulation.
10) Building the Bearish and Bullish Zones
newZone = ExhaustionZone.new(
zoneTop = sweepHigh,
zoneBot = priorHigh,
isBullish = false,
formBar = sweepBar,
formTime = sweepTime,
retests = 0,
isActive = true,
inZone = false,
hasMomentumFade = bearMomFade,
zoneBox = na,
midLine = na,
zoneLabel = na,
sweepLabel = na)
newZone = ExhaustionZone.new(
zoneTop = priorLow,
zoneBot = sweepLow,
isBullish = true,
formBar = sweepBar,
formTime = sweepTime,
retests = 0,
isActive = true,
inZone = false,
hasMomentumFade = bullMomFade,
zoneBox = na,
midLine = na,
zoneLabel = na,
sweepLabel = na)
These two blocks define the actual exhaustion zones.
For bearish MMXL:
the zone top is the sweep candle high,
and the zone bottom is the prior swing high that got raided.
For bullish MMXL:
the zone top is the prior swing low that got raided,
and the zone bottom is the sweep candle low.
This is a very practical choice because the zone spans the rejection area between the liquidity level and the extreme of the sweep candle. In other words, the model does not just mark the swept price. It marks the full exhaustion region created by the failed expansion.
11) Drawing the Zone, Mid Line, and Sweep Marker
this.zoneBox := box.new(
left = this.formTime,
top = this.zoneTop,
right = time,
bottom = this.zoneBot,
border_color = bordCol,
border_width = 1,
bgcolor = fillCol,
xloc = xloc.bar_time)
if showMidLine
midLineCol = color.new(this.isBullish ? #00BCD4 : #FF5252, 55)
this.midLine := line.new(
x1 = this.formTime,
y1 = midPrice,
x2 = time,
y2 = midPrice,
color = midLineCol,
style = line.style_dashed,
width = 1,
xloc = xloc.bar_time)
This method handles the primary visual construction of each zone.
The script draws a filled box from the formation time to the current time, using the top and bottom prices of the exhaustion zone. If the mid line option is enabled, it also draws a dashed center line at the average of the zone top and zone bottom.
So the user gets:
the full zone body,
an optional equilibrium reference,
and live forward projection of the zone.
12) Zone Label and Momentum Fade Tag
fadeTag = this.hasMomentumFade ? " ⚡ Fading" : ""
labelText = (this.isBullish ? "MMXL ▲" : "MMXL ▼") +
" Retests: " + str.tostring(this.retests) + fadeTag
The label text is not static. It contains live information about the zone state.
Every label shows:
whether the zone is bullish or bearish,
how many retests have occurred,
and whether the setup formed with momentum fade.
This is useful because it lets the trader read structural context directly from the chart without opening settings or rechecking filters manually.
13) Extending the Zone and Updating Retests
method updateRight(ExhaustionZone this) =>
if not na(this.zoneBox)
box.set_right(this.zoneBox, time)
if showMidLine and not na(this.midLine)
line.set_x2(this.midLine, time)
if not na(this.zoneLabel)
label.set_x(this.zoneLabel, time)
fadeTagU = this.hasMomentumFade ? " ⚡ Fading" : ""
label.set_text(this.zoneLabel,
(this.isBullish ? "MMXL ▲" : "MMXL ▼") +
" Retests: " + str.tostring(this.retests) + fadeTagU)
if barstate.isconfirmed
for z in zones
if z.isActive
z.updateRight()
nowInside = z.isInsideZone()
if nowInside and not z.inZone
z.retests += 1
z.inZone := nowInside
These blocks manage the live state of every active zone.
On each confirmed bar, the script extends the right side of the box, the mid line, and the label to the latest time.
Then it checks whether price is currently inside the zone using isInsideZone() . If price has just entered the zone and it was not inside on the previous bar, the retest counter is incremented. The inZone flag is then updated.
This is important because retests are counted on fresh reentry, not on every bar that remains inside the zone. That prevents overcounting during long stays inside the same area.
14) How the Script Defines a Zone Retest
method isInsideZone(ExhaustionZone this) =>
high >= this.zoneBot and low <= this.zoneTop
This method defines zone interaction.
Price is considered inside a zone when the bar’s high is above or equal to the zone bottom and the bar’s low is below or equal to the zone top. In other words, any overlap between the current candle range and the zone counts as interaction.
This broad overlap definition is practical because zones are areas, not exact prices. A full candle close inside the zone is not required for retest counting.
15) Zone Violation Logic
method checkViolation(ExhaustionZone this) =>
if this.isBullish
close < this.zoneBot
else
close > this.zoneTop
This method defines when a zone is no longer valid.
For bullish zones:
a close below the zone bottom invalidates the structure.
For bearish zones:
a close above the zone top invalidates the structure.
This is a strict close based rule, which helps avoid invalidating the zone on a temporary wick only.
16) Visual Handling of Violated Zones
method violate(ExhaustionZone this) =>
this.isActive := false
if not na(this.zoneBox)
box.set_bgcolor(this.zoneBox, violatedCol)
box.set_border_color(this.zoneBox, color.new(#78909C, 50))
if showMidLine and not na(this.midLine)
line.set_color(this.midLine, color.new(#78909C, 70))
if not na(this.zoneLabel)
label.set_textcolor(this.zoneLabel, color.new(#78909C, 40))
label.set_text(this.zoneLabel,
(this.isBullish ? "MMXL ▲" : "MMXL ▼") +
" VIOLATED")
When a violation happens, the zone is not fully deleted. Instead, the script changes its state and appearance.
The zone becomes inactive, its colors are muted, and the label text changes to indicate that the structure has been violated.
This preserves chart history while clearly separating valid zones from failed ones.
17) Alert Logic for Formations, Retests, and Violations
alertcondition(newBearZone,
title = "MMXL — Bearish Exhaustion Zone Formed",
message = "MMXL: BSL sweep detected on {{ticker}} {{interval}}. Bearish exhaustion zone created.")
alertcondition(newBullZone,
title = "MMXL — Bullish Exhaustion Zone Formed",
message = "MMXL: SSL sweep detected on {{ticker}} {{interval}}. Bullish exhaustion zone created.")
alertcondition(bullRetest,
title = "MMXL — Bullish Zone Retest",
message = "MMXL: Price retesting bullish exhaustion zone on {{ticker}} {{interval}}.")
alertcondition(bearRetest,
title = "MMXL — Bearish Zone Retest",
message = "MMXL: Price retesting bearish exhaustion zone on {{ticker}} {{interval}}.")
alertcondition(bullViolated or bearViolated,
title = "MMXL — Zone Violated",
message = "MMXL: An exhaustion zone was violated (close outside zone) on {{ticker}} {{interval}}.")
These alerts turn the script into an event driven structure tool.
The first set alerts when a new bullish or bearish MMXL zone forms.
The second set alerts when price retests an active zone.
The third alert triggers when a zone becomes invalidated.
This makes the model useful not only for visual chart review, but also for live monitoring workflows. مؤشر

POC Sweep Reclaim [LuxAlgo]The POC Sweep Reclaim (PSR) model identifies a two-step "rejection then acceptance" price action pattern centered around the Point of Control (POC) of previous candles. By approximating volume-at-price data using lower timeframe (LTF) granularity, the tool highlights specific liquidity traps where price first fails to sustain a move beyond a high-volume level and subsequently reclaims it.
The PSR framework is built on the logic that a "Sweep" represents a failed probe of value, while the "Reclaim" represents a successful breach, signaling a potential shift in market dominance as price moves away from trapped participants.
🔶 USAGE
The indicator visualizes market microstructure dynamics through a sequence of two distinct events:
🔹 The Sweep (The Rejection)
A sweep occurs when a candle's wick trades through the previous bar's POC, but the candle body fails to close beyond it. This identifies a "Liquidity Grab" where price interacts with a high-volume node but fails to find acceptance, often trapping breakout traders.
Buyside Sweep: Price wicks above the previous POC but closes below it (Bearish Rejection). Sellside Sweep: Price wicks below the previous POC but closes above it (Bullish Rejection).
🔹 The Reclaim (The Acceptance)
A reclaim occurs when the candle immediately following a sweep successfully closes beyond the same POC level that was just rejected.
BSR (Buyside Reclaim): A bullish signal where price closes above a previously swept upper POC, suggesting the trap is resolved to the upside. SSR (Sellside Reclaim): A bearish signal where price closes below a previously swept lower POC, suggesting follow-through to the downside.
🔶 DETAILS
The script aims to bridge the gap between standard OHLCV analysis and order-flow dynamics. While a true footprint engine (available on higher TradingView tiers) is more accurate, this script uses a proxy by aggregating volume from a lower timeframe (e.g., 1-minute) to estimate the POC of higher-timeframe bars.
🔹 Academic Intuition
Order-Flow Imbalance (OFI): Short-term price changes are strongly linked to the inability of one side to provide enough depth. A "reclaim" reflects a shift where the dominant side successfully absorbs the liquidity that caused the initial rejection. Salient Prices: High-volume nodes like the POC act as psychological and mechanical barriers. Research indicates that liquidity clusters around these prominent prices, making them significant areas for support/resistance. Stop-Loss Cascades: Sweeps often interact with clustered stop-loss orders. If price reclaims the level after clearing these stops, it can trigger a directional move as the market "clears" the liquidity hurdle.
🔹 Practical Limitations
Footprint Proxy: The POC is calculated by aggregating volume at the close of LTF bars. This is a noisy proxy compared to a true footprint, which tracks every tick. Data Snooping: Like all pattern-based indicators, the "Reclaim" logic should be verified with robust backtesting to ensure signals are not the result of random price noise. Repainting: Because the POC depends on LTF data, the values for the current developing bar may fluctuate until the candle closes.
🔶 SETTINGS
Lower Timeframe for POC: Sets the granularity for volume aggregation. A lower value (like 1m) provides a more precise POC proxy. Show POC: Toggles the visibility of the calculated Point of Control dots for every bar. Show Sweep Dots: Displays markers at the POC level when a wick interaction occurs without a body close. Show BSR (Buyside Reclaim): Highlights candles that successfully close above a swept buyside POC. Show SSR (Sellside Reclaim): Highlights candles that successfully close below a swept sellside POC. مؤشر

استراتيجية

مؤشر

Bitcoin Expectile Model [LuxAlgo]The Bitcoin Expectile Model is a novel approach to forecasting Bitcoin, inspired by the popular Bitcoin Quantile Model by PlanC. By fitting multiple Expectile regressions to the price, we highlight zones of corrections or accumulations throughout the Bitcoin price evolution.
While we strongly recommend using this model with the Bitcoin All Time History Index INDEX:BTCUSD on the 3 days or weekly timeframe using a logarithmic scale, this model can be applied to any asset using the daily timeframe or superior.
Please note that here on TradingView, this model was solely designed to be used on the Bitcoin 1W chart, however, it can be experimented on other assets or timeframes if of interest.
🔶 USAGE
The Bitcoin Expectile Model can be applied similarly to models used for Bitcoin, highlighting lower areas of possible accumulation (support) and higher areas that allow for the anticipation of potential corrections (resistance).
By default, this model fits 7 individual Expectiles Log-Log Regressions to the price, each with their respective expectile ( tau ) values (here multiplied by 100 for the user's convenience). Higher tau values will return a fit closer to the higher highs made by the price of the asset, while lower ones will return fits closer to the lower prices observed over time.
Each zone is color-coded and has a specific interpretation. The green zone is a buy zone for long-term investing, purple is an anomaly zone for market bottoms that over-extend, while red is considered the distribution zone.
The fits can be extrapolated, helping to chart a course for the possible evolution of Bitcoin prices. Users can select the end of the forecast as a date using the "Forecast End" setting.
While the model is made for Bitcoin using a log scale, other assets showing a tendency to have a trend evolving in a single direction can be used. See the chart above on QQQ weekly using a linear scale as an example.
The Start Date can also allow fitting the model more locally, rather than over a large range of prices. This can be useful to identify potential shorter-term support/resistance areas.
🔶 DETAILS
🔹 On Quantile and Expectile Regressions
Quantile and Expectile regressions are similar; both return extremities that can be used to locate and predict prices where tops/bottoms could be more likely to occur.
The main difference lies in what we are trying to minimize, which, for Quantile regression, is commonly known as Quantile loss (or pinball loss), and for Expectile regression, simply Expectile loss.
You may refer to external material to go more in-depth about these loss functions; however, while they are similar and involve weighting specific prices more than others relative to our parameter tau, Quantile regression involves minimizing a weighted mean absolute error, while Expectile regression minimizes a weighted squared error.
The squared error here allows us to compute Expectile regression more easily compared to Quantile regression, using Iteratively reweighted least squares. For Quantile regression, a more elaborate method is needed.
In terms of comparison, Quantile regression is more robust, and easier to interpret, with quantiles being related to specific probabilities involving the underlying cumulative distribution function of the dataset; on the other expectiles are harder to interpret.
🔹 Trimming & Alterations
It is common to observe certain models ignoring very early Bitcoin price ranges. By default, we start our fit at the date 2010-07-16 to align with existing models.
By default, the model uses the number of time units (days, weeks...etc) elapsed since the beginning of history + 1 (to avoid NaN with log) as independent variable, however the Bitcoin All Time History Index INDEX:BTCUSD do not include the genesis block, as such users can correct for this by enabling the "Correct for Genesis block" setting, which will add the amount of missed bars from the Genesis block to the start oh the chart history.
🔶 SETTINGS
Start Date: Starting interval of the dataset used for the fit.
Correct for genesis block: When enabled, offset the X axis by the number of bars between the Bitcoin genesis block time and the chart starting time.
🔹 Expectiles
Toggle: Enable fit for the specified expectile. Disabling one fit will make the script faster to compute.
Expectile: Expectile (tau) value multiplied by 100 used for the fit. Higher values will produce fits that are located near price tops.
🔹 Forecast
Forecast End: Time at which the forecast stops.
🔹 Model Fit
Iterations Number: Number of iterations performed during the reweighted least squares process, with lower values leading to less accurate fits, while higher values will take more time to compute.
مؤشر

Profitable Loser Model [MMT]Profitable Loser Model
Overview
The Profitable Loser Model is a powerful PineScript v6 indicator designed to enhance your trading by visualizing key price levels, session open zones, Fibonacci retracements, and premium/discount zones. This overlay indicator provides traders with a customizable toolkit to analyze market structure across any timeframe, making it ideal for intraday and swing trading strategies.
Features
Open Zone Visualization
- Plots a box based on the open and close of the first candle in a user-defined timeframe (default: 5-minute).
- Customizable box color, projection offset, and label size (Tiny, Small, Normal, Large).
- Displays a timeframe label (e.g., "5m Open Zone") for quick reference, toggleable on/off.
Session Open Lines
- Optionally draws horizontal lines at key session opens (8:30 AM, 9:30 AM, 1:30 PM, Midnight, New York time).
- Customize line color, style (Solid, Dashed, Dotted), width, and label size for each session.
- Perfect for identifying critical intraday price levels.
Premium and Discount Zones
- Highlights premium (above midpoint) and discount (below midpoint) zones based on session high/low.
- Toggleable with customizable colors and projection offsets.
- Helps traders spot overbought/oversold areas for potential mean-reversion trades.
Fibonacci Retracement Levels
- Plots user-defined Fibonacci levels (default: 0.23, 0.35, 0.5, 0.62, 0.705, 0.79, 0.886, 1, 1.1).
- Customizable line style, width, color, and labels (showing percentage and/or price).
- Dynamically adjusts based on price movement relative to the open zone.
Take Profit (TP) and Stop Loss (SL) Levels
- Highlights TP (default: 0.23) and SL (default: 1.1) Fibonacci levels with distinct colors.
- Fully customizable to align with your risk-reward strategy.
How It Works
- Session Detection : Resets daily (or per user-defined timeframe) to capture the first candle's open, high, low, and close.
- Open Zone : Draws a box between the open and close, extended forward by the projection offset.
- Session Lines : Plots lines at specified session opens with customizable styles and labels.
- Fibonacci Retracement : Adjusts levels dynamically based on session high/low and price action.
- Premium/Discount Zones : Calculated from the session range midpoint, updated in real-time.
Settings
- Open Zone :
- Timeframe (default: 5m), Calculate Timeframe (default: Daily).
- Toggle label, adjust size, box color, and projection offset.
- Session Open Lines :
- Enable/disable lines for 8:30 AM, 9:30 AM, 1:30 PM, Midnight.
- Customize color, style, width, label size, and vertical offset.
- Premium/Discount Zones :
- Toggle visibility, set colors, and adjust projection offset.
- Fibonacci Retracement :
- Toggle visibility, set custom levels, line style, width, color, and label options.
- Adjust projection offset.
- TP/SL :
- Set TP/SL Fibonacci levels and colors.
Use Cases
- Intraday Trading : Use session open lines and open zones to trade key market hours.
- Swing Trading : Leverage Fibonacci levels for potential reversal or continuation zones.
- Risk Management : Set precise TP/SL levels based on Fibonacci retracements.
- Market Structure : Identify overbought/oversold zones with premium/discount areas.
Notes
- Optimized with `dynamic_requests = true` for efficient real-time data handling.
- Visual elements (boxes, lines, labels) are cleaned up at the start of each new session.
- Session lines use New York time (`America/New_York`) for alignment with major markets. مؤشر

Bitcoin Power Law [LuxAlgo]The Bitcoin Power Law tool is a representation of Bitcoin prices first proposed by Giovanni Santostasi, Ph.D. It plots BTCUSD daily closes on a log10-log10 scale, and fits a linear regression channel to the data.
This channel helps traders visualise when the price is historically in a zone prone to tops or located within a discounted zone subject to future growth.
🔶 USAGE
Giovanni Santostasi, Ph.D. originated the Bitcoin Power-Law Theory; this implementation places it directly on a TradingView chart. The white line shows the daily closing price, while the cyan line is the best-fit regression.
A channel is constructed from the linear fit root mean squared error (RMSE), we can observe how price has repeatedly oscillated between each channel areas through every bull-bear cycle.
Excursions into the upper channel area can be followed by price surges and finishing on a top, whereas price touching the lower channel area coincides with a cycle low.
Users can change the channel areas multipliers, helping capture moves more precisely depending on the intended usage.
This tool only works on the daily BTCUSD chart. Ticker and timeframe must match exactly for the calculations to remain valid.
🔹 Linear Scale
Users can toggle on a linear scale for the time axis, in order to obtain a higher resolution of the price, (this will affect the linear regression channel fit, making it look poorer).
🔶 DETAILS
One of the advantages of the Power Law Theory proposed by Giovanni Santostasi is its ability to explain multiple behaviors of Bitcoin. We describe some key points below.
🔹 Power-Law Overview
A power law has the form y = A·xⁿ , and Bitcoin’s key variables follow this pattern across many orders of magnitude. Empirically, price rises roughly with t⁶, hash-rate with t¹² and the number of active addresses with t³.
When we plot these on log-log axes they appear as straight lines, revealing a scale-invariant system whose behaviour repeats proportionally as it grows.
🔹 Feedback-Loop Dynamics
Growth begins with new users, whose presence pushes the price higher via a Metcalfe-style square-law. A richer price pool funds more mining hardware; the Difficulty Adjustment immediately raises the hash-rate requirement, keeping profit margins razor-thin.
A higher hash rate secures the network, which in turn attracts the next wave of users. Because risk and Difficulty act as braking forces, user adoption advances as a power of three in time rather than an unchecked S-curve. This circular causality repeats without end, producing the familiar boom-and-bust cadence around the long-term power-law channel.
🔹 Scale Invariance & Predictions
Scale invariance means that enlarging the timeline in log-log space leaves the trajectory unchanged.
The same geometric proportions that described the first dollar of value can therefore extend to a projected million-dollar bitcoin, provided no catastrophic break occurs. Institutional ETF inflows supply fresh capital but do not bend the underlying slope; only a persistent deviation from the line would falsify the current model.
🔹 Implications
The theory assigns scarcity no direct role; iterative feedback and the Difficulty Adjustment are sufficient to govern Bitcoin’s expansion. Long-term valuation should focus on position within the power-law channel, while bubbles—sharp departures above trend that later revert—are expected punctuations of an otherwise steady climb.
Beyond about 2040, disruptive technological shifts could alter the parameters, but for the next order of magnitude the present slope remains the simplest, most robust guide.
Bitcoin behaves less like a traditional asset and more like a self-organising digital organism whose value, security, and adoption co-evolve according to immutable power-law rules.
🔶 SETTINGS
🔹 General
Start Calculation: Determine the start date used by the calculation, with any prior prices being ignored. (default - 15 Jul 2010)
Use Linear Scale for X-Axis: Convert the horizontal axis from log(time) to linear calendar time
🔹 Linear Regression
Show Regression Line: Enable/disable the central power-law trend line
Regression Line Color: Choose the colour of the regression line
Mult 1: Toggle line & fill, set multiplier (default +1), pick line colour and area fill colour
Mult 2: Toggle line & fill, set multiplier (default +0.5), pick line colour and area fill colour
Mult 3: Toggle line & fill, set multiplier (default -0.5), pick line colour and area fill colour
Mult 4: Toggle line & fill, set multiplier (default -1), pick line colour and area fill colour
🔹 Style
Price Line Color: Select the colour of the BTC price plot
Auto Color: Automatically choose the best contrast colour for the price line
Price Line Width: Set the thickness of the price line (1 – 5 px)
Show Halvings: Enable/disable dotted vertical lines at each Bitcoin halving
Halvings Color: Choose the colour of the halving lines
مؤشر

مؤشر

Market Structure Targets Model [LuxAlgo]The Market Structure Targets Model indicator provides an algorithmic approach to setting targets from market structure shifts (MSS) and market structure breaks (MSB), two popular Smart Money Concept (SMC) concepts. Depending on the target % settings, they can be used as take profit, confirmation levels, or potential reversal points.
🔶 USAGE
Our Market Structure Targets Model scripts provide automated and customizable targets from MSS and MSB. Each displayed target can be used in several ways described in the sub-sections below:
🔹 Take Profit
The targets can be used as take profit levels, where the target distance can be set separately for bullish/bearish MSS/MSB respectively.
🔹 Confirmation Levels
Alternatively, targets can be used as an additional confirmation level of a trend reversal when set at a lower percentage, filtering out fake signals that might be given from market structures. In this way, targets can be used as potential entry levels.
🔹 Potential Reversal Points
In some circumstances, targets being reached can be indicative of trend reversals. The percentage of the targets would be typically set higher to allow for trend exhaustion.
The above examples highlight this usage for bearish reversal scenarios, while the image below highlights it for bullish reversal scenarios.
🔹 Support/Resistance Levels
The targets, being horizontal levels, can also serve as potential support/resistances, with breakouts potentially confirming new trends. It is important to remain observant of the market structure. An MSS or MSB in the opposite direction provides essential information to be included in future decisions.
Using multiple timeframes can help detect longer-term trends. Depending on the user's preference, they can choose the appropriate timeframe for their needs.
Note that Target lines will only be drawn when the Target Level exceeds the close value when it is drawn.
🔹 Maximum Target Duration
The Maximum Target Duration setting removes unreached target levels when the amount of bars since the associated market structure of that target exceeds the user set limit. This effectively allows the removal of any target that might no longer be relevant to newer trends.
🔹 Type: Switch/Hold
This setting is another way to control unreached target levels.
Switch: When a new MSS/MSB is found, the previous target level associated with a market structure with the same direction (bullish/bearish) is deleted if it hasn't been reached.
Hold: Target levels are retained and continuously evaluated when a new MSS/MSB is formed.
The target level will be removed in both cases when the Maximum Target Duration condition is applied.
The above example shows the case when the Type setting is set to Switch , while in the example below, it is set to Hold .
🔶 DETAILS
🔹 Market Structure
Market structures are commonly classified as follows:
Market Structure Shift (MSS), also referred to as Change of Character (CHoCH)
Market Structure Break (MSB), also referred to as Break of Structure (BOS)
MSS indicates a shift in the market trend, confirming trend reversals. Conversely, MSB occurs once a trend is already determined, confirming new higher highs/lower lows.
🔹 Targets
A: Highest/lowest between the extremities of the MSS/MSB line
B: Price value of the MSS/MSB line
The distance between A and B is projected on the opposite side of the MSS/MSB line, adjusted with a percentage that can be set by the user. The above example used 100% of the distance between A and B.
The Target Percentage of MSS and MSB can be set separately for bullish or bearish market structures.
🔶 SETTINGS
Swings: Period used for the swing detection, with higher values returning longer-term Swing Levels.
Type: the Switch/Hold setting controls unattained target levels
Maximum Target Duration: removes the target lines when the amount of bars since the drawing of the target exceeds the limit and the target has not been reached
🔹 Market Structure Shift (MSS)
Bullish: Toggle, color setting, % Target
Bearish: Toggle, color setting, % Target
🔹 Market Structure Break (MSB)
Bullish: Toggle, color setting, % Target
Bearish: Toggle, color setting, % Target
مؤشر

Returns Model by TenozenHey there! I've been diving into the book "Paul Wilmott on Quantitative Finance," and I stumbled upon this cool model for calculating and modeling returns. Basically, it helps us figure out how much a price has changed over a set number of periods—I like to use 20 periods as a default. Once we get that rate of change value, we crunch some numbers to find the standard deviation and mean using all the historical data we have. That's the foundation of this model.
Now, let's talk about how to use it. This model shows us how returns and price behavior are connected. When returns hang out in the +1 to +2 standard deviation range, it usually means returns are about to drop, and vice versa. Often, this leads to corresponding price moves. But here's the thing: sometimes prices don't do what we expect. Why? It's because there's another hidden factor at play—I like to call it "power."
This "power" isn't something we can see directly, but it's there. Basically, when returns are within that standard deviation range, the market faces resistance when trying to move in its preferred direction, whether bullish or bearish. The strength of this "power" determines if the market will snap back to the average or go for a wild ride. It can show up as small price wiggles, big price jumps, or lightning-fast moves. By understanding this "power," we can get a better handle on what the market might do next and avoid getting blindsided. In the meantime, I couldn't explain "power" yet, but In the future, when I've learned enough, I'd love to share the model with you guys!
So... I'm planning to explore and share more models from this book as I learn, even if those pesky math formulas can be tough to crack. I hope you find this indicator as helpful as I do, and if you've got any suggestions or feedback, please feel free to share! Ciao!
مؤشر

مؤشر

Normal Distribution CurveThis Normal Distribution Curve is designed to overlay a simple normal distribution curve on top of any TradingView indicator. This curve represents a probability distribution for a given dataset and can be used to gain insights into the likelihood of various data levels occurring within a specified range, providing traders and investors with a clear visualization of the distribution of values within a specific dataset. With the only inputs being the variable source and plot colour, I think this is by far the simplest and most intuitive iteration of any statistical analysis based indicator I've seen here!
Traders can quickly assess how data clusters around the mean in a bell curve and easily see the percentile frequency of the data; or perhaps with both and upper and lower peaks identify likely periods of upcoming volatility or mean reversion. Facilitating the identification of outliers was my main purpose when creating this tool, I believed fixed values for upper/lower bounds within most indicators are too static and do not dynamically fit the vastly different movements of all assets and timeframes - and being able to easily understand the spread of information simplifies the process of identifying key regions to take action.
The curve's tails, representing the extreme percentiles, can help identify outliers and potential areas of price reversal or trend acceleration. For example using the RSI which typically has static levels of 70 and 30, which will be breached considerably more on a less liquid or more volatile asset and therefore reduce the actionable effectiveness of the indicator, likewise for an asset with little to no directional volatility failing to ever reach this overbought/oversold areas. It makes considerably more sense to look for the top/bottom 5% or 10% levels of outlying data which are automatically calculated with this indicator, and may be a noticeable distance from the 70 and 30 values, as regions to be observing for your investing.
This normal distribution curve employs percentile linear interpolation to calculate the distribution. This interpolation technique considers the nearest data points and calculates the price values between them. This process ensures a smooth curve that accurately represents the probability distribution, even for percentiles not directly present in the original dataset; and applicable to any asset regardless of timeframe. The lookback period is set to a value of 5000 which should ensure ample data is taken into calculation and consideration without surpassing any TradingView constraints and limitations, for datasets smaller than this the indicator will adjust the length to just include all data. The labels providing the percentile and average levels can also be removed in the style tab if preferred.
Additionally, as an unplanned benefit is its applicability to the underlying price data as well as any derived indicators. Turning it into something comparable to a volume profile indicator but based on the time an assets price was within a specific range as opposed to the volume. This can therefore be used as a tool for identifying potential support and resistance zones, as well as areas that mark market inefficiencies as price rapidly accelerated through. This may then give a cleaner outlook as it eliminates the potential drawbacks of volume based profiles that maybe don't collate all exchange data or are misrepresented due to large unforeseen increases/decreases underlying capital inflows/outflows.
Thanks to @ALifeToMake, @Bjorgum, vgladkov on stackoverflow (and possibly some chatGPT!) for all the assistance in bringing this indicator to life. I really hope every user can find some use from this and help bring a unique and data driven perspective to their decision making. And make sure to please share any original implementaions of this tool too! If you've managed to apply this to the average price change once you've entered your position to better manage your trade management, or maybe overlaying on an implied volatility indicator to identify potential options arbitrage opportunities; let me know! And of course if anyone has any issues, questions, queries or requests please feel free to reach out! Thanks and enjoy. مؤشر

مؤشر

FunctionBlackScholesLibrary "FunctionBlackScholes"
Some methods for the Black Scholes Options Model, which demonstrates several approaches to the valuation of a European call.
// reference:
// people.math.sc.edu
// people.math.sc.edu
asset_path(s0, mu, sigma, t1, n) Simulates the behavior of an asset price over time.
Parameters:
s0 : float, asset price at time 0.
mu : float, growth rate.
sigma : float, volatility.
t1 : float, time to expiry date.
n : int, time steps to expiry date.
Returns: option values at each equal timed step (0 -> t1)
binomial(s0, e, r, sigma, t1, m) Uses the binomial method for a European call.
Parameters:
s0 : float, asset price at time 0.
e : float, exercise price.
r : float, interest rate.
sigma : float, volatility.
t1 : float, time to expiry date.
m : int, time steps to expiry date.
Returns: option value at time 0.
bsf(s0, t0, e, r, sigma, t1) Evaluates the Black-Scholes formula for a European call.
Parameters:
s0 : float, asset price at time 0.
t0 : float, time at which the price is known.
e : float, exercise price.
r : float, interest rate.
sigma : float, volatility.
t1 : float, time to expiry date.
Returns: option value at time 0.
forward(e, r, sigma, t1, nx, nt, smax) Forward difference method to value a European call option.
Parameters:
e : float, exercise price.
r : float, interest rate.
sigma : float, volatility.
t1 : float, time to expiry date.
nx : int, number of space steps in interval (0, L).
nt : int, number of time steps.
smax : float, maximum value of S to consider.
Returns: option values for the european call, float array of size ((nx-1) * (nt+1)).
mc(s0, e, r, sigma, t1, m) Uses Monte Carlo valuation on a European call.
Parameters:
s0 : float, asset price at time 0.
e : float, exercise price.
r : float, interest rate.
sigma : float, volatility.
t1 : float, time to expiry date.
m : int, time steps to expiry date.
Returns: confidence interval for the estimated range of valuation. مكتبة

مؤشر

Ripple (XRP) Model PriceAn article titled Bitcoin Stock-to-Flow Model was published in March 2019 by "PlanB" with mathematical model used to calculate Bitcoin model price during the time. We know that Ripple has a strong correlation with Bitcoin. But does this correlation have a definite rule?
In this study, we examine the relationship between bitcoin's stock-to-flow ratio and the ripple(XRP) price.
The Halving and the stock-to-flow ratio
Stock-to-flow is defined as a relationship between production and current stock that is out there.
SF = stock / flow
The term "halving" as it relates to Bitcoin has to do with how many Bitcoin tokens are found in a newly created block. Back in 2009, when Bitcoin launched, each block contained 50 BTC, but this amount was set to be reduced by 50% every 210,000 blocks (about 4 years). Today, there have been three halving events, and a block now only contains 6.25 BTC. When the next halving occurs, a block will only contain 3.125 BTC. Halving events will continue until the reward for minors reaches 0 BTC.
With each halving, the stock-to-flow ratio increased and Bitcoin experienced a huge bull market that absolutely crushed its previous all-time high. But what exactly does this affect the price of Ripple?
Price Model
I have used Bitcoin's stock-to-flow ratio and Ripple's price data from April 1, 2014 to November 3, 2021 (Daily Close-Price) as the statistical population.
Then I used linear regression to determine the relationship between the natural logarithm of the Ripple price and the natural logarithm of the Bitcoin's stock-to-flow (BSF).
You can see the results in the image below:
Basic Equation : ln(Model Price) = 3.2977 * ln(BSF) - 12.13
The high R-Squared value (R2 = 0.83) indicates a large positive linear association.
Then I "winsorized" the statistical data to limit extreme values to reduce the effect of possibly spurious outliers (This process affected less than 4.5% of the total price data).
ln(Model Price) = 3.3297 * ln(BSF) - 12.214
If we raise the both sides of the equation to the power of e, we will have:
============================================
Final Equation:
■ Model Price = Exp(- 12.214) * BSF ^ 3.3297
Where BSF is Bitcoin's stock-to-flow
============================================
If we put current Bitcoin's stock-to-flow value (54.2) into this equation we get value of 2.95USD. This is the price which is indicated by the model.
There is a power law relationship between the market price and Bitcoin's stock-to-flow (BSF). Power laws are interesting because they reveal an underlying regularity in the properties of seemingly random complex systems.
I plotted XRP model price (black) over time on the chart.
Estimating the range of price movements
I also used several bands to estimate the range of price movements and used the residual standard deviation to determine the equation for those bands.
Residual STDEV = 0.82188
ln(First-Upper-Band) = 3.3297 * ln(BSF) - 12.214 + Residual STDEV =>
ln(First-Upper-Band) = 3.3297 * ln(BSF) – 11.392 =>
■ First-Upper-Band = Exp(-11.392) * BSF ^ 3.3297
In the same way:
■ First-Lower-Band = Exp(-13.036) * BSF ^ 3.3297
I also used twice the residual standard deviation to define two extra bands:
■ Second-Upper-Band = Exp(-10.570) * BSF ^ 3.3297
■ Second-Lower-Band = Exp(-13.858) * BSF ^ 3.3297
These bands can be used to determine overbought and oversold levels.
Estimating of the future price movements
Because we know that every four years the stock-to-flow ratio, or current circulation relative to new supply, doubles, this metric can be plotted into the future.
At the time of the next halving event, Bitcoins will be produced at a rate of 450 BTC / day. There will be around 19,900,000 coins in circulation by August 2025
It is estimated that during first year of Bitcoin (2009) Satoshi Nakamoto (Bitcoin creator) mined around 1 million Bitcoins and did not move them until today. It can be debated if those coins might be lost or Satoshi is just waiting still to sell them but the fact is that they are not moving at all ever since. We simply decrease stock amount for 1 million BTC so stock to flow value would be:
BSF = (19,900,000 – 1.000.000) / (450 * 365) =115.07
Thus, Bitcoin's stock-to-flow will increase to around 115 until AUG 2025. If we put this number in the equation:
Model Price = Exp(- 12.214) * 114 ^ 3.3297 = 36.06$
Ripple has a fixed supply rate. In AUG 2025, the total number of coins in circulation will be about 56,000,000,000. According to the equation, Ripple's market cap will reach $2 trillion.
Note that these studies have been conducted only to better understand price movements and are not a financial advice. مؤشر

مؤشر

مؤشر

Fourier series Model Of The Market█ OVERVIEW
The Fourier Series Model of the Market (FSMM) decomposes price action into harmonic components using bandpass filtering, then reconstructs a composite wave weighted by rolling energy ratios. This approach isolates cyclical market behavior at multiple frequencies, emphasizing dominant cycles for cleaner signal generation. The energy-adaptive weighting is the key differentiator from simple harmonic summation: cycles that dominate current price action contribute more to the output.
Based on Fourier analysis principles applied to financial markets, the indicator extracts harmonics (fundamental, 2nd, 3rd, etc.) using second-order IIR bandpass filters, then weights each harmonic's contribution by its relative energy compared to adjacent harmonics. This energy-adaptive weighting naturally emphasizes the cycles that are most prominent in current market conditions.
█ CONCEPTS
Fourier Decomposition
Fourier analysis represents any periodic signal as a sum of sine waves at different frequencies. In market analysis, price action can be decomposed into a fundamental cycle (the base period) plus harmonics at integer multiples of that frequency (period/2, period/3, etc.). Each harmonic captures oscillations at a specific frequency band, and their sum reconstructs the original cyclical behavior.
Bandpass Filtering
Each harmonic is extracted using a second-order IIR (Infinite Impulse Response) bandpass filter tuned to that harmonic's frequency. The filter isolates price activity within a narrow frequency range while rejecting both higher-frequency noise and lower-frequency trend drift. Before filtering, the source is debiased via 2-bar momentum to remove DC offset, ensuring each bandpass operates around true zero.
Energy-Weighted Reconstruction
Rather than simply summing all harmonics equally, FSMM weights each harmonic by its rolling energy relative to the previous harmonic. The energy score combines the current harmonic value with its rate of change, so it reflects both amplitude and momentum. Higher harmonics that hold comparatively more energy therefore contribute more to the composite wave, while weaker harmonics fade out. This adaptive weighting allows the model to respond to changing market cyclicality.
Quadrature Component (Rate of Change)
The rate of change output represents the 90°-phase-shifted (quadrature) component of the wave. When the wave is at zero and rising, the rate of change is at maximum positive. This provides complementary information about cycle phase and can be used for timing entries relative to cycle position.
█ INTERPRETATION
Wave Output
The composite wave oscillates around zero, representing the sum of all extracted harmonic components weighted by energy:
• Above zero : Net bullish cyclical momentum across harmonics
• Below zero : Net bearish cyclical momentum across harmonics
• Zero crossings : Cycle phase transitions - potential reversal points
• Wave amplitude : Strength of cyclical behavior; larger swings indicate cleaner cycles
Rate of Change
The quadrature component (90° phase-shifted) provides cycle phase information:
• Maximum rate of change : Wave is near zero and accelerating - early cycle phase
• Zero rate of change : Wave is at peak or trough - cycle extremes
• Rate/Wave divergence : When wave makes new highs/lows but rate of change does not confirm (lower momentum), suggests cycle exhaustion or impending phase shift
Combined Analysis
• Wave crossing above zero with positive rate of change: Strong bullish cycle initiation
• Wave crossing below zero with negative rate of change: Strong bearish cycle initiation
• Wave at extreme with rate of change reversing: Potential cycle peak/trough
Threshold Bands
When enabled, threshold bands define statistically significant wave deviations:
• Breach above +threshold : Unusually strong bullish cyclical behavior
• Breach below -threshold : Unusually strong bearish cyclical behavior
• Return inside thresholds : Normalizing behavior, potential mean reversion ahead
Alert Conditions
Four built-in alerts trigger on bar close (no repainting):
• Above +Threshold : Strong bullish cycle behavior
• Below -Threshold : Strong bearish cycle behavior
• Above Zero : Bullish cycle phase shift
• Below Zero : Bearish cycle phase shift
█ SETTINGS & PARAMETER TUNING
Fourier Series Model
• Source : Price series to decompose into harmonic components.
• Period (6-100): Base period for the fundamental harmonic. Higher harmonics divide this period (harmonic 2 = period/2, harmonic 3 = period/3). Match to the dominant market cycle for best results. Default 20.
• Bandwidth (0.05-0.5): Bandpass filter selectivity. Lower values create narrower passbands that isolate harmonics more precisely but may miss slightly off-frequency cycles. Higher values capture broader ranges but reduce harmonic separation. Default 0.1 balances precision and robustness.
• Harmonics (1-20): Number of harmonic components to extract. More harmonics capture finer cyclical detail but increase computation. For most applications, 3-5 harmonics suffice. The fundamental alone (1 harmonic) functions as a simple bandpass filter.
Display Settings
• Wave Outputs : Toggle visibility and color of the composite Fourier wave.
• Rate of Change : Toggle visibility and color of the quadrature component (90° phase-shifted wave).
• Zero Line : Reference line for oscillator neutrality.
Diagnostics - Dynamic Thresholds
Optional significance bands that identify when wave readings indicate strong cyclical behavior:
• Dynamic Threshold : Toggle threshold bands and set colors.
• Threshold Mode : Select calculation method:
- MAD (Median Absolute Deviation) : Robust, outlier-resistant measure using k * MAD where MAD ≈ 0.6745 * stdev.
- Standard Deviation : Volatility-sensitive, calculated as k * stdev of wave over the lookback period.
- Percentile Rank : Fixed probability bands using percentile of |wave| (90% means only 10% of values exceed threshold).
• Period (2-200): Lookback for threshold calculations. Default 50.
• Multiplier (k) : Scaling for MAD/Standard Deviation modes. Default 1.5.
• Percentile (%) (0-100): For Percentile Rank mode only. Default 90%.
Parameter Interactions
• Shorter periods respond faster to cycle changes but may capture noise.
• Lower bandwidth + more harmonics = more precise decomposition but requires accurate period setting.
• Higher bandwidth is more forgiving of period mismatches.
• For strongly trending markets, restrict harmonics to 1-2 so the model tracks the dominant cycle with fewer higher-frequency components.
• For ranging/oscillating markets, more harmonics (4-6) capture complex cycles.
█ LIMITATIONS
Inherent Characteristics
• Period dependency : Effectiveness depends on correctly matching the Period parameter to actual market cycles. Use cycle measurement tools (autocorrelation, FFT, dominant cycle indicators) to identify appropriate periods.
• Stationarity assumption : The indicator assumes cycle frequencies remain relatively stable within the lookback window. Rapidly shifting dominant cycles (regime transitions) may produce inconsistent results until the buffer adapts.
• Filter lag : Despite bandpass design, some lag remains inherent to causal filtering. Higher harmonics have less lag but more noise sensitivity.
• Energy weighting artifacts : During regime changes when harmonic energy ratios shift rapidly, weighting may produce transient anomalies.
Market Conditions to Avoid
• Strong trending markets : Pure trends with no cyclicality produce weak, meandering signals. The indicator assumes cyclical market behavior.
• News events/gaps : Large discontinuities disrupt filter continuity. Requires 1-2 full periods to stabilize.
• Period mismatch : If the Period parameter doesn't match actual market cycles, harmonic extraction produces noise rather than signal.
Parameter Selection Pitfalls
• Too many harmonics : Beyond 5-6 harmonics, additional components often capture noise rather than meaningful cycles.
• Bandwidth too narrow : Very low bandwidth (< 0.05) requires extremely precise period matching; slight mismatches cause signal loss.
• Over-optimization : Perfect historical parameter fits typically fail forward. Use robust defaults across multiple instruments.
█ NOTES
Credits
This indicator applies Fourier analysis principles to financial market data, building on the extensive work of Dr. John F. Ehlers in applying digital signal processing to trading. The bandpass filter implementation and harmonic decomposition approach draw from DSP fundamentals as presented in Ehlers' publications.
For those interested in the underlying mathematics and DSP concepts:
• Ehlers, J.F. (2001). Rocket Science for Traders: Digital Signal Processing Applications . John Wiley & Sons.
• Ehlers, J.F. (2013). Cycle Analytics for Traders . John Wiley & Sons.
• Various TASC articles by John Ehlers on bandpass filters, cycle analysis, and harmonic decomposition.
by ♚@e2e4 مؤشر
