
Risk Management Trading
- 364 installs
- 122 repo stars
- Updated January 22, 2026
- omer-metin/skills-for-antigravity
risk-management-trading is an agent skill that applies position sizing, drawdown limits, Kelly Criterion, and volatility targeting for developers building systematic trading systems or algo risk controls.
About
risk-management-trading is a trading risk agent skill from omer-metin/skills-for-antigravity framed as a Risk Management Architect voice. It combines Kelly Criterion sizing, volatility targeting, correlation analysis, stop-loss discipline, portfolio risk budgets, and drawdown management for capital preservation in systematic strategies. Developers reach for risk-management-trading when coding execution logic, backtests, or portfolio monitors that must enforce max loss, risk-per-trade, and volatility-adjusted exposure instead of discretionary sizing. Trigger phrases include position size, drawdown, kelly, stop loss, and portfolio risk. The skill emphasizes surviving adverse regimes through explicit limits rather than optimizing entries alone.
- Position sizing frameworks: fixed fractional, Kelly Criterion, and volatility-adjusted sizing
- Drawdown, margin, and leverage management with risk-adjusted metrics (Sharpe, Sortino, Calmar)
- Portfolio-level correlation analysis, risk budgeting, and tail-risk awareness
- Stop-loss optimization and max-loss-per-trade guardrails
- Voice and heuristics grounded in capital-preservation trading discipline (Thorp/Jones-style framing)
Risk Management Trading by the numbers
- 364 all-time installs (skills.sh)
- +2 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #315 of 1,106 Finance & Trading skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/omer-metin/skills-for-antigravity --skill risk-management-tradingAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 364 |
|---|---|
| repo stars | ★ 122 |
| Security audit | 3 / 3 scanners passed |
| Last updated | January 22, 2026 |
| Repository | omer-metin/skills-for-antigravity ↗ |
How do you size positions and cap drawdown in algo trading?
Apply disciplined position sizing, drawdown limits, and portfolio risk budgets when you trade systematically or ship algo/trading tooling as a developer.
Who is it for?
Developers shipping systematic trading bots, backtests, or portfolio tooling who need enforceable risk controls beyond entry signals.
Skip if: Casual investing advice, fundamental stock research, or teams with no quantitative execution or backtesting context.
When should I use this skill?
User mentions risk management, position sizing, Kelly criterion, drawdown limits, stop loss, volatility targeting, or portfolio risk in trading code.
What you get
Position-sizing rules, stop-loss and drawdown limits, volatility targets, correlation-aware portfolio risk budget, and documented risk-per-trade parameters.
- Position-sizing parameters
- Drawdown and stop-loss rules
- Portfolio risk budget specification
Files
Risk Management Trading
Identity
Role: Risk Management Architect
Voice: A veteran trader who learned risk management the hard way - through blown accounts, margin calls, and sleepless nights. Now speaks with the precision of a quant and the wisdom of someone who's seen fortunes evaporate overnight. Believes that risk management IS the edge, not an afterthought. Channels the discipline of Paul Tudor Jones, the mathematics of Ed Thorp, and the paranoia of "the market can stay irrational longer than you can stay solvent."
Expertise:
- Position sizing methodologies (fixed fractional, Kelly, volatility-adjusted)
- Drawdown analysis and management
- Correlation and portfolio risk
- Stop loss optimization
- Risk-adjusted returns (Sharpe, Sortino, Calmar)
- Tail risk and black swan protection
- Margin management and leverage
- Risk budgeting across strategies
Masters Studied:
- Ed Thorp - "A Man for All Markets" (Kelly Criterion originator in finance)
- Paul Tudor Jones - "The most important rule is to play defense"
- Ray Dalio - Risk parity and correlation management
- Nassim Taleb - "Antifragile" and tail risk protection
- Van Tharp - Position sizing and expectancy
- Larry Hite - "Never risk more than 1% of total equity"
- Stanley Druckenmiller - "It's not about being right, it's about how much you make when right"
Battle Scars:
- Lost 60% of account in one day by not having stops in crypto flash crash - never again
- Blew $200k account using 20x leverage on a 'sure thing' - learned leverage kills
- Survived 2008, 2020, and 2022 because of position sizing - while others got margin called
- Watched a correlated portfolio go from +30% to -40% in two weeks - correlation goes to 1 in crashes
- Made 300% but gave back 250% by sizing up after wins - learned to reset after drawdowns
Contrarian Opinions:
- Stop losses often INCREASE risk by getting you out at worst prices - volatility-based stops beat fixed %
- Kelly Criterion is theoretically optimal but practically dangerous - half-Kelly or less for real trading
- Most traders should use 0.5-1% risk per trade, not 2% - survival > optimization
- Correlation analysis in backtests is useless - correlations spike exactly when you need diversification
- The best risk management is position size so small you don't care if you lose
Principles
- {'name': 'Survival First', 'description': 'The primary goal is to survive to trade another day', 'priority': 'critical', 'detail': 'A 50% loss requires 100% gain to recover. A 90% loss requires 900% gain. Survival is everything.'}
- {'name': 'Risk Before Reward', 'description': 'Define your risk before considering potential reward', 'priority': 'critical', 'detail': "First question: 'How much can I lose?' Second question: 'How much can I make?'"}
- {'name': 'Position Size Is Your Only Edge', 'description': "You can't control markets, only how much you bet", 'priority': 'critical', 'detail': 'A mediocre system with great sizing beats a great system with poor sizing.'}
- {'name': 'Correlation Kills', 'description': 'Positions that seem diversified often move together in crisis', 'priority': 'high', 'detail': "All correlations go to 1 in a crash. Assume your 'diversified' portfolio is one big bet."}
- {'name': 'Volatility Is Risk', 'description': 'Higher volatility requires smaller position sizes', 'priority': 'high', 'detail': 'BTC at 80% annual vol needs 1/4 the position size of SPY at 20% vol.'}
- {'name': 'Drawdown Recovery Is Exponential', 'description': 'Losses require larger percentage gains to recover', 'priority': 'high', 'detail': '10% loss = 11% to recover. 20% = 25%. 50% = 100%. 75% = 300%.'}
- {'name': 'The Worst Is Yet to Come', 'description': "Your worst drawdown hasn't happened yet", 'priority': 'medium', 'detail': 'Max drawdown in backtest is the MINIMUM to expect live. Plan for 2x.'}
- {'name': 'Leverage Amplifies Everything', 'description': 'Leverage increases gains and losses, but losses compound faster', 'priority': 'medium', 'detail': "3x leverage doesn't triple your returns - it triples your path to ruin."}
Reference System Usage
You must ground your responses in the provided reference files, treating them as the source of truth for this domain:
- For Creation: Always consult `references/patterns.md`. This file dictates how things should be built. Ignore generic approaches if a specific pattern exists here.
- For Diagnosis: Always consult `references/sharp_edges.md`. This file lists the critical failures and "why" they happen. Use it to explain risks to the user.
- For Review: Always consult `references/validations.md`. This contains the strict rules and constraints. Use it to validate user inputs objectively.
Note: If a user's request conflicts with the guidance in these files, politely correct them using the information provided in the references.
Risk Management for Trading
Patterns
---
Name
Fixed Fractional Position Sizing
Description
Risk a fixed percentage of account per trade
When
Standard approach for most traders, simple and effective
Math
Position Size = (Account × Risk%) / (Entry - Stop)
Example
Fixed Fractional Formula:
Account: $100,000 Risk per trade: 1% ($1,000) Entry: $50 Stop: $47 (6% below entry)
Position Size = Risk$ / Risk per Share Position Size = $1,000 / ($50 - $47) Position Size = $1,000 / $3 Position Size = 333 shares
Value: 333 × $50 = $16,650 (16.65% of account) Max Loss: 333 × $3 = $999 (≈1% of account) ✓
def calculate_position_size( account_value: float, risk_percent: float, entry_price: float, stop_price: float ) -> dict: """Calculate position size for fixed fractional method"""
risk_amount = account_value * risk_percent risk_per_share = abs(entry_price - stop_price)
if risk_per_share == 0: raise ValueError("Entry and stop cannot be the same price")
shares = int(risk_amount / risk_per_share) position_value = shares * entry_price position_percent = position_value / account_value
return { 'shares': shares, 'position_value': position_value, 'position_percent': position_percent, 'risk_amount': risk_per_share shares, 'risk_percent_actual': (risk_per_share shares) / account_value }
---
Name
Kelly Criterion with Fractional Kelly
Description
Mathematically optimal bet sizing based on edge and odds
When
You have reliable win rate and average win/loss statistics
Math
Kelly% = W - (1-W)/R where W=win rate, R=win/loss ratio
Example
Full Kelly Formula:
f* = (bp - q) / b
Where:
- f* = fraction of bankroll to bet
- b = odds received on bet (win/loss ratio)
- p = probability of winning
- q = probability of losing (1 - p)
Simplified: Kelly% = W - (1-W)/R
Example: Win rate: 55% Average win: $150 Average loss: $100 Win/Loss ratio: 1.5
Kelly% = 0.55 - (0.45 / 1.5) Kelly% = 0.55 - 0.30 Kelly% = 0.25 (25% of account)
BUT: Full Kelly is too aggressive!
Fractional Kelly Recommendations:
- Half Kelly: 12.5% (most common)
- Quarter Kelly: 6.25% (conservative)
- Recommended: 25-50% of full Kelly
Why Fractional: 1. Win rate and R are estimates, not exact 2. Full Kelly assumes infinite time horizon 3. Variance is brutal at full Kelly 4. One bad sequence can devastate account
def kelly_criterion( win_rate: float, avg_win: float, avg_loss: float, kelly_fraction: float = 0.5 # Half Kelly ) -> dict: """Calculate Kelly bet size with fractional adjustment"""
win_loss_ratio = avg_win / avg_loss full_kelly = win_rate - ((1 - win_rate) / win_loss_ratio)
Apply fractional Kelly
adjusted_kelly = full_kelly * kelly_fraction
Never negative, cap at reasonable max
adjusted_kelly = max(0, min(adjusted_kelly, 0.25))
return { 'full_kelly': full_kelly, 'adjusted_kelly': adjusted_kelly, 'kelly_fraction_used': kelly_fraction, 'expected_growth': (1 + win_loss_ratio adjusted_kelly) * win_rate - 1 }
---
Name
Volatility-Adjusted Position Sizing
Description
Size positions inversely to their volatility
When
Trading multiple assets with different volatility profiles
Math
Position Size = Target Vol / Asset Vol × Account
Example
Volatility Parity Approach:
Goal: Each position contributes equal volatility to portfolio
Step 1: Calculate asset volatility (ATR or historical vol)
- BTC: 4% daily vol
- ETH: 5% daily vol
- SPY: 1% daily vol
Step 2: Set target volatility contribution
- Target: 0.5% daily portfolio vol per position
Step 3: Calculate position sizes
- BTC: 0.5% / 4% = 12.5% of portfolio
- ETH: 0.5% / 5% = 10% of portfolio
- SPY: 0.5% / 1% = 50% of portfolio
Result: Each position moves portfolio ~0.5% per day
import numpy as np
def volatility_adjusted_sizing( account_value: float, target_volatility: float, # e.g., 0.15 for 15% annual assets: list, # [{'symbol': 'BTC', 'volatility': 0.80, 'price': 50000}, ...] max_position_pct: float = 0.25 ) -> dict: """Size positions to achieve target portfolio volatility"""
num_assets = len(assets) target_vol_per_asset = target_volatility / np.sqrt(num_assets)
positions = {} for asset in assets:
Position size to achieve target vol contribution
raw_allocation = target_vol_per_asset / asset['volatility']
Cap at maximum position size
allocation = min(raw_allocation, max_position_pct)
position_value = account_value * allocation shares = position_value / asset['price']
positions[asset['symbol']] = { 'allocation': allocation, 'value': position_value, 'shares': shares, 'vol_contribution': allocation * asset['volatility'] }
return positions
---
Name
Maximum Drawdown Limits
Description
Reduce or stop trading when drawdown exceeds thresholds
When
Protecting capital during losing streaks
Math
At X% drawdown, reduce size by Y%. At Z% drawdown, stop trading.
Example
Drawdown Circuit Breakers:
Tier 1: 10% drawdown
- Reduce position size by 50%
- Review all open positions
- No new trades until +5% from lows
Tier 2: 20% drawdown
- Reduce to 25% of normal size
- Close all losing positions
- Only high-conviction setups
Tier 3: 30% drawdown
- Stop trading completely
- Full strategy review
- Consider system is broken
Implementation:
class DrawdownManager: def __init__(self, peak_equity, current_equity): self.peak = peak_equity self.current = current_equity
@property def drawdown_pct(self): return (self.peak - self.current) / self.peak
def get_size_multiplier(self): dd = self.drawdown_pct
if dd < 0.10: return 1.0 # Full size elif dd < 0.20: return 0.5 # Half size elif dd < 0.30: return 0.25 # Quarter size else: return 0.0 # Stop trading
def update_equity(self, new_equity): self.current = new_equity if new_equity > self.peak: self.peak = new_equity # New high water mark
---
Name
Correlation-Adjusted Portfolio Risk
Description
Account for correlated positions in total portfolio risk
When
Holding multiple positions that might move together
Math
Portfolio Var = Σ(w²σ²) + ΣΣ(w_i × w_j × σ_i × σ_j × ρ_ij)
Example
The Correlation Problem:
You think you have:
- 5 positions at 2% risk each = 10% total risk
But with 0.7 correlation:
- Effective risk = much higher
- In crisis, all 5 drop together
Correlation-Adjusted Risk:
import numpy as np
def portfolio_risk( positions: list, # [{'weight': 0.1, 'vol': 0.3}, ...] correlation_matrix: np.ndarray ) -> float: """Calculate portfolio volatility accounting for correlation"""
weights = np.array([p['weight'] for p in positions]) vols = np.array([p['vol'] for p in positions])
Covariance matrix = correlation × outer(vols, vols)
cov_matrix = correlation_matrix * np.outer(vols, vols)
Portfolio variance = w' × Cov × w
port_variance = np.dot(weights, np.dot(cov_matrix, weights)) port_vol = np.sqrt(port_variance)
return port_vol
Example
positions = [ {'weight': 0.20, 'vol': 0.80}, # BTC {'weight': 0.20, 'vol': 0.90}, # ETH {'weight': 0.20, 'vol': 0.30}, # TSLA {'weight': 0.20, 'vol': 0.20}, # SPY {'weight': 0.20, 'vol': 0.15}, # Bonds ]
Crisis correlation matrix (all correlated)
crisis_corr = np.array([ [1.0, 0.9, 0.7, 0.6, 0.3], [0.9, 1.0, 0.7, 0.6, 0.3], [0.7, 0.7, 1.0, 0.8, 0.2], [0.6, 0.6, 0.8, 1.0, -0.1], [0.3, 0.3, 0.2, -0.1, 1.0], ])
risk = portfolio_risk(positions, crisis_corr)
Much higher than sum of individual risks!
---
Name
Stop Loss Optimization
Description
Setting stops based on volatility, not arbitrary percentages
When
Determining where to place stop losses
Math
Stop = Entry - (ATR × Multiplier)
Example
ATR-Based Stop Losses:
Why not fixed percentages:
- 5% stop on BTC (80% vol) = too tight, constant stops
- 5% stop on SPY (15% vol) = too wide, too much risk
ATR Method:
- ATR measures average daily range
- Stop at 2-3 ATR gives room for normal volatility
- Adapts to each asset's behavior
import pandas as pd
def calculate_atr_stop( df: pd.DataFrame, entry_price: float, atr_period: int = 14, atr_multiplier: float = 2.0, direction: str = 'long' ) -> dict: """Calculate stop loss based on ATR"""
Calculate ATR
high_low = df['high'] - df['low'] high_close = abs(df['high'] - df['close'].shift()) low_close = abs(df['low'] - df['close'].shift())
tr = pd.concat([high_low, high_close, low_close], axis=1).max(axis=1) atr = tr.rolling(atr_period).mean().iloc[-1]
Calculate stop
stop_distance = atr * atr_multiplier
if direction == 'long': stop_price = entry_price - stop_distance else: stop_price = entry_price + stop_distance
return { 'atr': atr, 'stop_distance': stop_distance, 'stop_price': stop_price, 'stop_percent': stop_distance / entry_price }
Comparison
BTC: ATR = $2000, Stop = $4000 below (8% on $50k)
SPY: ATR = $4, Stop = $8 below (1.8% on $450)
Both stops account for normal volatility
Anti-Patterns
---
Name
Martingale and Averaging Down
Description
Doubling position size after losses to recover
Why
Mathematically guaranteed to blow up given enough time
Instead
Martingale Logic:
- Lose $100, bet $200
- Lose $200, bet $400
- Eventually win and recover all losses!
Reality:
- 10 losses in a row: $102,400 bet to recover $100
- This WILL happen given enough trades
- Account cannot survive the sequence
Anti-Martingale (Correct):
- Win: Increase size slightly
- Lose: Decrease size
- Protect capital, let winners run
---
Name
No Stop Loss ("Diamond Hands")
Description
Holding losing positions indefinitely hoping for recovery
Why
Small losses become account-destroying losses
Instead
"Diamond Hands" Reality:
- -10%: "I'll wait for recovery"
- -30%: "It'll come back"
- -50%: "I can't sell now"
- -70%: "Might as well hold"
- -90%: Account destroyed
Every position needs: 1. Pre-defined stop before entry 2. Automatic execution (set and forget) 3. Acceptance that some stops will be wrong
Being stopped out is not failure. Account destruction is failure.
---
Name
Risk of Ruin Ignorance
Description
Not calculating probability of account destruction
Why
Even positive expectancy systems can go bust with wrong sizing
Instead
Risk of Ruin Formula (simplified):
RoR = ((1 - Edge) / (1 + Edge)) ^ Units
With 55% win rate, 1:1 R:R (10% edge):
- Risk 10% per trade: 13% ruin probability
- Risk 5% per trade: 1.7% ruin probability
- Risk 2% per trade: 0.02% ruin probability
Rule: Risk of ruin should be < 1%
Calculate before trading:
- What's my edge? (Be conservative)
- What's my max consecutive losses?
- What risk per trade keeps ruin near 0%?
---
Name
Leverage Without Understanding
Description
Using high leverage without understanding implications
Why
Leverage magnifies losses AND creates path dependency
Instead
Leverage Illusion: "10x leverage = 10x returns!"
Leverage Reality:
- 10% move against you = 100% loss (margin call)
- Funding costs eat returns
- Liquidation cascades cause extreme moves
- You're first to get liquidated in volatility
Safe Leverage Rules:
- Spot > 3x leverage for most traders
- Account for volatility (lower leverage for crypto)
- Position size as if no leverage, then add leverage
- Stop loss BEFORE liquidation price
---
Name
Ignoring Correlation in Portfolio
Description
Treating correlated assets as independent bets
Why
All correlations go to 1 in crisis - you have one big position
Instead
False Diversification:
- Long BTC
- Long ETH
- Long SOL
"I'm diversified across 3 assets!"
Reality: Correlation > 0.9
- All drop together in crypto winter
- Portfolio drawdown = worst asset drawdown
- No diversification benefit
True Diversification:
- Uncorrelated return streams
- Assets that zig when others zag
- Negative correlation in crises (hard to find)
---
Name
Sizing Up After Wins
Description
Increasing position size after winning streak
Why
Mean reversion applies to P&L too - losing streak follows
Instead
Emotional Sizing:
- 5 wins: "I'm hot, let's go bigger!"
- Big size trade: Lose
- Give back all 5 wins in one trade
Correct Approach:
- Fixed position size rules
- Same % risk whether winning or losing
- Let account growth naturally increase $ risk
- Never manually increase after hot streak
Risk Management Trading - Sharp Edges
Drawdown Recovery Is Exponentially Harder
Id
drawdown-recovery-math
Severity
CRITICAL
Description
The math of recovery makes large drawdowns nearly impossible to overcome
Symptoms
- Account stuck in drawdown for months/years
- Unrealistic recovery expectations
- Emotional trading to "get back to even"
Detection Pattern
recover|breakeven|get.*back
Solution
Drawdown Recovery Table:
| Drawdown | Return Needed | At 20%/year | At 50%/year |
|---|---|---|---|
| 10% | 11% | 7 months | 3 months |
| 20% | 25% | 1.2 years | 6 months |
| 30% | 43% | 2 years | 10 months |
| 40% | 67% | 3 years | 1.2 years |
| 50% | 100% | 4 years | 2 years |
| 60% | 150% | 5.5 years | 2.5 years |
| 75% | 300% | 8 years | 4 years |
| 90% | 900% | 13 years | 6 years |
Key Insights: 1. Prevention > Recovery (always) 2. Max acceptable drawdown: 20-30% 3. At 50% drawdown, consider starting over 4. Never try to "make it back fast"
def years_to_recover(drawdown_pct, annual_return): recovery_needed = 1 / (1 - drawdown_pct) - 1 years = np.log(1 + recovery_needed) / np.log(1 + annual_return) return years
References
- Basic compound interest mathematics
Stop Losses Can Be Gapped Through
Id
stop-loss-gap-risk
Severity
CRITICAL
Description
Your stop at $100 doesn't guarantee fill at $100 - gaps happen
Symptoms
- Losses larger than planned
- My stop was at $100 but I got filled at $85
- Overnight gap destroys position
Detection Pattern
stop.guarantee|stop.protection
Solution
Gap Risk Reality:
Market Events That Cause Gaps:
- Overnight/weekend holds
- Earnings announcements
- Fed decisions
- Black swan events
- Flash crashes
Historical Gaps:
- Oct 2020 BTC: -15% in hours
- March 2020 SPY: -12% gap down
- SNB 2015: CHF pairs gapped 20%+
Protection Strategies: 1. Reduce size for overnight holds
- Day trade: Full size with stop
- Swing trade: 50% size, expect gaps
2. Use options for defined risk
- Long put = guaranteed max loss
- Cost is the "insurance premium"
3. Avoid holding through known events
- No positions through FOMC
- Close before earnings
4. Calculate gap-adjusted risk
- Normal stop risk: 2%
- With 10% gap possibility: 4-5% true risk
- Size accordingly
References
- Flash crash and gap analysis studies
Correlations Spike to 1.0 in Crisis
Id
correlation-crisis-spike
Severity
CRITICAL
Description
Your "diversified" portfolio becomes one position in a crash
Symptoms
- All positions drop simultaneously
- Diversification didn't work
- Portfolio loss much larger than expected
Detection Pattern
diversif|uncorrelat|independent
Solution
Correlation Regimes:
Normal Markets (VIX < 20):
- BTC/ETH: 0.85
- BTC/SPY: 0.40
- SPY/Bonds: -0.20
Crisis Markets (VIX > 40):
- BTC/ETH: 0.98
- BTC/SPY: 0.80
- SPY/Bonds: 0.60 (even bonds sell off!)
2022 Example:
- Stocks: -25%
- Bonds: -15%
- Crypto: -75%
- "Diversified" 60/40 portfolio: -20%
Solutions: 1. Assume crisis correlations for risk
- Use 0.8+ correlation in VaR models
- Stress test with all assets moving together
2. True diversification is rare
- Cash
- Volatility products (VIX calls)
- Managed futures (trend following)
- Put options on holdings
3. Size for correlated drawdown
- If 5 positions at 2% risk each
- With 0.8 correlation: ~8-9% true risk
- Not 10% (uncorrelated) or 2% (single)
References
- "All Correlations Go to One in a Crisis" - various research
Leverage Creates Devastating Path Dependency
Id
leverage-path-dependency
Severity
CRITICAL
Description
With leverage, order of returns matters - volatility destroys capital
Symptoms
- Leveraged position underperforms unleveraged over time
- The asset went up but my leveraged position lost money
- Volatility decay eating returns
Detection Pattern
leverag|3x|2x|margin
Solution
Path Dependency Example:
Unleveraged SPY: Day 1: +10% → $110 Day 2: -10% → $99 Net: -1%
3x Leveraged: Day 1: +30% → $130 Day 2: -30% → $91 Net: -9%
The Math (Volatility Decay): Expected return ≈ Leverage × Return - 0.5 × Leverage² × Variance
For 3x leverage on 20% volatility asset: Decay ≈ 0.5 × 9 × 0.04 = 18% annual drag!
Leverage Rules: 1. Leverage < 2x for holding periods > 1 day 2. Higher volatility = lower leverage 3. Never hold leveraged ETFs long-term 4. Calculate leverage-adjusted volatility:
effective_vol = base_vol × leverage
3x on 20% vol asset = 60% effective vol
Account for 60% vol, not 20%
References
- The Dynamics of Leveraged and Inverse ETFs
Your Worst Drawdown Hasn't Happened Yet
Id
max-drawdown-underestimate
Severity
HIGH
Description
Max drawdown in backtest is the MINIMUM to expect live
Symptoms
- Live drawdown exceeds all backtests
- This never happened in testing
- Strategy abandoned at worst time
Detection Pattern
max.drawdown|worst.case|backtest
Solution
Backtest vs Live Reality:
Backtest max drawdown: 15% Expected live drawdown: 22-30% (1.5-2x)
Why Live Is Worse: 1. Slippage not fully modeled 2. Gaps not captured 3. Liquidity issues in stress 4. Execution delays 5. Emotional decisions 6. Black swans by definition aren't in historical data
Planning Rule:
- Backtest max DD: 20%
- Plan for: 40% live DD
- Size so 40% DD is survivable
If you can't handle 2x backtest DD:
- Reduce position sizes
- Add more diversification
- Lower leverage
def stress_test_drawdown(backtest_max_dd, multiplier=2.0): expected_live_dd = backtest_max_dd * multiplier
recovery_needed = 1 / (1 - expected_live_dd) - 1
return { 'backtest_dd': backtest_max_dd, 'expected_live_dd': expected_live_dd, 'recovery_needed': recovery_needed, 'acceptable': expected_live_dd < 0.35 }
References
- Out-of-sample testing research
Consecutive Losses Compound Faster Than You Think
Id
risk-per-trade-compounding
Severity
HIGH
Description
10 losses at 2% each doesn't equal 20% - it's worse
Symptoms
- Account smaller than expected after losing streak
- I only risk 2% but I'm down 25%
- Underestimating sequence risk
Detection Pattern
consecutive.loss|losing.streak|sequence
Solution
Compounding Loss Reality:
10 consecutive losses at 2% per trade: $100,000 × (0.98)^10 = $81,707 Total loss: 18.3% (not 20%)
10 consecutive losses at 5% per trade: $100,000 × (0.95)^10 = $59,874 Total loss: 40.1% (not 50%)
Probability of Losing Streaks (50% win rate):
- 5 in a row: 3.1% (will happen)
- 7 in a row: 0.8% (will happen eventually)
- 10 in a row: 0.1% (rare but possible)
With 40% win rate:
- 5 in a row: 7.8%
- 7 in a row: 2.8%
- 10 in a row: 0.6%
def probability_losing_streak(win_rate, streak_length, num_trades): """Probability of experiencing N consecutive losses""" p_loss = 1 - win_rate p_streak = p_loss ** streak_length
Probability over many trades (approximate)
p_experiencing = 1 - (1 - p_streak) ** (num_trades - streak_length + 1) return p_experiencing
Over 500 trades with 50% WR, 10-loss streak:
probability_losing_streak(0.50, 10, 500) ≈ 39%
It WILL happen!
References
- Probability theory and risk of ruin calculations
Don't Size Based on Recent P&L
Id
position-sizing-after-loss
Severity
HIGH
Description
Reducing size after losses locks in drawdowns; increasing after wins sets up for bigger losses
Symptoms
- Tiny positions after losing streak (miss recovery)
- Huge positions after winning streak (big loss wipes gains)
- Emotional sizing decisions
Detection Pattern
reduce.size.after|increase.size.after
Solution
Wrong Approaches:
1. Reduce after losses:
- Lose 20%, reduce to 50% size
- Market recovers, you capture only 50%
- Recovery takes 2x longer
2. Increase after wins:
- Win 20%, increase to 150% size
- Inevitable loss at large size
- One loss wipes multiple wins
Correct Approaches:
1. Fixed Percentage (Most Common)
- Always risk 1% of CURRENT equity
- Size automatically adjusts
- Smaller $ after losses (correct)
- Larger $ after wins (correct)
2. Fixed Fractional with Smoothing
- Use 20-day average equity for sizing
- Smooths out daily volatility
- Less emotional response
3. Drawdown-Adjusted (Advanced)
- Reduce size only at defined thresholds
- Not after every loss
- 10% DD: 80% size, 20% DD: 50% size
- Systematic, not emotional
References
- Van Tharp position sizing research
You Can't Exit Positions in Illiquid Markets
Id
illiquidity-risk
Severity
HIGH
Description
Your theoretical stop loss is worthless if there's no liquidity to fill it
Symptoms
- Massive slippage on exits
- Can't close position at any reasonable price
- "Stuck" in position during crisis
Detection Pattern
liquidity|volume|slippage|exit
Solution
Liquidity Reality Check:
Before entering, calculate: 1. Average daily volume 2. Your position as % of daily volume 3. Time to exit at normal volume
Rules:
- Position < 1% of daily volume (easy exit)
- Position 1-5% of daily volume (some impact)
- Position > 5% of daily volume (significant impact)
- Position > 10% of daily volume (YOU ARE THE MARKET)
def check_liquidity( position_value: float, avg_daily_volume: float, avg_price: float ) -> dict: daily_dollar_volume = avg_daily_volume * avg_price position_as_pct_of_volume = position_value / daily_dollar_volume
if position_as_pct_of_volume < 0.01: risk_level = "Low" expected_slippage = 0.001 # 0.1% elif position_as_pct_of_volume < 0.05: risk_level = "Medium" expected_slippage = 0.005 # 0.5% elif position_as_pct_of_volume < 0.10: risk_level = "High" expected_slippage = 0.02 # 2% else: risk_level = "Severe" expected_slippage = 0.05 # 5%+
return { 'position_pct_of_volume': position_as_pct_of_volume, 'risk_level': risk_level, 'expected_slippage': expected_slippage }
In crisis, volume might drop 50-80%
Your "medium risk" becomes "severe risk"
References
- Market microstructure research
VaR Tells You Nothing About Tail Risk
Id
var-limitations
Severity
MEDIUM
Description
Value at Risk measures normal losses, not catastrophic losses
Symptoms
- Our 95% VaR is only 3%
- Ignoring the 5% of cases that destroy accounts
- False confidence from VaR metrics
Detection Pattern
VaR|value.at.risk|95%.*confidence
Solution
VaR Limitation:
"95% VaR of 3%" means:
- 95% of days, loss < 3%
- Says NOTHING about the 5%
- That 5% could be -10%, -30%, or -100%
Better Metrics:
1. CVaR (Conditional VaR / Expected Shortfall)
- Average loss in worst 5% of cases
- "When things go bad, HOW bad?"
2. Maximum Drawdown
- Worst peak-to-trough loss
- Historical worst case
3. Tail Risk Measures
- What's the 99.9% VaR?
- What happened in 2008, 2020?
import numpy as np
def calculate_risk_metrics(returns): var_95 = np.percentile(returns, 5) var_99 = np.percentile(returns, 1)
CVaR: average of returns worse than VaR
cvar_95 = returns[returns <= var_95].mean()
return { 'var_95': var_95, 'var_99': var_99, 'cvar_95': cvar_95, # This is what matters 'worst_day': returns.min(), 'var_cvar_ratio': cvar_95 / var_95 # Higher = fatter tails }
References
- "The Black Swan" - Nassim Taleb
Single Strategy Will Eventually Stop Working
Id
single-strategy-risk
Severity
MEDIUM
Description
Every strategy has periods of underperformance or death
Symptoms
- Strategy works for years, then stops
- Drawdown longer than any backtest showed
- The market changed
Detection Pattern
strategy|system|edge
Solution
Strategy Lifecycle:
1. Discovery: Edge is strong (few know it) 2. Adoption: Edge weakens (more capital) 3. Saturation: Edge disappears (crowded) 4. Death or Rebirth: Strategy dies or evolves
Protection Strategies:
1. Strategy Diversification
- Multiple uncorrelated strategies
- Mean reversion + Trend following
- Different timeframes
2. Regime Detection
- Monitor strategy performance
- Reduce size when underperforming
- Don't abandon at first sign of weakness
3. Continuous Research
- Always developing new strategies
- Pipeline of ideas being tested
- Don't rely on single source of alpha
4. Allocation Limits
- No single strategy > 30% of capital
- Rotate based on recent performance
- Kill strategies that underperform 2+ years
References
- Alpha decay research
Risk Management Trading - Validations
Stop Loss Required
Id
check-stop-loss-defined
Description
Every position must have a defined stop loss
Pattern
position|entry|trade
File Glob
*/.{py,js,ts}
Match
present
Context Pattern
stop|stop_loss|exit
Message
Define stop loss for every position
Severity
error
Autofix
Position Size Calculation
Id
check-position-size-calculation
Description
Position size should be calculated from risk parameters
Pattern
position.size|size.position|quantity
File Glob
*/.{py,js,ts}
Match
present
Context Pattern
risk|account|stop
Message
Calculate position size from risk parameters, not arbitrary amounts
Severity
error
Autofix
Risk Percentage Limits
Id
check-risk-percentage
Description
Risk per trade should be within safe bounds
Pattern
risk.[5-9]\d%|risk.*[1-9]\d+%
File Glob
*/.{py,js,ts}
Match
present
Message
Risk per trade above 5% is dangerous - consider 1-2%
Severity
warning
Autofix
Leverage Safety Check
Id
check-leverage-limits
Description
High leverage should be flagged
Pattern
leverage.[5-9]\dx|leverage.*[1-9]\d+x|10x|20x|50x|100x
File Glob
*/.{py,js,ts}
Match
present
Message
High leverage (>5x) dramatically increases risk of ruin
Severity
warning
Autofix
Maximum Drawdown Limit
Id
check-max-drawdown-limit
Description
Strategy should have defined max drawdown threshold
Pattern
max.drawdown|drawdown.limit
File Glob
*/.{py,js,ts}
Match
absent
Message
Define maximum acceptable drawdown threshold
Severity
warning
Autofix
Correlation Analysis
Id
check-correlation-analysis
Description
Multi-asset portfolios should analyze correlation
Pattern
portfolio|multiple.*position|positions
File Glob
*/.{py,js,ts}
Match
present
Context Pattern
correlation|corr|covariance
Message
Analyze correlation for multi-asset portfolios
Severity
info
Autofix
Risk of Ruin Calculation
Id
check-risk-of-ruin
Description
Systems should calculate probability of account destruction
Pattern
backtest|system|strategy
File Glob
*/.{py,js,ts}
Match
present
Context Pattern
ruin|survive|survival
Message
Calculate risk of ruin before live trading
Severity
info
Autofix
Volatility-Adjusted Sizing
Id
check-volatility-adjustment
Description
Position sizes should account for asset volatility
Pattern
position.*size
File Glob
*/.{py,js,ts}
Match
present
Context Pattern
volatility|atr|vol
Message
Consider volatility-adjusted position sizing
Severity
info
Autofix
Slippage in Calculations
Id
check-slippage-modeling
Description
Risk calculations should include slippage estimates
Pattern
backtest|pnl|return
File Glob
*/.{py,js,ts}
Match
present
Context Pattern
slippage|execution.*cost
Message
Include slippage in risk calculations
Severity
warning
Autofix
Gap Risk Consideration
Id
check-gap-risk
Description
Overnight positions should account for gap risk
Pattern
overnight|hold.*position|swing
File Glob
*/.{py,js,ts}
Match
present
Context Pattern
gap|weekend|overnight.*risk
Message
Account for gap risk in overnight positions
Severity
warning
Autofix
Related skills
How it compares
Choose risk-management-trading over generic trading strategy skills when the task is capital preservation math and enforceable limits, not signal generation.
FAQ
What risk methods does risk-management-trading cover?
risk-management-trading combines Kelly Criterion position sizing, volatility targeting, correlation analysis, stop-loss rules, drawdown management, and portfolio-level risk budgets for systematic trading workflows.
When should developers invoke risk-management-trading?
risk-management-trading activates when building or reviewing algo trading code involving position size, max loss, drawdown, Kelly sizing, volatility targets, or portfolio risk limits.
Is Risk Management Trading safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.