Kill-switch and risk control engine for live trading bots
Project description
๐ก๏ธ Trading Risk Engine
A Python library with kill-switch and risk controls for live trading bots.
Enforce position sizing, drawdown limits, and leverage controls โ before your account pays the price.
๐ Quick Navigation
The Problem ยท Why Backtests Fail ยท What Is This? ยท Outcomes ยท Who Is This For? ยท Quick Example ยท Freqtrade Integration ยท Tests ยท Roadmap ยท License
๐ The Problem No One Talks About
Without proper risk controls, even a perfect strategy can wipe out your account.
Most trading bots don't fail because the strategy is bad.
They fail because risk is unmanaged.
- Fixed position sizing that ignores account state
- Unlimited drawdown with no emergency stop
- Correlated exposure across multiple positions
- No kill switch when things go wrong
These are the real reasons accounts go to zero โ often after successful backtests.
"I backtested for 6 months, went live, and lost 40% in 2 weeks."
โ Every algo trader, at some point
โ Why Backtests Didn't Save You
| What You Thought | What Actually Happened |
|---|---|
| "My backtest was profitable" | Lookahead bias inflated results |
| "I used 1% risk per trade" | Fixed sizing ignored changing equity |
| "I had a stop loss" | No global risk context across trades |
| "The strategy was tested" | No kill switch when live conditions diverged |
Strategies don't kill accounts. Uncontrolled risk does.
๐ฏ What Is This?
Trading Risk Engine is a strategy-agnostic risk layer that sits between your signals and execution, enforcing hard risk limits โ even when your strategy is wrong.
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Your Strategy โ
โ (Freqtrade / Custom Bot) โ
โโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Trading Risk Engine โ โ This Layer
โ โ
โ โ Can I afford this trade? โ
โ โ Am I overexposed? โ
โ โ Should I stop trading? โ
โ โ
โโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Execution Layer โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ What It Prevents (Outcomes)
| Before | After |
|---|---|
| "I lost 30% before I noticed" | Never lose more than 15% per session (configurable) |
| "Position sizes were random" | Every trade risks exactly 1% of equity (configurable) |
| "One bad week wiped months of gains" | Trading stops automatically at drawdown limit |
| "I was over-leveraged without knowing" | Leverage is capped at 3x before orders are placed (configurable) |
| "I had 5 correlated positions open" | Exposure limits prevent concentration risk |
This is not about making more money. It's about keeping what you have.
๐ง How It Works (High Level)
The engine evaluates every trade request against your defined limits:
- Kill Switch Check โ Is trading enabled, or are we in shutdown?
- Drawdown Check โ Are we within account drawdown limits?
- Session Check โ Have we lost too much today?
- Exposure Check โ Do we have room for another position?
- Size Calculation โ What's the correct position size for this stop loss?
- Leverage Check โ Would this position exceed our leverage limit?
Any failure = trade rejected. No exceptions. No overrides.
๐ค Who Is This For?
โ This is for:
- Algo traders running live bots
- Developers using Freqtrade, Backtrader, or custom systems
- Traders who understand: profits don't matter if risk is broken
- Anyone who has blown an account and is tired of repeating it
โ This is NOT for:
- Signal sellers looking for marketing buzzwords
- "Guaranteed profit" seekers
- Beginners who don't understand drawdown
- People who think backtests equal live results
If you're looking for a magic profit button, look elsewhere.
๐ฆ What You Get
Core Components
| Component | Function |
|---|---|
| RiskConfig | Define your limits (drawdown, leverage, positions) |
| RiskState | Track runtime state (equity, peak, exposure) |
| RiskEngine | Evaluate trades: APPROVE / REJECT / SHUTDOWN |
Guards (Risk Controls)
| Guard | What It Does |
|---|---|
| DrawdownGuard | Triggers kill switch at max drawdown |
| LeverageGuard | Prevents over-leveraged positions |
| ExposureGuard | Limits concurrent positions |
Position Sizing
| Sizer | Method |
|---|---|
| FixedRiskSizer | Classic % risk per trade formula |
| VolatilitySizer | ATR-based sizing (coming in v1.1) |
Adapters
| Adapter | Integration |
|---|---|
| GenericAdapter | Plain Python usage |
| FreqtradeAdapter | Drop-in Freqtrade integration |
โก Quick Example
from risk_engine import RiskConfig, RiskState, RiskEngine
from risk_engine.interfaces.position import TradeRequest, PositionSide
# Define your risk limits
config = RiskConfig(
max_account_drawdown=0.15, # 15% max drawdown โ kill switch
risk_per_trade=0.01, # 1% risk per trade
max_leverage=3.0, # Max 3x leverage
max_open_positions=3, # Max 3 concurrent trades
)
# Initialize with current account state
state = RiskState(current_equity=10000, equity_peak=10000)
engine = RiskEngine(config, state)
# Evaluate a trade
decision = engine.evaluate_trade(TradeRequest(
symbol="BTC/USDT",
side=PositionSide.LONG,
entry_price=50000,
stop_loss=49000,
))
if decision.is_approved:
print(f"โ
Trade approved: {decision.position_size} units")
else:
print(f"โ Trade rejected: {decision.reason}")
# Check kill switch status after losses
print(f"Kill switch active: {not state.trading_enabled}")
๐ Freqtrade Integration
Drop-in integration with Freqtrade strategies:
from risk_engine.adapters.freqtrade import FreqtradeRiskAdapter, FreqtradeConfig
class MyStrategy(IStrategy):
def __init__(self, config):
super().__init__(config)
self.risk_adapter = FreqtradeRiskAdapter(
FreqtradeConfig(
max_account_drawdown=0.15,
risk_per_trade=0.01,
)
)
def bot_start(self, **kwargs):
self.risk_adapter.on_bot_start(self.wallets.get_total_stake_amount())
def custom_stake_amount(self, pair, current_rate, proposed_stake, side, **kwargs):
return self.risk_adapter.get_stake_amount(
pair=pair,
entry_price=current_rate,
stoploss_price=current_rate * (1 - abs(self.stoploss)),
proposed_stake=proposed_stake,
side=side,
)
Full example: freqtrade_example.py
๐งช Tested & Reliable
========================= 61 tests passed =========================
| Test Suite | Coverage |
|---|---|
| Config validation | โ |
| Drawdown + kill switch | โ |
| Position sizing | โ |
| Leverage guards | โ |
| Full engine integration | โ |
| Fail-closed behavior | โ |
The engine is tested for the scenarios that matter most:
- Losing streaks that hit drawdown limits
- Concurrent position limits
- Manual reset after shutdown
- Error handling (fail-closed)
๐ License
Free for personal experimentation and research.
A commercial license is required for live trading, paid services, or client deployments.
๐ง Commercial licensing: Get a License
๐บ๏ธ Roadmap
| Version | Features |
|---|---|
| v1.0 โ | Kill switch, Fixed sizing, Leverage guard, Freqtrade adapter |
| v1.1 | Session exposure limits, DCA caps, Volatility sizing |
| Pro | Correlation analysis, Regime detection |
Remember: This engine protects capital. It doesn't make money.
That's your strategy's job โ if it survives long enough to prove itself.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file trading_risk_engine-1.0.0.tar.gz.
File metadata
- Download URL: trading_risk_engine-1.0.0.tar.gz
- Upload date:
- Size: 34.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3fbcae4b8e6a9d70db1361b0347bc81d8ba12df0934e1640b76f2fc470b5e352
|
|
| MD5 |
4fefee0cc0a09b65efa9645c00141a98
|
|
| BLAKE2b-256 |
5ed271f25d71661849a11f953f65dcb0aec6413fc81dc9d11eda4b45c1ccefc4
|
File details
Details for the file trading_risk_engine-1.0.0-py3-none-any.whl.
File metadata
- Download URL: trading_risk_engine-1.0.0-py3-none-any.whl
- Upload date:
- Size: 34.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
35a912a4c133384aa11b87198466b41c9ac6cbc1fd68e6e550179303ae6363f0
|
|
| MD5 |
0b8d761567be1078579b20e7d81ac697
|
|
| BLAKE2b-256 |
12c45120338a66893e6634f2c4050f520792be86456971d5082a3c35724747b9
|