OPEN-SOURCE SCRIPT
Zaktualizowano Risk & Levels Cockpit

Risk & Levels Cockpit
Risk & Levels Cockpit answers one question on any market and any timeframe: if I take this trade, where is my stop, what size should I trade, and what can I lose? It is a risk-and-levels tool, not a buy/sell signal — it does not predict direction, it bounds risk around a trade you have already decided to take.
HOW IT WORKS
Three components chain one-way:
Theil-Sen robust channel — fits a trend line as the median of all pairwise slopes over the lookback. Being a median, it cannot be tilted by a single spike or wick the way ordinary regression can, so the rails give you a stable structure to trade against.
Extreme Value Theory tail model (Peaks-Over-Threshold, Generalized Pareto) — estimates how far price can realistically move against you at a chosen tail quantile, replacing a guessed 2xATR stop with a distance grounded in the actual tail of the return distribution. The channel rail acts as a structural floor, so your stop is never tighter than the channel edge.
Fixed-fractional sizer — turns that stop into a position size: units = floor(risk-budget / (risk distance x point value)). When the stop is wider than your risk budget, size correctly floors to zero and the panel shows what one unit would cost and the capital that would make one unit equal your target risk, so a zero is a decision, not a dead end.
TWO SIZING BASES
Stop distance risks your fraction at the drawn stop. Expected Shortfall risks your fraction at the mean loss beyond the stop (McNeil-Frey POT form, from the same tail fit) — wider, so fewer units, so that gapping through your stop still respects your budget. The panel always shows both the at-stop and at-tail loss per unit, so gap risk is visible in either mode. An optional vol-target overlay (on by default) scales size to keep portfolio volatility steadier across regimes; the Size-mode row always shows the live multiplier.
WORKS ON ANY MARKET, ANY TIMEFRAME
No session, expiry, or clock anchors; every lookback is in bars and volatility annualization self-scales — identical behavior from 1-minute scalping to daily positional, on stocks, futures, forex, crypto, and indices worldwide. Set the currency symbol and point value (money per point per unit) to your instrument: stocks/crypto/spot = 1; index and futures = the contract multiplier (for example NIFTY 65, S&P E-mini 50, Nikkei 1000, DAX 25); forex = point value per lot; options = point value x delta.
A Scalp/Intraday, Positional, or Custom preset adjusts the tail horizon and quantile. Scalp/Intraday is the default (tighter stops); positional traders should switch to the Positional preset for wider, conservative stops.
ON THE CHART
A slope-colored robust trend line with a TREND pill and a channel band, plus solid, pill-labeled decision levels — red STOP, amber BREAK (invalidation), and green T1 and T2 TARGET, each showing price and R-multiple. The panel gives the full sizing and risk readout, including a daily-loss-budget line.
LIMITATIONS (read before use)
Not a signal and not investment advice. Stops and targets are model references, not guarantees — gaps and slippage can exceed them. The tail quantile is scaled to the holding horizon by square-root-of-time, a deliberate approximation chosen over overlapping h-bar fitting which violates independence. The daily-loss cap is a display aid; a single-chart indicator cannot track or enforce live fills. The vol-target overlay multiplies the fixed-fractional size and can nudge per-trade risk above the nominal percent in calm markets — set Size clamp max to 1.0 to only reduce size, or turn it off for a strict fixed-percent rule. Position sizing does not create an edge; it bounds risk.
CREDITS
Original implementation. Theil (1950) and Sen (1968) robust slope; Pickands-Balkema-de Haan / Peaks-Over-Threshold Generalized Pareto tail estimation and Expected Shortfall (McNeil-Frey); fixed-fractional position sizing (Tharp / Vince).
Risk & Levels Cockpit answers one question on any market and any timeframe: if I take this trade, where is my stop, what size should I trade, and what can I lose? It is a risk-and-levels tool, not a buy/sell signal — it does not predict direction, it bounds risk around a trade you have already decided to take.
HOW IT WORKS
Three components chain one-way:
Theil-Sen robust channel — fits a trend line as the median of all pairwise slopes over the lookback. Being a median, it cannot be tilted by a single spike or wick the way ordinary regression can, so the rails give you a stable structure to trade against.
Extreme Value Theory tail model (Peaks-Over-Threshold, Generalized Pareto) — estimates how far price can realistically move against you at a chosen tail quantile, replacing a guessed 2xATR stop with a distance grounded in the actual tail of the return distribution. The channel rail acts as a structural floor, so your stop is never tighter than the channel edge.
Fixed-fractional sizer — turns that stop into a position size: units = floor(risk-budget / (risk distance x point value)). When the stop is wider than your risk budget, size correctly floors to zero and the panel shows what one unit would cost and the capital that would make one unit equal your target risk, so a zero is a decision, not a dead end.
TWO SIZING BASES
Stop distance risks your fraction at the drawn stop. Expected Shortfall risks your fraction at the mean loss beyond the stop (McNeil-Frey POT form, from the same tail fit) — wider, so fewer units, so that gapping through your stop still respects your budget. The panel always shows both the at-stop and at-tail loss per unit, so gap risk is visible in either mode. An optional vol-target overlay (on by default) scales size to keep portfolio volatility steadier across regimes; the Size-mode row always shows the live multiplier.
WORKS ON ANY MARKET, ANY TIMEFRAME
No session, expiry, or clock anchors; every lookback is in bars and volatility annualization self-scales — identical behavior from 1-minute scalping to daily positional, on stocks, futures, forex, crypto, and indices worldwide. Set the currency symbol and point value (money per point per unit) to your instrument: stocks/crypto/spot = 1; index and futures = the contract multiplier (for example NIFTY 65, S&P E-mini 50, Nikkei 1000, DAX 25); forex = point value per lot; options = point value x delta.
A Scalp/Intraday, Positional, or Custom preset adjusts the tail horizon and quantile. Scalp/Intraday is the default (tighter stops); positional traders should switch to the Positional preset for wider, conservative stops.
ON THE CHART
A slope-colored robust trend line with a TREND pill and a channel band, plus solid, pill-labeled decision levels — red STOP, amber BREAK (invalidation), and green T1 and T2 TARGET, each showing price and R-multiple. The panel gives the full sizing and risk readout, including a daily-loss-budget line.
LIMITATIONS (read before use)
Not a signal and not investment advice. Stops and targets are model references, not guarantees — gaps and slippage can exceed them. The tail quantile is scaled to the holding horizon by square-root-of-time, a deliberate approximation chosen over overlapping h-bar fitting which violates independence. The daily-loss cap is a display aid; a single-chart indicator cannot track or enforce live fills. The vol-target overlay multiplies the fixed-fractional size and can nudge per-trade risk above the nominal percent in calm markets — set Size clamp max to 1.0 to only reduce size, or turn it off for a strict fixed-percent rule. Position sizing does not create an edge; it bounds risk.
CREDITS
Original implementation. Theil (1950) and Sen (1968) robust slope; Pickands-Balkema-de Haan / Peaks-Over-Threshold Generalized Pareto tail estimation and Expected Shortfall (McNeil-Frey); fixed-fractional position sizing (Tharp / Vince).
Informacje o Wersji
Risk & Levels Cockpit v1.3 — Volume Profile updateThis update adds volume-profile structure to the risk and levels engine, so stops and targets can anchor to where volume actually traded, not only to the tail model and the robust channel.
What's new:
Volume Profile (POC / Value Area). A rolling profile computes the Point of Control and the 70% value area (VAH/VAL) over the lookback window. These are drawn as labelled levels and feed the risk logic directly.
VP as a third stop floor. The stop now sits at the widest of three independent structures — the EVT tail, the Theil-Sen rail, and the value-area edge (VAL for longs, VAH for shorts) — with a sanity cap so a distant value area can't blow up the stop. The Stop-source row shows which structure is binding (EVT tail / Rail floor / VP).
Value-area context. A new panel row reads "in value / above VAH (premium) / below VAL (discount)," telling you when price is balanced versus extended.
Optional VP target mode. Targets can anchor to POC and the value edges instead of fixed R-multiples; target labels show the effective R either way.
Universal volume handling. If the instrument has no volume (some spot/forex/index feeds), the profile auto-disables and the Cockpit falls back to the tail/channel logic exactly as before.
Also: label sizing reduced for cleaner display on fast timeframes; internal naming genericized for full cross-market use.
Unchanged: this remains a risk-and-levels tool, not a signal. Volume-profile levels are structure, not prediction — they make stops and targets non-arbitrary. Position sizing bounds risk; it does not create an edge. Not investment advice.
Informacje o Wersji
Risk & Levels Cockpit v1.4 — Net R and alertsTwo additions that change how the tool is used day to day.
TRANSACTION COSTS AND NET R
Gross R flatters every setup. This version converts your round-trip cost — brokerage, exchange fees, taxes and expected slippage — into price points and applies it on both sides of the trade: it shrinks the distance you capture and it widens the loss you actually take. So the reported figure is R_net = (target − cost) / (stop + cost), not simply a discounted target.
Both net and gross R are shown side by side, and a new Cost drag row reports what cost is as a share of your R, color-coded. On tight intraday stops this is often a large fraction, and it decides whether a setup is worth taking at all. Three cost models are provided so the tool fits any market: percent of turnover, fixed money per unit, or ticks per side. Costs can be switched off to see gross figures.
ALERTS
Six conditions are now available from the alert dialog: stop touched, Target 1 reached, Target 2 reached, break level crossed (structure invalidated), trend bias flipped, and size fell to zero — the last firing when the stop has widened beyond what your risk budget can size. Levels are computed on confirmed bars and alerts fire on the touch.
Everything else is unchanged: the Theil-Sen robust channel, the EVT tail stop with Expected Shortfall sizing, volume-profile structure, and the universal instrument model all behave exactly as before.
Unchanged framing: this is a risk-and-levels tool, not a signal. It does not forecast direction. Position sizing bounds risk; it does not create an edge. Not investment advice.
Skrypt open-source
W zgodzie z duchem TradingView twórca tego skryptu udostępnił go jako open-source, aby użytkownicy mogli przejrzeć i zweryfikować jego działanie. Ukłony dla autora. Korzystanie jest bezpłatne, jednak ponowna publikacja kodu podlega naszym Zasadom serwisu.
Wyłączenie odpowiedzialności
Informacje i publikacje nie stanowią i nie powinny być traktowane jako porady finansowe, inwestycyjne, tradingowe ani jakiekolwiek inne rekomendacje dostarczane lub zatwierdzone przez TradingView. Więcej informacji znajduje się w Warunkach użytkowania.
Skrypt open-source
W zgodzie z duchem TradingView twórca tego skryptu udostępnił go jako open-source, aby użytkownicy mogli przejrzeć i zweryfikować jego działanie. Ukłony dla autora. Korzystanie jest bezpłatne, jednak ponowna publikacja kodu podlega naszym Zasadom serwisu.
Wyłączenie odpowiedzialności
Informacje i publikacje nie stanowią i nie powinny być traktowane jako porady finansowe, inwestycyjne, tradingowe ani jakiekolwiek inne rekomendacje dostarczane lub zatwierdzone przez TradingView. Więcej informacji znajduje się w Warunkach użytkowania.