Leverage Pressure Map [BOSWaves]Leverage Pressure Map - Volume-Weighted Liquidation Level Projection with Thermal Heatmap Visualization
Overview
Leverage Pressure Map is a leveraged position liquidation estimation system that projects where open leveraged positions would be force-liquidated based on current price and volume activity, where heatmap intensity, level density, and distribution sidebar are driven by accumulated volume-weighted contract estimates at each price band rather than arbitrary fixed grid overlays or static percentage calculations.
Instead of displaying a generic liquidation grid at fixed intervals, the system builds its heatmap organically from price action, projecting liquidation zones from each bar's close in the direction that would liquidate the positions opened on that bar, weighting each level by the bar's volume and by the leverage multiple configured, and accumulating contract estimates over time to reveal where the greatest concentration of leveraged exposure has built up relative to current price.
This creates a continuously evolving pressure map where bands closest to price reflect the most recently opened leveraged positions, higher-leverage bands cluster tighter to price than lower-leverage equivalents, thermal coloring from the base color through yellow to white reveals the most dangerous liquidation clusters at a glance, and a sidebar distribution profile summarizes the full pressure landscape across the visible price range in a compact bar chart.
Price is therefore evaluated not just directionally but against a constantly updating picture of where forced selling and forced buying from leveraged liquidations is likely to cascade if price reaches those levels.
Conceptual Framework
Leverage Pressure Map is founded on the principle that leveraged market participation leaves a predictable spatial footprint in price space, and that estimating the distribution of that footprint from volume and price data provides actionable information about where cascading liquidation events are most likely to concentrate.
In leveraged markets, positions opened at any given price carry a liquidation distance determined by their leverage multiple. A 100x long position opened at the close of a bullish bar will liquidate approximately one percent below that close. A 10x position will liquidate approximately ten percent below. By projecting these distances from the close of each bar, weighting by volume as a proxy for participation size, and accumulating those estimates across all recent bars, the map builds a statistical picture of where the most leveraged exposure is concentrated without requiring access to exchange order book data.
Three core principles guide the design:
Liquidation levels should be projected from the close of each directional bar at the mathematically correct distance for each configured leverage multiple, weighted by volume to reflect the relative size of participation at each price point.
Thermal coloring should normalize all levels against the global maximum contract estimate, producing a relative intensity map that immediately identifies the highest-pressure clusters regardless of absolute contract values.
A sidebar distribution profile should aggregate the full heatmap into a compact price-by-pressure bar chart, providing a summary view of the total liquidation landscape without requiring the full heatmap to be analyzed row by row.
This shifts market analysis from directional price reading into leveraged exposure mapping where the spatial distribution of forced liquidation risk is continuously estimated and visualized alongside price action.
Theoretical Foundation
The indicator combines per-bar liquidation price calculation for configurable leverage multiples, volume-weighted contract accumulation at snapped price bands, global maximum normalization for thermal color mapping, sweep detection for removing levels that price has already passed through, and a sidebar bin aggregation system that compresses all active levels into a configurable number of price rows for distribution visualization.
Liquidation prices for long positions are calculated as close multiplied by one minus one divided by leverage, projecting below the close at a distance inversely proportional to the leverage multiple. Short liquidation prices are calculated as close multiplied by one plus one divided by leverage, projecting above the close. Each projected price is snapped to the nearest band boundary defined by the tick-scaled level height, ensuring levels accumulate at consistent grid positions rather than scattering across continuous price space. Leverage weights are assigned proportionally, with higher leverage multiples receiving greater weight reflecting their more aggressive risk profile.
Four internal systems operate in tandem:
Liquidation Projection Engine : On each bar with volume, calculates liquidation prices for all configured leverage multiples in both directions, snaps each price to the nearest level band, and either adds contract weight to an existing band or creates a new band at that position.
Sweep and Extension System : On each bar, extends all active level bands rightward to the current bar and removes any long liquidation bands that price has fallen through or short liquidation bands that price has risen through, keeping the heatmap current with price movement.
Thermal Color Engine : Normalizes each level's accumulated contracts against the global maximum and maps the result through a four-stage thermal gradient that progresses from a transparent base color at low concentration through the full base color to yellow and finally to near-white at peak concentration.
Sidebar Distribution System : On the last bar, aggregates all active long and short liquidation levels into configurable price bins spanning the recent high-low range extended to cover all active levels, draws proportional horizontal bars for each bin based on its relative contract sum, and plots a peak level line at the highest-concentration bin.
This design allows the heatmap to build organically from price action while the sidebar provides a continuous summary view of the full liquidation pressure distribution.
How It Works
Leverage Pressure Map evaluates price through a sequence of projection and accumulation processes:
Level Band Sizing : The minimum tick multiplied by the configured level scale produces the height of each liquidation band, controlling the granularity of the pressure grid relative to the instrument's tick size.
Leverage Table Construction : On the first bar, enabled leverage multiples are loaded into arrays with their corresponding weights calculated as the leverage value divided by 25, giving higher leverage multiples proportionally greater contract weight.
Long Liquidation Projection : On each bullish bar with volume, the liquidation price for each enabled leverage multiple is calculated as close multiplied by one minus one divided by leverage. Each price is snapped to its level band and the bar's volume multiplied by the leverage weight is added to the band's contract accumulation.
Short Liquidation Projection : On each bearish bar with volume, the liquidation price for each enabled leverage multiple is calculated as close multiplied by one plus one divided by leverage. Each price is snapped and weighted identically to the long projection process.
Band Deduplication : When projecting to a band that already exists in the active level array, contracts are added to the existing band rather than creating a duplicate, building cumulative pressure at each price level over time.
Sweep Removal : Long liquidation levels with their bottom boundary at or below the current bar's low are deleted and removed from the array. Short liquidation levels with their top boundary at or above the current bar's high are deleted, reflecting that those positions have already been liquidated.
Global Maximum Normalization : The maximum contract accumulation across all active long and short levels is calculated and used to normalize every level's contracts to a 0-1 range for thermal color assignment.
Thermal Color Assignment : Normalized values above 0.85 receive near-white coloring. Values between 0.65 and 0.85 gradient from yellow to white. Values between 0.35 and 0.65 gradient from the base color to yellow. Values below 0.35 graduate from a highly transparent base color to the full base color, producing a four-stage thermal effect that intensifies with concentration.
Sidebar Construction : On the last bar, the price range spanning the 200-bar high-low extended to cover all active level extremes is divided into the configured number of rows. Each active level's midpoint determines its bin assignment and its contracts are added to that bin's sum. Bins are drawn as horizontal bars proportional to their relative sum, colored by whether they sit below or above current price.
Peak Level Rendering : The sidebar bin with the maximum contract sum has a horizontal line drawn across the full visible range and a price label placed to the right, marking the single level of highest total liquidation pressure across all active levels.
Together, these elements form a continuously updating liquidation pressure landscape where the heatmap exposes per-level concentration and the sidebar summarizes the full distribution in a single compact view.
Interpretation
Leverage Pressure Map should be interpreted as a probabilistic liquidation pressure distribution tool rather than a precise order book representation:
Heatmap Bands (Long, Teal) : Horizontal bands below price representing estimated long position liquidation levels. These levels would trigger forced selling if price declines to them, potentially amplifying downside momentum.
Heatmap Bands (Short, Red) : Horizontal bands above price representing estimated short position liquidation levels. These levels would trigger forced buying if price rises to them, potentially amplifying upside momentum.
Thermal Intensity : Band color intensity reflects the relative concentration of estimated contracts at each level. Near-white bands represent the highest-pressure clusters. Yellow bands represent elevated but secondary concentrations. Dimmer base-colored bands represent lower-pressure background levels.
Band Density Near Price : Higher leverage multiples project their liquidation distances closer to price, producing denser band clustering near current price. Wider spacing further from price reflects the lower leverage multiples that require larger adverse moves to trigger liquidation.
Sidebar Distribution : The horizontal bar chart to the right of price summarizes total liquidation pressure at each price level across both long and short levels, providing an immediate overview of where the greatest cumulative exposure sits without analyzing individual heatmap bands.
Peak Level Line : The horizontal white line drawn across the chart at the sidebar's maximum-pressure bin marks the single most concentrated liquidation level across the entire active heatmap, representing the price at which the greatest estimated volume of leveraged positions would be forced to close.
Swept Levels : When price passes through a band, the band is removed from the display, reflecting that those positions have already been liquidated and no longer represent pending pressure.
Heatmap thermal intensity, peak level proximity to current price, and sidebar distribution shape collectively provide more information about leveraged market risk than any element in isolation.
Signal Logic & Visual Cues
Leverage Pressure Map does not generate discrete buy or sell signals. Instead it provides a continuous spatial representation of estimated liquidation pressure with two primary reference outputs:
Peak Level Line : The highest-concentration liquidation level across the full active heatmap, updated on every bar, marking where a price move is most likely to encounter cascading forced position closures.
Thermal Intensity Clusters : Near-white or yellow bands identify areas of elevated liquidation pressure that price is approaching, providing anticipatory context for potential momentum amplification or absorption events as price enters high-concentration zones.
The sidebar distribution provides a continuous summary reference for assessing whether liquidation pressure is concentrated near price or distributed across a wide range, informing both directional bias and risk management decisions.
Strategy Integration
Leverage Pressure Map fits within liquidity-aware and leveraged market structure approaches:
Liquidation Cascade Target Identification : Use high-intensity heatmap clusters as anticipatory targets for directional moves, particularly in leveraged crypto or futures markets where cascade events frequently drive price to liquidation cluster levels before reversing.
Peak Level Reference : Monitor the peak level line as a dynamic reference for the single highest-concentration liquidation zone. Directional moves approaching this level may accelerate as they trigger forced closures and then reverse sharply once the liquidation cascade exhausts.
Pressure Asymmetry Analysis : Compare the density and intensity of long liquidation bands below price against short liquidation bands above price using the sidebar distribution. Greater pressure on one side suggests a directional bias toward the path that would trigger the larger cascade.
Momentum Amplification Context : Use thermal cluster proximity as a context layer for evaluating whether a developing directional move is approaching a zone that would amplify momentum through forced closures or whether the path ahead is relatively clear of concentrated liquidation pressure.
Leverage Multiple Configuration : Configure leverage multiples to reflect the typical leverage profile of the target market. Crypto perpetual markets with common 100x and 50x usage benefit from the default configuration while futures markets with lower typical leverage may be better represented by adjusting multiples toward 20x, 10x, and 5x.
Multi-Timeframe Pressure Context : Apply the indicator on a higher timeframe to establish the broader liquidation pressure landscape while using a lower timeframe for entry timing, ensuring directional decisions are informed by the macro liquidation distribution rather than only the immediate price vicinity.
Technical Implementation Details
Projection Engine : Per-leverage close-derived liquidation price calculation with mintick-scaled band snapping and volume-weighted contract accumulation
Data Structure : Custom type array management for long and short level arrays with deduplication on existing band addresses
Sweep System : Per-bar directional price breach testing with immediate band deletion and array removal for swept levels
Thermal Color : Four-stage normalized gradient from transparent base through full base color to yellow to near-white
Sidebar : Last-bar price-range bin aggregation with proportional width bars and peak bin identification
Peak Level : Highest sidebar bin horizontal line with price label updated on every last bar render
Performance Profile : Configurable maximum level count per side with oldest level removal enforcing object count management
Optimal Application Parameters
Timeframe Guidance:
1 - 5 min : Intraday liquidation pressure mapping for scalping in high-leverage crypto markets with responsive level accumulation and fine level scale for precise cluster identification
15 - 60 min : Session-level pressure distribution monitoring with balanced level count and moderate scale for intraday cascade target identification
4H - Daily : Swing-level liquidation landscape mapping with higher level scale for broader band visibility across larger price ranges
Suggested Baseline Configuration:
Max Levels Per Side : 100
Level Scale : 50
Leverage 1 : 100
Leverage 2 : 50
Leverage 3 : 25
Leverage 4 : 10
Show Distribution : Enabled
Show Peak Level : Enabled
Sidebar Width : 20
Sidebar Rows : 75
These suggested parameters should be used as a baseline; their effectiveness depends on the typical leverage profile of the target market, instrument tick size, and preferred heatmap granularity, so fine-tuning is expected for optimal performance.
Parameter Calibration Notes
Use the following adjustments to refine behavior without altering the core logic:
Bands too thin to see : Increase Level Scale to produce taller bands that are more visible at normal zoom levels, accepting reduced price resolution in exchange for improved visual clarity.
Bands too thick and overlapping : Decrease Level Scale toward 10 for finer band resolution, producing a more precise pressure grid at the cost of reduced visual prominence per band.
Too many levels cluttering the chart : Reduce Max Levels Per Side to limit the number of active bands per direction, with the oldest levels removed first as the cap is enforced.
Heatmap not reflecting market's leverage profile : Adjust the four leverage multiples to match the typical leverage tiers used by participants in the target market. Setting a leverage multiple to zero disables that tier entirely.
Sidebar too narrow to read : Increase Sidebar Width to extend the maximum bar length of the distribution profile, making the relative pressure differences between price levels more visually distinguishable.
Sidebar resolution too coarse : Increase Sidebar Rows for finer price-level resolution in the distribution profile, producing more granular pressure mapping across the visible range.
Adjustments should be incremental and evaluated across multiple session types rather than isolated market conditions.
Performance Characteristics
High Effectiveness:
High-leverage perpetual crypto markets where 25x to 100x positions are common and liquidation cascade events regularly drive price to cluster levels before reversing
Futures markets with identifiable leverage tier participation where volume-weighted projection produces meaningful pressure estimates relative to actual open interest distribution
Momentum trading approaches where liquidation cluster proximity provides anticipatory context for potential acceleration or reversal around high-pressure zones
Risk management frameworks that benefit from understanding where cascading forced closures are most likely to amplify directional moves beyond fundamental price drivers
Reduced Effectiveness:
Spot-only markets without leverage participation where liquidation mechanics are absent and the projection model loses its theoretical basis
Low-volume instruments where volume-weighted contract estimates become unreliable due to thin and erratic participation
Markets with very low typical leverage where default leverage multiples project liquidation distances beyond the normal trading range, producing bands that are rarely relevant to near-term price action
Instruments with extreme tick sizes relative to their price where mintick-scaled band heights produce either excessively coarse or excessively granular level grids that do not align with meaningful price structure
Integration Guidelines
Confluence : Combine with BOSWaves order flow tools, structural indicators, or momentum oscillators to validate whether price approaching a high-intensity liquidation cluster is doing so with the participation and conviction needed to trigger a cascade
Peak Level Respect : Monitor price behavior approaching the peak level line as the highest-probability cascade trigger zone. Price reaching this level may accelerate sharply through it as cascading liquidations fire, then reverse once the forced closure sequence exhausts.
Pressure Side Awareness : Assess whether greater pressure sits above or below current price using the sidebar. A heavier distribution of short liquidation pressure above price suggests upside moves may be self-amplifying, while heavier long liquidation pressure below suggests downside moves may cascade further than directional indicators alone would imply.
Level Sweep Interpretation : When price sweeps through a concentration of bands and they are removed, interpret the clearing as a liquidation event having occurred. The subsequent behavior of price after clearing a major cluster is often directionally informative about whether the move was primarily liquidation-driven or backed by genuine directional conviction.
Model Limitations : This indicator estimates liquidation pressure from volume and price data and does not access exchange-level open interest, funding rates, or actual leveraged position data. All readings represent probabilistic estimates rather than verified exposure measurements and should be treated as context rather than precise quantitative inputs.
Disclaimer
Leverage Pressure Map is a professional-grade liquidation pressure estimation and visualization tool. It uses volume-weighted leverage projection with thermal heatmap rendering but does not access real exchange open interest data or actual leveraged position information. All liquidation level estimates are approximations derived from OHLCV data and configured leverage multiples. Results depend on market leverage profile, instrument volume characteristics, parameter selection, and disciplined execution. BOSWaves recommends deploying this indicator within a broader analytical framework that incorporates order flow context, structural analysis, and comprehensive risk management. Indicator

Crypto: Macro Heatmap [invincible3]Crypto Macro Heatmap is an automatic market-regime dashboard designed to summarize crypto macro conditions using liquidity, leverage, breadth, and risk-participation metrics.
The indicator converts multiple market data sources into normalized 0–100 scores and displays them in a structured heatmap table. It is built to help traders quickly understand whether the broader crypto environment is risk-on, neutral, or risk-off.
Main dashboard sections:
1. Liquidity
Tracks Global M2, total crypto market cap, USDT dominance, and BTC volume confirmation. Higher liquidity scores generally suggest stronger macro support for crypto markets.
2. Leverage
Tracks open interest pressure, funding-risk proxy, liquidation-risk proxy, and OI acceleration. Higher leverage scores mean higher stress or crowding risk.
3. Breadth
Tracks TOTAL2, TOTAL3, BTC dominance, ETH dominance, and altcoin participation. This section helps identify whether market strength is broad or concentrated.
Key features:
* Fully automatic scoring
* No manual market-score inputs
* Dashboard show/hide checkbox
* Light/dark chart theme detection
* Composite regime score
* Regime meter
* Market phase detection
* Risk-state classification
* Confidence score
* Section delta versus 7 days ago
* Fixed-width heatmap layout for cleaner visual alignment
The composite score combines liquidity support, market breadth, and leverage-adjusted risk into one regime reading. The dashboard is intended for macro context and regime analysis, not direct buy or sell signals.
Use this tool as a higher-timeframe market filter together with your own technical analysis, risk management, and trading system.
Disclaimer: This indicator is for educational and analytical purposes only. It does not provide financial advice. Always do your own research and manage risk carefully.
Indicator

Risk Controller | MouryaRisk Controller | Mourya - Complete Indicator Guide
Overview
Risk Controller | Mourya is an institutional-grade, real-time risk management matrix and position layout dashboard built directly onto your chart. Instead of forcing traders to context-switch between spreadsheets and their charting screen, this terminal brings complete mathematical clarity to active position-sizing, trailing stops, real-time tracking, and multi-tier target distributions. Designed for both professional execution and sleek workspace integration, it features absolute flexibility from pure cash or spot accounts to heavily leveraged derivative trades.
How to Use (Setup and Workflow)
* Apply the indicator to your chart and open the settings menu.
* Select your Position Type (Long or Short) and pick your preferred currency symbol from the dropdown menu.
* Enter the exact Quantity or Shares you are trading.
* Enter your Leverage multiplier. If you are using a standard spot or cash account without leverage, enter 0.
* Choose your Brokerage Fee type (Fixed Value or Percentage) and enter the corresponding fee amount so the dashboard can calculate your true net profits.
* Enter your total account balance into the Net Cash Available field to enable automatic account risk percentage tracking.
* Set your levels visually by clicking the price lines directly on your chart to wake up the TradingView drag handles, then drag your Entry, Stop Loss, and up to 4 Take Profit targets to your desired locations.
* If you prefer strict mathematical targets instead of dragging lines, type a value into the Percentage Overrides settings to automatically lock a Take Profit target to an exact asset percentage move.
* Customize your workspace by navigating to the Dashboard Settings to move the terminal to any corner of the screen, scale the overall size from tiny to huge, and select custom colors for the header background, header text, and chart lines.
* For a quick reset when scanning multiple tickers, open the settings menu, click the Defaults button in the bottom left corner, and select Reset Settings to wipe the board clean back to zero.
How it Works (Core Features)
* Interactive Chart Synchronization: Bypasses manual price typing by letting you drag and drop your target lines on the live chart. The dashboard matrix instantly recalculates all metrics the moment you release the line.
* Live P and L Tracking Module: A dedicated real-time row sits beneath your entry, constantly tracking your exact active Profit and Loss, tick distance, and live Return on Equity (ROE) as the market moves tick-by-tick.
* Trailing Stop Loss Support: The mathematical engine adapts instantly. If you drag your Stop Loss line past your Entry price into profit territory, the dashboard flips its internal logic, converting the red loss metrics into secured green profits.
* Percentage Overrides: Overrides your manual chart line placement, locking in exact percentage-based profit targets while keeping the Stop Loss manually adjustable.
* Dynamic Hide Logic: Automatically collapses and hides Take Profit rows 2, 3, and 4 on your dashboard if you leave their values at zero, keeping your screen clutter-free.
* Account Risk Diagnostics: Evaluates your Stop Loss distance against your Net Cash Available to show the exact percentage of your total account at risk. It also flashes a critical margin warning if your required margin exceeds your cash balance.
* Margin and Breakeven Engine: Identifies the actual cash margin required to open the position and calculates the exact asset price you need to hit to exit the trade at absolute zero after all entry and exit brokerage fees are deducted.
* True Return on Equity (ROE): Scales your return metrics accurately. If you input 0 leverage, it mirrors the raw asset movement. If you input leverage, it calculates the amplified return strictly on your invested margin.
* Risk-to-Reward (R:R) Tracking: Instantly evaluates the structural viability of your trade setup by calculating the ratio between your Stop Loss risk and Take Profit 1 potential.
* Wick-Sensitive Hit Engine: Mimics real broker limit fills by actively tracking live high and low wicks instead of waiting for a candle to close. The moment a price touches your Stop Loss or Take Profit, the dashboard row flashes in vivid solid colors (Institutional Green for TP, Red for SL) and the chart label flashes yellow.
* True Market Context Module: Calculates the exact percentage distance between the real-time live price and critical historical extremes. Includes today's High/Low, a mathematically pure 52-Week High/Low (calculated using exactly 252 trading days to account for weekends and holidays), and the All-Time High/Low.
* Context Toggles: Allows you to independently check or uncheck the Day, 52-Week, and All-Time context metrics to save screen space when you do not need them.
* Built-in Settings Tooltips: Every single input in the settings menu features an integrated guide next to the small info icon explaining its exact function and mathematical behavior. Indicator

Liquidation Cascade Risk Map [AGPro Series]Liquidation Cascade Risk Map
🧠 Core Idea
When leverage pressure builds, is the market entering a real cascade-risk zone, or is liquidation pressure already cooling?
📌 Overview / What it does
Liquidation Cascade Risk Map is a crypto derivatives analysis tool designed to visualize liquidation-cascade risk without pretending to know exact exchange liquidation levels.
The script evaluates open interest data when available, falls back to a transparent volume-proxy mode when needed, and combines volatility expansion, range pressure, candle body stress, directional movement, and distance from reference structure into a single cascade-risk context.
It produces a cascade pressure path, right-side state tags, event labels, optional pulse markers, and a compact AG Pro dashboard panel. It does not predict future price, automate entries, provide liquidation prices, or act as a guaranteed signal system.
🎯 Purpose & Design Philosophy
This script was built for traders who want to understand when a crypto market may be carrying unstable leverage pressure.
Many liquidation tools focus on exact levels, heatmaps, or speculative liquidation clusters. Those can be useful, but they often require external datasets and may create false certainty when used as chart overlays.
Liquidation Cascade Risk Map takes a different approach. It asks whether current market behavior has the ingredients of cascade vulnerability: expanding pressure, directional stress, range instability, aggressive bodies, and persistence.
⚡ Why This Script Is Different
Most tools focus on liquidation levels, estimated heatmap bands, or simple volatility alerts.
This script does NOT claim to know where every liquidation sits, and it does not draw exchange-style liquidation heatmaps.
Instead, it maps the quality of the surrounding cascade-risk environment. It highlights when the market is showing pressure that may support long-side cascade risk, short-side cascade risk, two-way cascade vulnerability, or cooling after a pressure build-up.
⚙️ Methodology
1. Context Detection
The script checks whether usable open interest data exists. If not, it can fall back to a volume-proxy model so the visual framework remains usable across more symbols.
2. Pressure Mapping
It evaluates data change, volatility shock, candle range pressure, body expansion, distance from reference structure, and directional movement.
3. Cascade Evaluation
Those components are blended into a cascade-risk score. The script then classifies the environment as Long Cascade Risk, Short Cascade Risk, Two-Way Cascade, Risk Cooling, Neutral Risk, or Data Missing.
4. Visual Output
The chart displays a cascade pressure path, a dotted center reference, a vertical pressure needle, right-side tags, event labels, and a panel that summarizes the active state.
🗺️ How to Read the Chart
The upper pressure rail represents elevated liquidation-cascade risk.
The lower pressure rail represents cooling or pressure release context.
The dotted centerline acts as the current reference path.
The vertical needle shows how stretched the active cascade-risk score is inside the pressure path.
Event labels identify important changes such as Long Cascade, Short Cascade, Two-Way Cascade, or Risk Cooling.
The panel summarizes state, score, data change, velocity, persistence, cooling, direction, grade, data mode, ATR shock, data source, and trend.
🚦 Signals & States
• Long Cascade Risk → downside pressure is elevated and long-side liquidation vulnerability may be rising
• Short Cascade Risk → upside pressure is elevated and short-side liquidation vulnerability may be rising
• Two-Way Cascade → volatility and pressure are elevated on both sides, suggesting unstable conditions
• Risk Cooling → cascade pressure is decreasing after a build-up
• Neutral Risk → no strong cascade-risk condition is currently active
• Data Missing → the selected data source is not usable on the current symbol or mode
🔔 Alerts Logic
Alerts can be enabled for Long Cascade Risk, Short Cascade Risk, Two-Way Cascade, and Risk Cooling.
Each alert triggers when the selected state becomes active. Alerts are designed as attention markers, not trade instructions.
🧩 Confluence Logic
The context becomes stronger when data expansion, volatility shock, range pressure, directional bias, and persistence align at the same time.
For example, high volatility with strong directional movement and rising pressure persistence may indicate a more unstable cascade-risk environment than volatility alone.
📊 When to Use
• Crypto perpetual futures
• High-volatility market phases
• Sharp directional moves
• Post-breakout acceleration
• Failed recovery or forced unwind environments
• Situations where leverage pressure may matter more than ordinary trend context
⚠️ When NOT to Use
• Very low liquidity symbols
• Symbols with unreliable volume or open interest data
• Extremely noisy low-timeframe charts
• Markets with abnormal gaps or data breaks
• Any situation where the user expects exact exchange liquidation prices
🎛️ Key Inputs
• Data Mode → chooses between automatic open interest, manual open interest symbol, or volume proxy
• Lookback Length → controls the normalization window for pressure scoring
• Fast / Slow Pressure Length → controls short-term and baseline pressure reaction
• Cascade Threshold → defines how demanding the script is before marking cascade-risk conditions
• Cooling Threshold → controls when pressure is considered to be cooling
• Persistence Bars → measures whether pressure is sustained or only momentary
• Visual settings → control labels, pulse markers, path visibility, panel layout, and font sizes
🖥️ Interface & Visual Design
The interface is built to make the chart readable at first glance.
The cascade path is intentionally not a large boxed zone. It is a pressure-path structure designed to remain visually distinct from corridor, ladder, and basis-style scripts.
The panel uses a merged AG Pro header row, compact metrics, and a dark professional layout. Visual elements avoid white or pale primary treatments so the script remains readable on both dark and light TradingView chart backgrounds.
🧪 Practical Usage Workflow
1. Read the panel state first.
2. Check whether Data Mode shows real open interest or volume proxy.
3. Look at the cascade pressure path and current needle position.
4. Check event labels for recent pressure build-up or cooling.
5. Compare the state with broader trend, volatility, and market structure.
🔍 Interpretation Guidelines
Do not treat a cascade-risk state as a direct entry or exit signal.
Use it as a context layer. The script is most useful when combined with structure, liquidity, volatility, market regime, and risk management.
Rising cascade risk can mean the market is becoming unstable. Cooling can mean pressure is easing, but it does not guarantee reversal or continuation.
🚫 What This Script Is NOT
This script is not a prediction engine.
It is not financial advice.
It is not an automated trading system.
It does not calculate exact liquidation prices.
It does not guarantee that a liquidation cascade will happen.
⚠️ Limitations & Transparency
Open interest availability depends on symbol, exchange, and TradingView data support.
Volume proxy mode is only a proxy. It can help visualize pressure context, but it is not the same as real open interest.
Different timeframes may produce different readings.
Fast markets, illiquid symbols, gaps, and abnormal candles can affect outputs.
🧠 Market Context Notes
Liquidation pressure is often connected to leverage, volatility, liquidity, and forced positioning.
This script focuses on context quality rather than exact liquidation geography. That makes it useful as a decision-support layer, but it should always be interpreted with broader market evidence.
🧾 Use Case Examples
When price accelerates downward while pressure score and persistence rise, the chart may show Long Cascade Risk.
When price squeezes upward with high pressure and volatility expansion, the chart may show Short Cascade Risk.
When volatility and pressure expand without clean directional separation, the chart may show Two-Way Cascade.
When pressure falls after a build-up, the chart may show Risk Cooling.
🧱 System Philosophy
AGProLabs scripts are built as structured decision-support tools.
The goal is not to make the chart louder. The goal is to make hidden market context easier to read, compare, and question.
🔐 Non-Promise Statement
No script can remove uncertainty.
No state should be treated as certainty.
No visual element should replace trader judgment.
📉 Risk Disclosure
Trading involves risk.
Crypto derivatives and leveraged markets can be especially volatile.
This script is for educational and analytical purposes only.
Nothing in this script should be interpreted as financial advice, investment advice, or a guarantee of outcome.
Users remain fully responsible for their own decisions.
📚 Educational Note
Use this script to study how pressure, volatility, persistence, and directional stress interact before and after unstable crypto market moves.
Indicator

Leverage Reset Quality Map [AGPro Series]Leverage Reset Quality Map
🧠 Core Idea
Did leverage actually reset, or did the market only pause before risk rebuilt again?
📌 Overview / What it does
Leverage Reset Quality Map is a crypto derivatives context tool designed to evaluate whether a leverage washout is developing into a cleaner reset, a fragile reset, a crowded stress condition, or a reload-risk environment.
The script combines open interest when available, a transparent volume-proxy fallback, data-change behavior, volatility shock, range expansion, wick flush behavior, recovery quality, persistence, and trend context. It converts those inputs into a reset-quality ladder, compact state labels, right-side tags, pulse markers, alerts, and an AG Pro dashboard.
It does not liquidate positions, predict future price direction, automate entries, or claim that a reset must lead to a reversal. It is an analytical map for reading whether leverage pressure appears to be clearing, rebuilding, or remaining unstable.
🎯 Purpose & Design Philosophy
This script was built for traders who want to separate a true leverage reset from a simple bounce, pause, or noisy reaction.
After sharp moves, many markets look relieved for a short period. The important question is whether participation pressure cooled, volatility stabilized, and price recovered with acceptable structure. Leverage Reset Quality Map turns that question into a visible workflow.
The design philosophy is simple: a reset is not automatically bullish or bearish. A reset is a context condition. Its quality depends on stress release, recovery quality, volatility behavior, and whether participation starts rebuilding too early.
⚡ Why This Script Is Different
Most tools focus on liquidation levels, open interest changes, or raw volume spikes.
This script does NOT draw another liquidation heatmap, does NOT treat every OI drop as bullish, and does NOT mark every volume spike as meaningful leverage cleansing.
Instead, it evaluates reset quality as a multi-factor condition. It asks whether stress is building, whether pressure is releasing, whether the market is recovering cleanly, and whether leverage-style participation is reloading before the reset matures.
⚙️ Methodology
1. Context Detection
The script reads official open interest when available. If official OI is unavailable and fallback is enabled, it uses volume as a transparent leverage-participation proxy.
2. Stress Mapping
It evaluates data-change pressure, velocity, volatility shock, range shock, and wick flush behavior to estimate whether leverage-style stress is present.
3. Reset Quality Evaluation
It measures participation contraction, volatility cooling, price recovery, wick recovery, and trend context to estimate reset quality.
4. Visual Output
The output is displayed as a reset-quality ladder with state, quality, reload risk, event labels, compact pulse markers, reaction tracks, and a dashboard panel.
🗺️ How to Read the Chart
The reset-quality ladder is the main visual object.
The upper step represents the current reset or stress state.
The middle step represents reset quality.
The lower step represents reload risk.
The vertical needle shows where current reset quality sits inside the ladder.
Labels mark state transitions such as Clean Reset, Fragile Reset, Reload Risk, and Stress Build.
Compact pulse markers add context:
• R = Clean Reset pulse
• F = Fragile Reset pulse
• L = Reload Risk pulse
• S = Stress Build pulse
Colors communicate context:
• Teal = cleaner reset pressure
• Yellow = fragile or incomplete reset
• Pink = reload or stress risk
• Indigo = neutral reset-quality structure
The panel summarizes state, reset quality, data change, stress score, persistence, reload score, direction, grade, data mode, volatility shock, OI source, and trend.
🚦 Signals & States
• Clean Reset → stress release and recovery quality are improving
• Fragile Reset → some reset behavior is visible, but quality remains incomplete
• Reload Risk → participation may be rebuilding before the reset is healthy
• Crowded Stress → leverage-style pressure is building without a clean reset
• Neutral Reset → no active reset state dominates the current read
• Data Missing → official OI and fallback data are not available
🔔 Alerts Logic
Alerts trigger when the script transitions into selected reset-quality states.
Clean Reset alerts mark improving reset quality.
Fragile Reset alerts mark incomplete reset conditions.
Reload Risk alerts mark renewed leverage-style participation before quality improves.
Stress Build alerts mark stress expansion without a clean reset read.
Alerts are attention markers, not trade instructions.
🧩 Confluence Logic
The strongest context appears when several components align:
Participation contraction + volatility cooling + wick recovery + price recovery + improving reset quality.
The weakest context appears when participation expands again, volatility stays hot, and reset quality remains low.
📊 When to Use
• Crypto perpetual and futures charts
• Post-selloff or post-squeeze environments
• High-volatility reactions
• Open interest or volume-pressure analysis
• Markets where leverage reset quality matters more than a raw signal
⚠️ When NOT to Use
• Extremely illiquid symbols
• Markets with unreliable open interest or volume data
• Very low-volatility sideways charts where leverage pressure is not active
• News-driven gaps where normal reset logic may be distorted
• Any situation where the user expects a direct buy or sell signal
🎛️ Key Inputs
• Data Mode → selects official OI, manual OI, or volume-proxy behavior
• Manual Open Interest Symbol → lets the user define a specific OI source
• Context Lookback → controls the normalization window
• Fast Reaction Length → controls the short-term recovery track
• Slow Baseline Length → controls the slower reset baseline
• Minimum Stress Score → controls how much pressure is required for stress states
• Minimum Quality Score → controls how much recovery quality is required for a clean reset
• Event Label Cooldown → controls label spacing and visual density
• Panel / label settings → control visual layout and readability
🖥️ Interface & Visual Design
The interface is designed to feel different from zone-first or corridor-first tools.
Instead of drawing a large boxed area, the script uses a staggered reset-quality ladder. This keeps the chart readable on both dark and light TradingView backgrounds and reduces the risk of looking like a duplicate of nearby derivatives tools.
The panel uses a merged blue AG Pro header row and a compact information hierarchy.
🧪 Practical Usage Workflow
1. Read the panel state.
2. Check whether data mode is Open Interest or Volume Proxy.
3. Look at the reset-quality ladder.
4. Compare reset quality with reload risk.
5. Review recent event labels and pulse markers.
6. Confirm the broader chart structure.
🔍 Interpretation Guidelines
A Clean Reset does not mean price must rise.
A Reload Risk state does not mean price must fall.
The script is designed to help users think in terms of leverage pressure, reset quality, and context alignment. It should be interpreted with broader structure, liquidity, trend, and risk controls.
🚫 What This Script Is NOT
This script is not a prediction engine.
It is not financial advice.
It is not an auto-trading system.
It is not a liquidation heatmap.
It does not guarantee reversals, continuations, entries, exits, or outcomes.
⚠️ Limitations & Transparency
Open interest availability depends on the symbol, exchange, and TradingView data support.
When official OI is unavailable, the script can use volume as a transparent proxy. A proxy is not the same as official open interest.
Timeframe differences may change how reset quality appears.
Volatility spikes, exchange-specific behavior, and sudden news events may distort the read.
🧠 Market Context Notes
Leverage resets often appear after forced movement, sharp volatility expansion, wick-heavy reactions, or participation contraction.
The important distinction is whether the reset becomes cleaner or whether risk reloads before the market has stabilized.
This script focuses on that distinction.
🧾 Use Case Examples
When price flushes lower, participation contracts, volatility cools, and price recovers toward the reaction track, the script may show Clean Reset.
When a market bounces but participation expands again while reset quality remains weak, the script may show Reload Risk.
When volatility remains hot and stress score remains elevated, the script may show Crowded Stress.
🧱 System Philosophy
Leverage Reset Quality Map follows the AGProLabs principle of building decision-support maps rather than prediction tools.
The goal is to make hidden market conditions easier to observe, compare, and interpret without overclaiming certainty.
🔐 Non-Promise Statement
No script can know future price direction.
No state should be treated as certainty.
Every output should be interpreted as context, not as an instruction.
📉 Risk Disclosure
Trading involves risk.
Crypto derivatives can be highly volatile and may involve leverage, liquidation risk, exchange risk, data limitations, and rapid market movement.
Users remain fully responsible for their own decisions.
This script does not provide financial advice.
📚 Educational Note
This script is intended for educational, analytical, and visual market-structure study.
Its value comes from helping users ask better questions about leverage pressure, reset quality, and risk rebuilding.
Indicator

Live Position Tracker Leverage CalculatorLive Position Tracker Leverage Calculator
A leverage and position calculator that lives on your chart. Set your entry candle, entry price, take profit, and stop loss with a few clicks and get an instant visual breakdown of the trade — risk, reward, liquidation distance, breakeven, and live PnL — all anchored to the actual candle you entered on.
Unlike static calculator widgets, this tool tracks your trade from entry to exit. It records the best and worst points your position reached, counts how many bars you've held, and freezes everything when the trade closes so you have a clean snapshot of how it played out.
WHAT GETS PLOTTED ON THE CHART
· Entry, Take Profit, and Stop Loss lines anchored from your entry candle forward
· Liquidation price line (calculated from your leverage and maintenance margin)
· Breakeven line (entry adjusted for fees)
· Filled zones between entry/TP (green) and entry/SL (red)
· Best Point and Worst Point markers showing the maximum favorable and adverse excursion the trade reached
· Live PnL label that updates with current price
WHAT'S IN THE INFO PANEL
· Position: capital, notional, quantity, maintenance margin, fee rate
· Outcomes: live PnL, projected PnL at TP, projected loss at SL, risk-to-reward ratio
· Liquidation: liquidation price, distance to liquidation, round-trip fees
· Trade history: bars in trade, best point reached, worst point reached
· Status: pending entry, active, target hit, stop hit, or liquidated
KEY FEATURES
· Click-to-set workflow: TradingView prompts you to click the entry candle, entry price, TP, and SL when you add the indicator
· Auto direction detection from your TP and SL placement (or manually force Long/Short)
· Liquidation calculator with adjustable maintenance margin (works for any exchange — set the value from your exchange's tier table)
· Sanity warnings: flags when stop loss is past the liquidation price, or when TP/SL are on the wrong side of entry
· Trade tracking freezes the moment any exit (TP/SL/liquidation) is hit, giving you a clean post-trade snapshot
· Three independent color systems: on-chart tag colors, Live PnL label colors, and panel theme — each customizable without affecting the others
· Customizable line widths, label colors, font color, and panel theme (dark, light, or fully custom)
· Adjustable label offsets and stagger so the chart never gets cluttered regardless of timeframe or symbol
· Alerts for TP, SL, liquidation, and breakeven crossings
MAINTENANCE MARGIN REFERENCE
Maintenance margin (MMR) is the minimum equity percentage required to keep your leveraged position open. The default 0.5% is roughly accurate for BTC/ETH on major exchanges, but real values vary:
· BTC/ETH majors: 0.4 – 0.5%
· Top 20 alts: 0.5 – 1.0%
· Mid-cap alts: 1.0 – 2.5%
· Low-cap and meme coins: 2.5%+
For accurate liquidation calculations, find your exchange's exact MMR for your symbol and position size.
NOTES
The liquidation price is a simplified isolated-margin approximation and does not account for tiered margin requirements at different position sizes. Always verify against your exchange's actual liquidation calculator before sizing real positions.
This tool calculates risk-to-reward as the gross price-distance ratio (matching TradingView's built-in long/short position tool). The fee-adjusted dollar amounts are shown separately in the "If TP Hit" and "If SL Hit" rows.
Indicator

Volatility Managed Kelly LeverageThe Volatility Managed Kelly Leverage (VMKL) indicator is a tool that dynamically adjusts position sizing based on forecasted market volatility. It helps you to optimize leverage exposure by systematically reducing risk during high volatility periods and increasing exposure when markets are calm.
VMKL adapts in real-time to changing market conditions, potentially generating alpha while smoothing volatility and reducing maximum drawdown.
This indicator implements the Optimal Volatility Plus Mean Strategy (OVPMS) from one of my favorite leverage papers:
" Alpha Generation and Risk Smoothing using Managed Volatility " by Tony Cooper (2010)
These are the key findings from the paper, which this indicator translates to real life:
Volatility is predictable while returns are not
Dynamic leverage based on volatility forecasts can generate significant excess returns
The strategy reduces volatility of volatility (vovo), kurtosis, and maximum drawdown
Tested on 125+ years of market data across multiple global indices
The OVPMS strategy (translated into this indicator) returned 12.6% annual return vs 7.0% for buy-and-hold, with the same volatility as the underlying index. Outstanding.
The indicator calculates optimal leverage using a three-step process
1. Volatility Forecasting
Uses Exponential Weighted Moving Average (EWMA):
σ²(t) = λ·σ²(t-1) + (1-λ)·r²(t-1)
This predicts next-day volatility from recent price movements
2. Return Prediction
Expected Return = a × σ^(b+1)
Where:
a = Power coefficient (baseline return, default: 0.10)
b = Power exponent (return-volatility relationship, default: -1.76 for SPY)
σ = Forecasted volatility
The negative exponent means returns decrease as volatility increases - a well-documented market behaviour.
3. Optimal Leverage Calculation
Full Kelly Leverage = μ / σ²
Actual Leverage = Full Kelly × Kelly Fraction × Caps × Smoothing
The Kelly Criterion provides the theoretically optimal leverage, which is then reduced via:
Kelly Fraction: Safety margin (default 75% = three-quarter Kelly)
Leverage Caps: Hard maximum and minimum limits
Smoothing: SMA to reduce rebalancing frequency
The Core Insight: Volatility varies over time (volatility of volatility), and this variation is costly. By targeting consistent volatility through dynamic leverage:
Reduces volatility drag - Compounding works better with stable volatility
Reduces drawdowns - Automatically deleverages before crashes
Reduces kurtosis - Fewer extreme return events
Generates alpha - Exploits the return-volatility relationship
The indicator calculates optimal leverage in real-time using EWMA volatility forecasting and Kelly Criterion mathematics, automatically detecting market regimes from CASH to VERY AGGRESSIVE and respective leverages. The statistics table shows Full Kelly leverage, Kelly Fraction leverage, forecasted volatility, predicted returns, and current regime.
Settings Guide
Please check the informational "i" in setting to get a lot more info.
You can also use preset configurations:
Conservative (Safe)
Kelly Fraction: 0.50
Max Leverage: 2.0x
Lambda: 0.97
Sensitivity: Enhanced
Moderate (Balanced) ⭐ DEFAULT
Kelly Fraction: 0.75
Max Leverage: 3.0x
Lambda: 0.94
Sensitivity: Enhanced
Aggressive (Maximum)
Kelly Fraction: 1.0
Max Leverage: 5.0x
Lambda: 0.90
Sensitivity: Standard
Paper Replication (Academic)
Kelly Fraction: 1.0
Max Leverage: 3.0x
Lambda: 0.94
Sensitivity: Standard
Adaptive: ON
Smoothing: 1
Remember: LEVERAGE MAGNIFIES BOTH GAINS AND LOSSES
Let me know if you have questions!
By Henrique Centieiro Indicator

Xer0's Dual Engine Ladder AllocatorOverview
This indicator is designed for long-term investors using a "Dual Engine" portfolio strategy on M1 Finance — mixing a broad-market index fund with a leveraged counterpart in the same Pie. Instead of guessing when to buy the dip, this script provides a systematic, step-by-step roadmap for increasing your leveraged allocation as the market falls, and resetting it as the market recovers.
How It Works
The strategy is built on "Sticky All-Time High" logic. It tracks the highest close price and calculates the current drawdown from that peak, then responds with one of three scenarios:
Ladder Down (Risk On): For every defined drop step (e.g. every -5%), the indicator signals a RISK UP event — automatically calculating your new target allocation to the leveraged slice of your Pie. This forces systematic, disciplined buying at lower prices.
Recovery Reset (Risk Off): Once the market recovers by a set percentage from the bottom, the script signals a RESET — returning your allocation to the base level and locking in the gains from the dip-buying phase.
Bull Step: When the market pushes into new high territory, the script tracks each new leg up and keeps your reference point current.
Key Features
Sticky ATH Tracking: Automatically calculates true drawdown from the cycle peak
Customizable Ladder Steps: Define your own drop trigger percentage and leverage increase per step
Max Cap: Hard ceiling on leverage exposure to protect against catastrophic drawdowns
Bar Confirmation: All signals fire on daily close to avoid intraday false triggers
Visual Dashboard: Bottom-right table showing current mode, target leverage, drawdown, and recovery price target
Alert Conditions: Built-in RISK UP and RESET alerts compatible with TradingView's "Once Per Bar Close" setting
Backtested Performance (Simulated — Read Carefully)
The following results are from a Python backtest covering approximately 30 years (1996–2026), using $923/week in contributions every Friday. The strategy used two M1 Pies: Pie 1 (S&P 500 index fund / 3× S&P 500 ETF, base leverage 35%) and Pie 2 (Nasdaq-100 index fund / 3× Nasdaq-100 ETF, base leverage 25%). Tax assumptions reflect California state + federal rates for a $47K–$100K income bracket. Data prior to 2010 is synthetic, modeled from underlying index returns.
Results are hypothetical and do not represent actual trading. Past performance does not guarantee future results.
Ladder Strategy | VOO Benchmark
Total Contributed $1,395,576 | $1,395,576
Final Value (after-tax) $25,286,879 | $9,025,443
Total Return 1,711.9% | 546.7%
CAGR (on contributions) 10.1% | 6.4%
Max Drawdown -91.8% | -50.5%
Taxes Paid (CA) $5,358,907 | N/A (buy & hold)
Cash After Full Liquidation $23,500,189 | $7,171,385
The ladder strategy produced approximately 227.7% more after-tax cash than buy-and-hold VOO after full liquidation. However, the strategy experienced a maximum drawdown of -91.8% — meaning at its worst point, the portfolio lost nearly all of its value on paper. This level of volatility is not suitable for most investors and requires strong conviction and a long time horizon to hold through.
How to Use
Add this indicator to a Daily (1D) chart of your chosen index. Configure the inputs to match your risk tolerance — Base Leverage %, Drop Step %, and Max Cap %. Enter your M1 Pie name in the input field so alerts reference it by name. Set alerts using "Once Per Bar Close" and adjust your Pie allocation whenever a signal fires.
Disclaimer
This script is for informational and educational purposes only. It does not constitute financial advice. Backtested results are simulated and hypothetical — they do not account for all real-world frictions and should not be interpreted as a guarantee of future performance. Trading leveraged instruments involves significant risk, including the potential loss of your entire investment, and is not suitable for all investors. Indicator

Kelly Criterion CurveThe Kelly Criterion Curve indicator gives you the leverage/return tradeoff by displaying a bell curve with growth and leverage. This indicator shows where you are on the risk curve depending your allocation/leverage used and the optimal leverage to use in any asset.
What Does It Show?
The indicator plots the Kelly growth function:
g(f) = μ·f - 0.5·σ²·f²
Where:
g(f) = Expected growth rate at leverage f
μ = Annualized return
σ = Annualized volatility
f = Leverage multiplier
The curve peaks at the Optimal Kelly leverage (full Kelly) and then declines, showing that:
Too little leverage = underutilized capital
Too much leverage = volatility drag destroys returns
The curve is dynamically divided into zones based on your asset's return profile:
Underinvesting (Green) - Too conservative, underutilized capital
Optimal Sizing (Teal) - Sweet spot for position sizing
High Risk (Yellow) - Diminishing returns, high volatility drag
Never Logical (Red) - Risk outweighs reward
Suicidal (Black) - Negative expected returns
Position Markers
★ Kelly Optimal (Green/Red) - Maximum long-term log growth leverage
½ Kelly (Yellow) - Conservative sizing (recommended most times)
Settings for Kelly Calculation
Lookback Period - Historical data window for calculations (default: 252 = 1 year)
Annual Trading Days - For annualization (default: 252)
Use Log Returns - More accurate for compounding (recommended: ON)
Curve Smoothness (20-200) - Number of points on curve (default: 100)
Maximum Leverage Display (2-10x) - X-axis range
Show Short Positions - Display negative leverage for short strategies. Note the chart is not fully optimized for shorts.
Show Optimal Kelly Marker - Mark optimal leverage on curve
Show Half Kelly Marker - Mark conservative leverage
How to Use
Look at Optimal Kelly - This is the theoretical maximum for the period analyzed
Use Half Kelly for conservative sizing
Check which risk zone your position falls into
If your leverage is in the High Risk zone → Consider reducing
If you're in Never Logical or Suicidal → I wish you good luck because you will need a lot
If you're in Underinvesting → You may be too conservative
IMPORTANT
The indicator is based on past returns and volatility. It CANNOT predict:
Market crashes
Regime changes
Black swan events
If you use Optimal Kelly and suddenly there's a crash, you are toasted.
Full Kelly maximizes long-term growth but can experience large drawdowns
Most traders use ¼ to ½ Kelly for risk management
You should almost never use full Kelly, unless you are extremely confident
Remember leverage amplifies gains and losses
Notice how Max Growth isn't simply Ann. Return × Leverage
The formula accounts for volatility drag (the cost of using leverage)
Higher volatility = lower optimal leverage
The Kelly Criterion was developed by John L. Kelly Jr. in 1956 for information theory and later adapted for gambling (card counting for example, pioneered by Edward O. Thorp), and investing.
Optimal Leverage:
f* = μ / σ²
Expected Growth Function:
g(f) = μ·f - 0.5·σ²·f²
This is a quadratic function that forms the bell curve you see on the chart.
This indicator pairs perfectly with my other indicators:
Kelly Optimal Leverage Indicator
Jensen's Inequality + Kelly Leverage
Multi-Leverage VAR/VaG Indicator
For deeper insights on Kelly Criterion and optimal leverage:
Read my article: Unlock the Power of Monte Carlo
Read these papers:
Alpha Generation and Risk Smoothing using Managed
Volatility
Leverage for the Long Run - A Systematic Approach to Managing Risk and Magnifying Returns in Stocks
Trading with leverage involves substantial risk of loss.
The Kelly Criterion provides a theoretical framework - actual trading requires additional risk management, market analysis, and psychological discipline.
Some examples of using the Kelly Criterion Curve:
Russel 2000, last 500 days Kelly curve
Here's you can see that the optimal sizing over the last 500 days would have been around 1.7x leverage and that full Kelly is 3.4x leverage.
While Russel 2000 returned 16%, full Kelly would have returned 27.8%, and more that full Kelly (3.4x leverage) would lower the returns.
Berkshire Hathaway, last 1000 days Kelly curve
BRK stock optimal Kelly (full Kelly) is 2.5x for the last 1000 trading days. To reduce volatility, one could use 1/2 Kelly which is 1.25x leverage.
Bitcoin, last 2000 trading days Kelly curve
Very interestingly, the indicator tells us not to leverage Bitcoin. Even a 2x leverage can lead to ruin given its volatility, and in fact, in 2025 many traders got liquidated while leveraging Bitcoin by 2x.
Let me know if you have questions, suggestions and comments.
- Henrique Centieiro Indicator

Indicator

Indicator

Indicator

Multi-Leverage VAR/VaG IndicatorHere's why I developed this indicator: I love leverage but most people don't use leverage correctly. This indicator helps you understanding whether leverage is advantageous and how much should be used.
Standard VAR calculations assume linear scaling (2x leverage = 2x risk), which is wrong for leveraged ETFs. Also, most VaR indicators show risk without comparing it to potential reward. This one tells you how do you quantify whether current market conditions are friendly or hostile to leveraged positions?
To do this, we calculate both the downside risk (VAR), upside potential (VaG), and their relationship across different leverage levels.
PROBLEMS THIS INDICATOR SOLVES
THE LEVERAGE SCALING FALLACY
Problem: Traders assume 3x leverage means 3x the risk.
Reality: Due to volatility decay and daily rebalancing, leveraged ETFs don't scale linearly. A 3x ETF can lose MORE than 3x in high downside volatility markets or LESS than 3x during up trending markets.
Solution: This indicator simulates actual leveraged ETF mechanics by applying leverage to each daily return and compounding over your holding period.
THE REGIME BLINDNESS PROBLEM
Problem: Traders use the same leverage in all market conditions.
Reality: Trending, low-volatility markets favor leverage. Choppy, high-volatility markets penalize leverage through volatility drag.
Solution: The VaG/|VAR| ratio quantifies leverage efficiency. When the leverage VaG/|VAR| is higher than the 1x VaG/|VAR|, then leverage is friendly .
THE RISK-WITHOUT-CONTEXT PROBLEM
Problem: Knowing your maximum loss doesn't tell you if that risk is worth taking.
Reality: A -10% VAR might be acceptable if VaG is +30%, but terrible if VaG is only +8%.
Solution: I calculate both downside and upside at the same confidence level for complete risk/reward context.
HOW THIS INDICATOR IS USEFUL TO INVESTORS
Determine optimal leverage level for current market conditions
Identify when to scale up or reduce leveraged positions based on regime changes
Calculate dollar risk on any account size for proper position sizing
Understand true risk of leveraged ETFs beyond the "3x" label
Detect transitions between leverage-friendly and leverage-hostile regimes
CORE METHODOLOGY: Historical simulation with daily rebalancing
Unlike parametric VAR (assumes normal distribution) or Monte Carlo (generates synthetic scenarios), this uses historical simulation - what actually happened in the past.
Calculate daily returns from closing prices
Simulate leveraged ETF behavior with daily rebalancing - apply leverage to each daily return, compound over the holding period, and cap losses at -100% (ETFs can't go negative)
Create a distribution by sliding the holding period window across the lookback period (252-day lookback with 21-day holding = 232 scenarios)
Sort all outcomes and extract percentiles: VAR = lower tail (e.g., 5th percentile at 95% confidence), VaG = upper tail (e.g., 95th percentile)
Calculate efficiency ratio: VaG / |VAR|
This tells you: for every dollar of downside risk, how many dollars of upside potential do you get?
HOW TO USE THIS INDICATOR
Lookback Period (default: 252 days) - Longer = more data but slower to adapt; Shorter = more responsive but less reliable
Holding Period (default: 21 days) - Match to your timeframe: 5-10 days (day traders), 21-42 days (swing traders), 63-126 days (position traders)
Confidence Level (default: 95%) - 90% for typical outcomes, 95% for balanced view, 99% for extreme tail risk
Leverage Levels (default: 1x, 2x, 3x) - Customize to your trading, supports decimals like 1.5x
INTERPRETING THE TABLE:
Lev = Leverage multiplier
VAR (%) = Maximum expected loss over holding period
VaG (%) = Minimum expected gain over holding period
VaG/|VAR| = Leverage efficiency ratio
VAR on $10k = Dollar loss on $10,000 position
EXAMPLE INTERPRETATION
This QQQ chart demonstrates the indicator's power to identify leverage regimes.
Current metrics (table):
1x: VAR -3.21%, VaG +21.58%, Ratio 6.73
2x: VAR -6.79%, VaG +46.58%, Ratio 6.86
3x: VAR -10.71%, VaG +75.26%, Ratio 7.02
This means:
Ratios above 6.5 are outstanding - upside is nearly 7x the downside at all leverage levels
Backwardation pattern: the ratio IMPROVES with more leverage (6.73 → 7.02), indicating strong trending conditions favor higher leverage
VAR remains very manageable even at 3x (-10.71% on a 55-day hold)
At 3x leverage, you risk $1,071 to potentially gain $7,526 on $10k - exceptional risk/reward. And understanding risk/reward is one of the most important points here.
Trade smart. Manage risk. Know your regime.
And let me know if you have any questions or suggestions.
- Henrique Centieiro Indicator

Risk AwarenessRisk Awareness - Liquidation Level Indicator
A clean, professional tool for displaying liquidation prices on leveraged positions. Designed for traders who need instant visibility of their risk levels without chart clutter.
KEY FEATURES
Real-time liquidation price calculation for long and short positions
Adjustable leverage from 1x to 200x
Fire engine red (long) and lime green (short) color-coded levels
Two label modes: Compact (minimal) and Detailed (full info)
Horizontal lines extending left from current price
Optional P&L tracking and display
Background alerts when approaching liquidation
Customizable maintenance margin and liquidation fee parameters
HOW IT WORKS
The indicator calculates liquidation prices using the standard formula:
Long Liquidation = Entry Price x (1 - 1/Leverage - Liquidation Fee + Maintenance Margin)
Short Liquidation = Entry Price x (1 + 1/Leverage + Liquidation Fee - Maintenance Margin)
Default parameters (0.5% maintenance margin, 0.5% liquidation fee) are calibrated for major crypto futures exchanges like Binance, Bybit, and OKX.
DISPLAY MODES
Compact Mode: Shows only leverage and price (e.g., "40x: 48750.00")
Detailed Mode: Shows full information including percentage distance and optional P&L
CUSTOMIZATION OPTIONS
Position Settings: Adjust leverage, toggle long/short, select entry price source
Custom Parameters: Fine-tune maintenance margin and liquidation fee for your specific exchange
Visual Settings: Colors, line width, label size, historical bands, disclaimer display
Alert Settings: Set distance threshold for liquidation warnings
Risk Management: Track unrealized P&L based on position size
ALERTS
Built-in alert conditions for:
Price crossing liquidation levels
Approaching liquidation threshold
Critical loss levels (50%+)
IMPORTANT DISCLAIMER
This indicator provides ESTIMATED liquidation levels for Tier 1 positions (small to medium size). Actual liquidation prices may vary due to:
- Position size tiers (larger positions = higher maintenance margins)
- Accumulated funding rates
- Market volatility and order book depth
- Cross margin vs isolated margin mode
- Exchange-specific liquidation engines
Always verify liquidation prices on your exchange platform before trading. This tool is for educational and risk awareness purposes only.
IDEAL FOR
Crypto futures traders on Binance, Bybit, OKX, and similar platforms
Day traders managing leveraged positions
Swing traders monitoring overnight risk
Anyone trading with leverage who needs clear visual risk management
PRO TIPS
Use Compact mode with Tiny/Small label size for minimal chart clutter
Enable the Info Table for detailed metrics when needed
Set Alert Distance to 1-2% for advance warning before liquidation
Toggle "Show Historical Bands" OFF (default) for cleaner charts
Adjust Custom Parameters if trading on exchanges with different fee structures
Stay aware. Trade smart. Manage your risk. Indicator

Jensen's Inequality + Kelly LeverageThis indicator reveals how volatility drag erodes returns through Jensen's Inequality and calculates scientifically optimal leverage levels using the Kelly Criterion. It answers the question: "At what leverage does volatility drag destroy more returns than leverage creates?"
I have created other indicators related to optimal leverage, Kelly Criterion and Jensen's inequality which you can fin in the comments.
Understand Jensen's Inequality
Jensen's Inequality is a theorem stating that for concave functions (like logarithms or sad face), the expected value of the function is less than the function of the expected value:
E ≤ log(1+E )
What this means for investors is that your realized geometric return (what you actually earn through compounding) is always less than your arithmetic average return. This gap is called volatility drag.
The drag formula: Drag = L² × σ² / 2
The quadratic term (L²) is crucial because if you double your leverage, quadruple your drag. This helps us to understand how much leverage we can take during volatile times (for example leveraged ETFs).
Understand Kelly Criterion
The Kelly Criterion, developed by John Kelly at Bell Labs in 1956, calculates the optimal bet size (or leverage) that maximizes long-term logarithmic growth of wealth:
Kelly = (μ - r_f) / σ²
Where:
μ = arithmetic return (expected return)
r_f = risk-free rate
σ² = variance (volatility squared)
Kelly tells you the exact leverage that balances return amplification against volatility drag to maximize your long-term compound growth rate.
Why I Combine Both?
Jensen's Inequality explains why leverage has, after a certain point, diminishing returns and eventually becomes destructive. Volatility drag grows faster than return amplification. The Kelly Criterion tells you exactly where the optimal point is before drag overwhelms your gains.
Together, they provide:
Jensen: How much drag you're experiencing
Kelly: What leverage maximizes your growth
Both: Where leverage becomes dangerous
The Math Behind It
Geometric return formula:
r_geometric = L × r_arithmetic - (L² × σ²) / 2
This shows the tug-of-war between leverage amplification (L × r_arithmetic) and drag (L² × σ²/2).
Maximum survivable leverage:
L_max = 2 × r_arithmetic / σ²
At this point, drag completely cancels out returns (geometric return = 0). Beyond this, you're guaranteed to lose money over time.
How To Read The Chart
Y-axis: Geometric returns (%) - what you actually earn after accounting for drag
Colored lines: Expected returns at different leverage levels over time
Green line (1.0x): Unleveraged baseline
Orange/Red lines (2x/3x): Higher leverage scenarios
Blue circles: Kelly optimal leverage level
Red label at zero: Max survivable leverage (breakeven point)
The Table Breakdown
Jensen's Inequality (1x & 2x): Side-by-side comparison demonstrating:
How drag scales quadratically (1.99% → 7.96% when leverage doubles)
The verification that L×E - Drag = Realized Return
Optimal Leverage: Kelly calculations with fractional variants
Full Kelly: Theoretically optimal but aggressive
0.75x, 0.5x, 0.25x Kelly: Conservative risk management
Sharpe Optimal: Maximizes risk-adjusted returns
Max Leverage: Your "game over" threshold
Leverage Scenarios: Detailed comparison of 1x, 2x, 3x positions showing geometric returns, drag costs, and Sharpe ratios
Practical Insights
Low volatility assets: Higher Kelly → can handle more leverage safely
High volatility assets (crypto for example): Lower Kelly → even 2x can be destructive
Current market regime matters: The indicator adapts to changing volatility conditions
Fractional Kelly is wisdom: Full Kelly assumes perfect parameter estimates (which we never have)
Settings
Risk-free rate: Auto-fetches FRED:DGS3MO (3-month T-Bills) or manual override
Log returns: Enabled by default for mathematically accurate compounding
Display options: Toggle curve/table, adjust positioning and font sizes
Lookback period: Adjustable from 50 to 1500 bars
As you should know by now, leverage is a double-edged sword. This indicator shows you exactly where the edge cuts both ways, helping you find the sweet spot between aggressive growth and mathematical ruin.
Let me know if you have any suggestions.
- Henrique Centieiro Indicator

Ultimate Risk Manager: Fixed Dollar Risk & Position CalculatorAre you tired of manually calculating your position size to risk exactly $10, $50, or $100 per trade?
The Ultimate Risk Manager is a professional-grade position sizing and risk calculation tool designed for day traders and scalpers. Instead of guessing your position size and hoping your stop loss doesn't wipe out your account, this tool allows you to set a Fixed Dollar Risk. It tells you exactly how much margin to use so that if your Stop Loss is hit, you lose exactly the amount you planned for.
Perfect for futures and leverage traders on any exchange (MEXC, Binance, Bybit, etc.).
✨ Key Features:
🎯 Strict Risk Management: Input your desired risk (e.g., $2.00) and the calculator outputs the exact "Total Position" and "Margin" required based on your Stop Loss distance.
🤖 Auto Long/Short Detection: No need to toggle directions. The script automatically detects if it's a LONG or SHORT based on where you place your Stop Loss relative to your Entry.
💸 Built-in Fee Calculator: Input your exchange's round-trip fee percentage. The table calculates your exact fee cost and provides your Net Profit (after fees) at your Take Profit target.
🧹 Ultra-Minimalist Chart Visuals: Say goodbye to indicator lines cutting through your price action. This script uses short, clean floating markers for Entry, SL, and TP that sit neatly in the empty space on the right side of your chart.
🎨 Customizable UI: Includes a Light/Dark theme toggle, adjustable table positioning, and sliders to push the floating chart markers exactly where you want them.
🛠️ How to Use:
Open the indicator Settings (Double-click the table).
Under "Trade Setup," enter your Fixed Risk ($), Leverage, and Exchange Fee (%).
Under "Price Levels," use the Price Picker tool (the target icon) to click your desired Entry, Stop Loss, and Take Profit levels directly on the chart.
Look at the dashboard table! Copy the highlighted Yellow Margin Number and type it directly into your exchange's order box.
Protect your capital and trade like a professional by keeping your risk mathematically consistent on every single trade. Indicator

Global Debt-to-GDP DashboardI've created this macro indicator to monitor world debt. The Global Debt-to-GDP Dashboard helps you to track, compare, and analyze sovereign and private debt levels across 20 major economies.
It provides institutional-grade debt analysis, allowing traders, long term investors and macro investors to identify systemic risks, divergences from global norms, and accelerating debt trends that could signal future economic instability or opportunities.
What It Does
This indicator transforms complex macroeconomic data into actionable insights to understand country leverage by:
Tracking Dual Debt Metrics: Monitors both government debt-to-GDP and private debt-to-GDP ratios for 20 countries. This provides a complete picture of total leverage in each economy.
Divergence Analysis: Compares each country's debt levels against the world average (calculated from selected countries), instantly highlighting which economies are over-leveraged or under-leveraged relative to global norms.
Velocity Tracking: Calculates the rate of change in debt divergence, identifying which countries are rapidly increasing or decreasing their debt burden.
Risk Assessment: Automatically categorizes countries by risk level using color-coded visual indicators
Key Features
20 Major Economies: USA, China, Japan, Germany, UK, France, Italy, Canada, Spain, Australia, South Korea, Brazil, India, Mexico, Switzerland, Singapore, Norway, Saudi Arabia, Russia, and Turkey
Simultaneous Visualization: Plot all selected countries on a single chart with unique color coding for easy identification
Dynamic Country Selection: Enable/disable countries to focus on specific regions or economic blocs
Three Divergence Analysis Modes
Government Only: Analyze sovereign debt divergence from government debt average
Private Only: Focus exclusively on private sector leverage (excludes countries without private debt data)
Total (Gov + Private): Comprehensive view of total economy-wide debt burden
Use Cases
For Macro Traders
Identify Sovereign Risk: Spot countries with unsustainable debt trajectories before credit events
Currency Pairs: Correlate debt divergence with currency strength/weakness
Bond Markets: Anticipate yield spread movements based on relative debt positions
Risk-On/Risk-Off: Use global debt velocity as a systemic risk indicator
For Long-Term Investors
Country Allocation: Make informed decisions about geographic exposure
Risk Management: Avoid over-exposure to high-debt economies
Opportunity Identification: Find under-leveraged economies with growth potential
Portfolio Rebalancing: Use debt trends as signals for portfolio adjustments
How to Use
Initial Setup: Select the countries you want to monitor from the Settings panel
Choose Divergence Type: Select Government Only, Private Only, or Total debt analysis
Configure Display: Adjust table position, text size, and sorting preferences
Set Alerts (Optional): Define your alert thresholds and enable notifications
Table Risk Scores:
🔴🔴🔴 Extreme Risk: Divergence > +100pp above average
🔴🔴 High Risk: Divergence > +50pp above average
🟠 Moderate Risk: Divergence > 0pp above average
🟢 Low Risk: Divergence > -50pp below average
🟢🟢 Very Low Risk: Divergence < -50pp below average
NOTE: "Low Risk" and low-debt might also mean that a country is unable to finance through the issuance of government debt. This is not necessarily a good thing and might not correspond to low risk.
Velocity Indicators:
⬆️⬆️⬆️ Rapid Acceleration: +5pp or more per period
⬆️⬆️ Strong Acceleration: +2 to +5pp per period
⬆️ Moderate Increase: +0.5 to +2pp per period
➡️ Stable: -0.5 to +0.5pp per period
⬇️ Moderate Decrease: -2 to -0.5pp per period
⬇️⬇️ Strong Deceleration: -5 to -2pp per period
⬇️⬇️⬇️ Rapid Deceleration: -5pp or less per period
Important Notes
Data Availability: Some countries lack private debt data (e.g., China, India, Brazil).
World Average Calculation: The world average is dynamically calculated based on your selected countries, not a fixed global figure. This allows for custom peer group comparisons.
Percentage Points vs Percentages: All divergence values are in percentage points (pp), representing the absolute difference from the average, not a relative percentage change.
Let me know if you have comments or suggestions.
Truly yours, Henrique Centieiro
Indicator

Liquidation Heatmap by RumiancevLiquidation Heatmap by Rumiancev
Overview
Liquidation Heatmap is an open-source visual map of estimated liquidation zones built from activity spikes .
When the script detects an unusually large spike, it projects liquidation levels for multiple leverage tiers and aggregates them into horizontal price “bins”. Each bin accumulates weight over time and is displayed as a color gradient:
• Brighter / hotter = higher accumulated weight
• Darker / colder = lower accumulated weight
Important: This is not an exchange liquidation feed and it does not display “real liquidation prices”. It is a proxy model designed to visualize where liquidation pressure could be clustering based on abnormal market activity.
Why BTCUSDT.P is recommended
For the most consistent and “liquidation-relevant” behavior, use a perpetual futures symbol such as BTCUSDT.P .
Perpetual markets provide Open Interest , so the script can use OI Delta (change in OI) as the spike stream. OI delta typically reflects leveraged positioning changes (build-up / flushes) more directly than spot volume.
• On perpetuals → OI data is available → spikes are usually cleaner for this model
• On spot → OI is not available → the script may fall back to volume, which can be noisier
If needed, set OI Symbol Override manually (examples are shown in the input tooltip).
How it works (logic)
1) Select a spike stream
• AUTO : uses OI Delta if available, otherwise Volume
• OI : forces OI Delta
• VOL : forces Volume only
2) Detect spike events
The script measures abnormal activity using a Z-score style approach on the absolute stream:
• Spike Lookback defines the baseline window
• Sensitivity maps to a threshold (lower = more events, higher = fewer events)
• Min bars between events optionally reduces clustering on lower timeframes
3) Project liquidation prices
For each spike event, liquidation estimates are calculated for up to three leverage tiers:
• Long liquidations are projected below the reference price
• Short liquidations are projected above the reference price
4) Bin, accumulate, and colorize
Projected levels are snapped into bins using Bin Scale (ticks) .
Bin weight is accumulated and displayed as a gradient between Low density and High density .
5) Freeze on touch
When price touches a bin (wick or close, depending on settings), the bin is frozen :
• it stops updating
• it becomes dotted / high transparency
This keeps a lightweight history of zones that have been interacted with.
How to read the map
• Bins below price often represent potential long-liquidation pressure zones
• Bins above price often represent potential short-liquidation pressure zones
• Brighter bins = more accumulated spike weight → potentially more crowded zone
• Frozen dotted bins = price already touched that zone (historical interaction)
Timeframes (recommendations)
This indicator runs on any timeframe, but density/noise changes significantly.
Best balance (recommended):
• 15m / 1H / 4H — good signal-to-noise and clean structure
Higher timeframes (cleaner, fewer zones):
• 12H / 1D — fewer events, more “macro” zones
Lower timeframes (noisier by nature):
• 1m / 3m / 5m — more spikes and more bins
To reduce clutter on low TF, consider:
• increasing Sensitivity (e.g., 14–18)
• enabling Min bars between events (e.g., 10–30)
• increasing Bin Scale (ticks) (thicker bins → fewer levels)
• enabling Keep only local range bins
Inputs (what each setting does)
Source
• Source Mode : AUTO / VOL / OI
• OI Symbol Override : manual OI source if AUTO is not suitable
Event (Spike) Filter
• Spike Lookback : baseline window for mean/stdev
• Sensitivity : lower = more events, higher = fewer events
• Use high/low for touch test : wick-based touches
• Min bars between events : reduces spike clustering
Liquidation Levels (bins)
• Reference Price : base price for projections (close/hl2/etc.)
• Leverage 1/2/3 : leverage tiers (set to 0 to disable any tier)
• Bin Scale (ticks) : bin thickness (bigger = fewer bins)
• Extend (bars) : how long active bins extend
• Max active bins per side : cap for active bins
• Dispersion (%) : splits part of the weight to the opposite side
• Keep only local range bins + Local range lookback : trims bins far from recent range
Visual
• Gradient colors, frozen transparency, legend, and debug marker
Limitations / Disclaimer
This script is provided for research and educational purposes only . It is not financial advice .
The plotted zones are estimates derived from a simplified model (spike detection + leverage projections). Results depend on symbol, exchange data availability (OI), and timeframe.
Indicator

Sigmoid Risk AllocatorThe Sigmoid Risk Allocator is a dynamic position sizing indicator that tells you how much of your capital to allocate based on current market conditions. Unlike simple "risk-on/risk-off" signals, this indicator gives you smooth, gradual transitions based on a sigmoid function.
Why a Sigmoid Curve?
Most position sizing approaches use fixed thresholds: "If drawdown > 20%, buy. Otherwise, don't." This creates all-or-nothing decisions.
Using the sigmoid (S-curve) makes this decision different. It creates a smooth transition where:
Small drawdowns → Stay near your baseline allocation
Moderate drawdowns → Gradually increase exposure
Large drawdowns → Approach maximum allocation
The sigmoid curve naturally "saturates" at the extremes, preventing you from going all-in too early or panicking out too fast. This is very useful to meek traders psychology and risk management in check.
What's a Sigmoid Function?
The sigmoid function is a mathematical S-curve defined as:
σ(x) = 1 / (1 + e^(-x))
This formula takes any input value and smoothly maps it to a number between 0 and 1. The curve has three key properties that make it ideal for position sizing in investing:
Smooth transitions: No sudden jumps. Allocation changes gradually.
Saturation at extremes: The curve flattens near 0 and 1, preventing overreaction and overexposure.
Sensitive in the middle: Most of the action happens around the midpoint.
To convert this into an allocation percentage, the indicator uses:
Allocation = α_min + (α_max - α_min) × σ(k × (Risk - Midpoint))
Where:
- `α_min` = Your minimum allocation (default 50%)
- `α_max` = Your maximum allocation (default 100%)
- `Risk` = Current risk metric (drawdown %, volatility, or Kelly %)
- `Midpoint` = The risk level where allocation sits halfway between min and max (default 15%)
- `k` = Steepness—how quickly allocation changes around the midpoint
Example : With defaults, if drawdown hits 15% (the midpoint), your allocation will be 75% (halfway between 50% and 100%). As the drawdown increases beyond 15%, the allocation curves toward 100%. As it decreases toward 0%, allocation curves toward 50%.
Cool, isn't it?
Asymmetric Response: Fast In, Slow Out
The indicator uses different steepness values for scaling in vs. scaling out. This is great to increase trend following. This is something I'm proud of too in this indicator.
k_increase = 30 (steep curve): When drawdowns appear, allocation ramps up quickly to catch the opportunity
k_decrease = 5 (slower curve): When conditions normalize, allocation decreases slowly to avoid selling the rebound
This asymmetry reflects how markets behave—drawdowns often overshoot fundamentals (rewarding quick entries), while recoveries tend to be more orderly (rewarding patience on exits).
Three Risk Metrics
You can choose what drives your allocation:
Drawdown (Default)
Volatility - Scales your position inversely to current market volatility.
Kelly Criterion - Automatically calculates optimal position size. The indicator applies a conservative "half Kelly" by default.
Use Cases
Position sizing for swing trading or trend following
Risk management overlay for any existing strategy
Drawdown-based DCA (dollar cost averaging) decisions
Volatility-adjusted exposure management
Feel free to provide feedback and share your thoughts!
- Henrique Centieiro Indicator

Indicator

Sigmoid Allocation Indicator & DashboardTL;DR This sigmoid-based allocation indicator tells you percentage of your portfolio to invest based on how much the market has dropped.
Market at all-time high? → Stay defensive, invest less (e.g., 30%)
Market crashed hard? → Get aggressive, invest more (e.g., 100%)
The "sigmoid" part just means the transition between these two extremes follows a smooth S-shaped curve.
Description
This indicator is a sigmoid-based allocation system that dynamically adjusts a portfolio exposure based on market drawdown.
It compares multiple steepness curves (K values) to find your optimal risk profile for leveraged ETF strategies, but it can also be used to scale in-out from stocks, crypto and to understand whether to use leverage or not.
The Sigmoid Allocation Dashboard helps you to dynamically adjust a portfolio allocation based on how much a market has dropped from its all-time high.
I've implemented it using a sigmoid (S-curve) function, that dynamically calculates the optimal allocation percentages. Depending on the market conditions, the S curves transition between defensive and aggressive allocations.
The Math Behind It (if you are a geek like me)
This indicator uses the sigmoid function to create smooth S-curve transitions:
α(D) = α_min + (α_max - α_min) × σ(k × (D - D_mid))
Where:
σ(x) = 1 / (1 + e^(-x)) ← Standard sigmoid function
You can also check it here:
// Sigmoid function: σ(x) = 1 / (1 + e^(-x))
sigmoid(float x) =>
1.0 / (1.0 + math.exp(-x))
// Alpha calculation: α(D) = α_min + (α_max - α_min) × σ(k × (D - D_mid))
calcAlpha(float drawdown, float k, float a_min, float a_max, float d_midpoint) =>
sig_input = k * (drawdown - d_midpoint) / 100.0
a_min + (a_max - a_min) * sigmoid(sig_input)
User parameters (you can tweak this):
Allocation Min (%): Your baseline allocation when markets are at ATH (default: 30%)
Allocation Max (%): Your maximum allocation during deep drawdowns (default: 100%)
D_mid (%): The drawdown level where you want to be at the midpoint (default: 25%)
Why do I like sigmoid and not a linear line?
Unlike linear models, the sigmoid creates "floors" and "ceilings" for your allocation. It transitions smoothly, no sudden jumps, and you never exceed your defined min/max bounds.
Understand the K Values (Steepness)
The K parameter controls how quickly your allocation shifts from defensive to aggressive.
Lower K (for example K=5) will give you a gradual transition, but at 0% drawdown you are already at a 46% allocation.
A higher like (like K=40) will give you a sharp transition, but at 0% drawdown you are close to the minimum allocation. On the other hand, a higher K will give close to 100% allocation when the markets are at new lows.
The example below illustrates this well, then the S&P 500 reached new lows in October 2022:
Different K values will affect the sigmoid curves (and you allocations differently). The chart below illustrates well how K affects the sigmoid curves:
Read the Dashboard
The main dashboard shows:
Current drawdown from ATH
Allocation % for each K value
Suggested action (Defensive → MAX LONG)
Use the Reference Chart
The static reference panel shows what your allocation would be at various drawdown levels (0%, 10%, 20%, 30%, 40%, 50%), helping you plan ahead.
Identify Zones
The color-coded chart background shows:
- 🟢 Green Zone: Aggressive positioning - "Buy the Dip"
- 🟡 Yellow Zone: Transition zone - Scaling in/out
- 🔴 Red Zone: Defensive positioning - Protect ya gains
Use Cases
Use case 1: Leveraged ETF Portfolio Management (this is my main use case)
When holding leveraged ETFs like TQQQ or UPRO, volatility makes it important to:
- Reduce exposure near all-time highs (when crashes hurt most)
- Increase exposure during drawdowns (when recovery potential is highest)
Example Strategy:
- At ATH: Hold 30% TQQQ, 70% cash/bonds or other uncorrelated assets
- At 25% drawdown: Hold 65% TQQQ, 35% cash/bonds
- At 40%+ drawdown: Hold 100% TQQQ
Use case 2: Diversified Leveraged Portfolio
Compare different K values for different assets:
- Use K = 10 for broad market (QQQ/SPY exposure via TQQQ/UPRO)
- Use K = 25 for sector bets (TECL, SOXL, TMF) that you want to scale into faster
Use case 3: Systematic Rebalancing Signals
Use the alerts to trigger rebalancing:
- Alert when K3 allocation crosses above 90% (time to add)
- Alert when drawdown exceeds your D_mid threshold
- Alert when market returns to within 5% of ATH
Tips for Best Results
It works best in longer time frames
Adjust the ATR lookback window
Match your risk tolerance level
I use this for index investing and stocks and haven't tried with crypto
Thanks for using the indicator and let me know if you have any feedback :)
- Henrique Centieiro
Indicator

Indicator

DCA Ladder CalculatorThis script is a DCA (Dollar-Cost Averaging) Ladder Calculator with Risk & Leverage Management baked in.
It’s designed for both LONG and SHORT positions, and helps you:
🎯 Strategically scale into positions across multiple entry points
🔐 Control risk exposure via defined capital allocation
⚖️ Utilize leverage responsibly — for efficiency, not destruction
🧮 Visualize risk, stop loss level, and entry distribution
🔁 Adapt to trend reversals or key zones, especially when combined with reversal indicators or higher timeframe signals
🧠 How It Works
This tool takes a capital allocation approach to building a ladder of positions:
1. You define:
- Portfolio value
- Risk per trade (as %)
- Leverage
- Number of DCA levels
- Entry multiplier (e.g. 1x, 2x, 4x...)
2. The script then:
- Calculates total margin to risk = Portfolio × Risk %
- Calculates total leveraged position size = Margin × Leverage
- Distributes entries according to exponential weights (1x, 2x, 4x...), totaling 7 for 3 levels
- Calculates per-entry:
- Entry price (based on price zone spacing)
- Multiplier
- Exact margin per entry
- Leverage per entry (margin × leverage)
- Computes:
- Average entry price (margin-weighted)
- Approximate stop loss level based on recent ATR and price structure
- % drawdown to SL
- Total margin and position size
3. Displays all this in a clean on-chart table.
📈 How to Use It
1. Apply the indicator to a chart (default: 1D — ideal for clean zones).
2. Configure your:
- Portfolio Value (total trading capital)
- Risk per Trade (%) (your acceptable loss)
- Leverage (exchange or strategy-based)
- DCA Levels (e.g. 3 = anchor + 2 entries)
- Multiplier (typically 2.0 for doubling)
3. Choose LONG or SHORT mode depending on direction.
4. The table will show:
- Entry price ladder
- Margin used per entry
- Total position size
- Approx. stop loss (where your full risk is defined)
Use in conjunction with price action, S/R zones, trendline breaks, volume divergence, or reversal indicators.
✅ Best Practices for Using This Tool
- Leverage is a tool, not a weapon. Use it to scale smartly — not recklessly.
- Use fewer, higher-conviction entries. Don’t blindly ladder; combine with price structure and signals.
- Stick to your risk percent. Never risk more than you can afford to lose. Let this calculator enforce discipline.
- Combine with other confirmation tools, like RSI divergence, momentum shifts, OB zones, etc.
- Avoid martingale-style over-exposure. This is not a gambling tool — it’s for capital efficiency.
🛡️ What This Tool Does NOT Do
- This is not a trade signal indicator.
- It does not place trades or auto-manage positions.
- It does not replace personal responsibility or strategy — it's a tool to help apply structure.
⚠️ Disclaimer
This script is for educational and informational purposes only.
It does not constitute financial advice, nor is it a recommendation to buy or sell any financial instrument.
Always consult a licensed financial advisor before making investment decisions.
Use of leverage involves high risk and can lead to substantial losses.
The author and publisher assume no liability for any trading losses resulting from use of this script. Indicator
