Risk Manager Pro: Diamond Edition [Kelly & EV Engine]1. Titolo dello Script
Risk Manager Pro: Diamond Edition
2. Descrizione (Copia e incolla nel box descrizione)
Risk Manager Pro: Diamond Edition is not just a position size calculator; it is a complete algorithmic trading assistant designed to bridge the gap between technical analysis and professional money management.
Many traders focus solely on where to enter. This tool focuses on if you should enter and how much you should risk, using institutional-grade probability models like the Kelly Criterion and Expected Value (EV).
💎 Key Features
1. The "Truth" Metrics (EV & Kelly) Instead of just showing PnL, the dashboard calculates two critical decision-making metrics:
Expected Value (EV): Calculated in your currency. It combines your Win Rate, Potential Profit, and Risk. If EV is Green, the trade makes mathematical sense. If Red, you are paying to gamble.
Kelly Criterion Edge: Measures your statistical edge.
Weighted R:R: Unlike standard calculators that average Risk:Reward, this engine weighs your R:R based on your partial take-profit quantities (e.g., closing 50% at TP1 vs 80% at TP1 changes your real math).
2. Kelly Auto-Sizing Engine (Algo-Sizing) This is the standout feature. When enabled in settings:
The script automatically adjusts your position size based on the strength of your statistical edge.
If the Kelly score is negative (no edge), the script forces Size = 0 (protecting you from bad trades).
If the edge is positive, it scales the risk proportionally (capped at your Max Risk input).
3. Planning Mode vs. Live Mode
Planning Mode: Set an Entry Mode to "Manual Level". The visual lines (Entry, SL, TP) detach from the current price, allowing you to plan Limit or Stop orders. The dashboard calculates risks based on that future entry.
Live Mode: Anchors calculations to the current Close price for market execution.
4. Institutional Fee Modeling
Includes inputs for Commissions, Spread, and Swap.
Triple Swap Toggle: A checkbox to account for weekend/Wednesday triple swap costs, crucial for Swing/Position traders.
5. Dynamic Visuals
Smart Trail Pilot: A dynamic trailing stop line that changes color from Purple (Risk Zone) to Neon Green (Safe Zone/Locked Profit) once price crosses your entry.
Clean Chart Toggle: Hide the background risk boxes for a minimalist view.
🛠️ Dashboard Breakdown
Row 1 (Status): Shows active mode (Planning/Live) and the Expected Value (EV). This is your "Go/No-Go" gauge.
Row 2 (Edge): Displays your Win Rate and Kelly Status.
Row 3 (Sizing): Calculates Lot Size and effective Leverage.
Row 4 (PnL): Projected Net Profit and the True Weighted R:R.
Row 5 (Costs): Total estimated drag on the account (Fees + Swap + Spread).
Row 6 (Context): Trend filter analysis (EMA 50/200 logic).
⚙️ How to Use
Configure Profile: Set your Account Balance and Currency.
Input Win Rate: Be honest. Input your historical Win Rate (or calculate it from your last 20 trades via the option).
Plan the Trade:
Select Long/Short.
Choose your SL Mode (Fixed, ATR, or Swing Structure).
Adjust TPs (Single or Multi-Target).
Check the EV: Look at the top right of the dashboard. Is the EV positive?
Execute: Use the calculated "Size" for your broker order window.
Disclaimer: This tool is for educational and risk management purposes only. It does not provide financial advice. The "Kelly Auto-Sizing" is a mathematical model and does not guarantee future profits. Always trade responsibly.
If you find this script useful, please leave a comment with your feedback! Suggestions for improvement are greatly appreciated.
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.


