Risk Manager & ATR TS Strategy📌 Overview
This script is not a simple indicator mashup. It is a Risk & Trade Planning Engine that combines a strategy-based signal generator with a snapshot-based risk, sizing, and expectancy model. It is designed to support real trading decisions, not just to generate cosmetic signals or overfitted backtests.
The core idea is to separate market logic from risk logic, evaluating each trade only at the moment it becomes actionable using fixed reference points that do not change afterward.
🎯 What makes this script original Unlike most tools that merely combine indicators or visualize entries, this script introduces several non-standard design choices:
Snapshot-based risk sizing (The "Time Machine" logic).
Expected Value (EV) calculation in both Money and R-multiples.
Kelly Criterion applied with weighted multi-target logic.
Strict architectural separation between the signal engine and the risk engine.
Decision-oriented dashboard instead of decorative plots.
These components are not merged for convenience; they are architecturally dependent on each other.
🧠 Conceptual Architecture
1️⃣ Signal Engine (Market Context) The signal engine is based on an ATR Trailing Stop system combined with trend regime filters (ADX and Choppiness Index). Its only responsibility is to answer one question: "Is this a valid directional opportunity right now?" It does not manage risk; it only identifies the opportunity.
2️⃣ Snapshot Logic (Key Design Choice) When a valid signal occurs, the script captures a Snapshot of the Entry price, Initial Stop-Loss, and Risk Distance. This snapshot is frozen at signal time. It is never updated, even if the trailing stop moves later. This avoids the most common error in TradingView scripts: recalculating position size using a moving stop, which falsifies the risk data.
3️⃣ Risk Engine (Sizing & Control) Using the snapshot values, the script computes:
Monetary risk per trade (capped at your user-defined max).
Position size derived from the fixed stop distance.
Effective leverage (informational).
4️⃣ Multi-Target Reward Model Instead of assuming a single take-profit, the script supports multiple targets with user-defined probability weights. From this, it derives a Weighted Risk/Reward Ratio, which feeds directly into the EV and Kelly calculations.
5️⃣ Expected Value (EV) in Money & R The script calculates EV in your account currency (real impact) and normalized in R-multiples (statistical quality). This allows you to compare trade quality across different assets and timeframes objectively.
6️⃣ Kelly Criterion (Conservative) The Kelly Criterion is applied using the weighted reward model and is always subordinated to your hard risk cap. If Kelly suggests a negative value, the script advises "NO TRADE". It is used as a filter, not a leverage amplifier.
📊 Dashboard & Alerts The on-chart dashboard summarizes everything you need at the moment of the signal:
Risk % and Position Size
Expected Value (Money + R)
Kelly Suggestion
Signal Strength
Alerts are triggered once per signal (on bar close) using snapshot data, ensuring no repainting and no spam.
🔍 How this is NOT a mashup Each component exists because another component depends on it. Snapshot logic is required for valid risk sizing; Risk sizing is required for EV normalization; Weighted RR is required for meaningful Kelly. Removing any part breaks the system’s logic.
📘 How to use
Choose your account size and risk parameters in the settings.
Configure your stop logic and reward targets.
Wait for a valid signal.
Evaluate the dashboard: Decide if the trade quality (EV, R, Risk) justifies participation.
⚖️ Open-Source Notice This script is published under the Mozilla Public License 2.0 (MPL-2.0). It does not copy or replicate any single public script. Standard concepts (ATR, ADX) are used as building blocks, but the architecture and calculations are original.
🚫 Disclaimer This script is a planning and evaluation engine designed to help traders think in terms of risk, expectancy, and discipline. It does not guarantee profitability.
✅ Summary This is a professional-grade framework built to answer one core question: “Is this trade worth taking, given my risk and my expectations?” Not every signal is a trade, and not every trade deserves capital. This script helps you make that distinction.
Kellycriterion
Kelly Optimal Leverage IndicatorThe Kelly Optimal Leverage Indicator mathematically applies Kelly Criterion to determine optimal position sizing based on market conditions.
This indicator helps traders answer the critical question: "How much capital should I allocate to this trade?"
Note that "optimal position sizing" does not equal the position sizing that you should have. The Optima position sizing given by the indicator is based on historical data and cannot predict a crash, in which case, high leverage could be devastating.
Originally developed for gambling scenarios with known probabilities, the Kelly formula has been adapted here for financial markets to dynamically calculate the optimal leverage ratio that maximizes long-term capital growth while managing risk.
Key Features
Kelly Position Sizing: Uses historical returns and volatility to calculate mathematically optimal position sizes
Multiple Risk Profiles: Displays Full Kelly (aggressive), 3/4 Kelly (moderate), 1/2 Kelly (conservative), and 1/4 Kelly (very conservative) leverage levels
Volatility Adjustment: Automatically recommends appropriate Kelly fraction based on current market volatility
Return Smoothing: Option to use log returns and smoothed calculations for more stable signals
Comprehensive Table: Displays key metrics including annualized return, volatility, and recommended exposure levels
How to Use
Interpret the Lines: Each colored line represents a different Kelly fraction (risk tolerance level). When above zero, positive exposure is suggested; when below zero, reduce exposure. Note that this is based on historical returns. I personally like to increase my exposure during market downturns, but this is hard to illustrate in the indicator.
Monitor the Table: The information panel provides precise leverage recommendations and exposure guidance based on current market conditions.
Follow Recommended Position: Use the "Recommended Position" guidance in the table to determine appropriate exposure level.
Select Your Risk Profile: Conservative traders should follow the Half Kelly or Quarter Kelly lines, while more aggressive traders might consider the Three-Quarter or Full Kelly lines.
Adjust with Volatility: During high volatility periods, consider using more conservative Kelly fractions as recommended by the indicator.
Mathematical Foundation
The indicator calculates the optimal leverage (f*) using the formula:
f* = μ/σ²
Where:
μ is the annualized expected return
σ² is the annualized variance of returns
This approach balances potential gains against risk of ruin, offering a scientific framework for position sizing that maximizes long-term growth rate.
Notes
The Full Kelly is theoretically optimal for maximizing long-term growth but can experience significant drawdowns. You should almost never use full kelly.
Most practitioners use fractional Kelly strategies (1/2 or 1/4 Kelly) to reduce volatility while capturing most of the growth benefits
This indicator works best on daily timeframes but can be applied to any timeframe
Negative Kelly values suggest reducing or eliminating market exposure
The indicator should be used as part of a complete trading system, not in isolation
Enjoy the indicator! :)
P.S. If you are really geeky about the Kelly Criterion, I recommend the book The Kelly Capital Growth Investment Criterion by Edward O. Thorp and others.
FunctionKellyCriterionLibrary "FunctionKellyCriterion"
Kelly criterion methods.
the kelly criterion helps with the decision of how much one should invest in
a asset as long as you know the odds and expected return of said asset.
simplified(win_p, rr)
simplified version of the kelly criterion formula.
Parameters:
win_p : float, probability of winning.
rr : float, reward to risk rate.
Returns: float, optimal fraction to risk.
usage:
simplified(0.55, 1.0)
partial(win_p, loss_p, win_rr, loss_rr)
general form of the kelly criterion formula.
Parameters:
win_p : float, probability of the investment returns a positive outcome.
loss_p : float, probability of the investment returns a negative outcome.
win_rr : float, reward on a positive outcome.
loss_rr : float, reward on a negative outcome.
Returns: float, optimal fraction to risk.
usage:
partial(0.6, 0.4, 0.6, 0.1)
from_returns(returns)
Calculate the fraction to invest from a array of returns.
Parameters:
returns : array trade/asset/strategy returns.
Returns: float, optimal fraction to risk.
usage:
from_returns(array.from(0.1,0.2,0.1,-0.1,-0.05,0.05))
final_f(fraction, max_expected_loss)
Final fraction, eg. if fraction is 0.2 and expected max loss is 10%
then you should size your position as 0.2/0.1=2 (leverage, 200% position size).
Parameters:
fraction : float, aproximate percent fraction invested.
max_expected_loss : float, maximum expected percent on a loss (ex 10% = 0.1).
Returns: float, final fraction to invest.
usage:
final_f(0.2, 0.5)
hpr(fraction, trade, biggest_loss)
Holding Period Return function
Parameters:
fraction : float, aproximate percent fraction invested.
trade : float, profit or loss in a trade.
biggest_loss : float, value of the biggest loss on record.
Returns: float, multiplier of effect on equity so that a win of 5% is 1.05 and loss of 5% is 0.95.
usage:
hpr(fraction=0.05, trade=0.1, biggest_loss=-0.2)
twr(returns, rr, eps)
Terminal Wealth Relative, returns a multiplier that can be applied
to the initial capital that leadds to the final balance.
Parameters:
returns : array, list of trade returns.
rr : float , reward to risk rate.
eps : float , minimum resolution to void zero division.
Returns: float, optimal fraction to invest.
usage:
twr(returns=array.from(0.1,-0.2,0.3), rr=0.6)
ghpr(returns, rr, eps)
Geometric mean Holding Period Return, represents the average multiple made on the stake.
Parameters:
returns : array, list of trade returns.
rr : float , reward to risk rate.
eps : float , minimum resolution to void zero division.
Returns: float, multiplier of effect on equity so that a win of 5% is 1.05 and loss of 5% is 0.95.
usage:
ghpr(returns=array.from(0.1,-0.2,0.3), rr=0.6)
run_coin_simulation(fraction, initial_capital, n_series, n_periods)
run multiple coin flipping (binary outcome) simulations.
Parameters:
fraction : float, fraction of capital to bet.
initial_capital : float, capital at the start of simulation.
n_series : int , number of simulation series.
n_periods : int , number of periods in each simulation series.
Returns: matrix(n_series, n_periods), matrix with simulation results per row.
usage:
run_coin_simulation(fraction=0.1)
run_asset_simulation(returns, fraction, initial_capital)
run a simulation over provided returns.
Parameters:
returns : array, trade, asset or strategy percent returns.
fraction : float , fraction of capital to bet.
initial_capital : float , capital at the start of simulation.
Returns: array, array with simulation results.
usage:
run_asset_simulation(returns=array.from(0.1,-0.2,0.-3,0.4), fraction=0.1)
strategy_win_probability()
calculate strategy() current probability of positive outcome in a trade.
strategy_avg_won()
calculate strategy() current average won on a trade with positive outcome.
strategy_avg_loss()
calculate strategy() current average lost on a trade with negative outcome.


