Skip to main content

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.

Python 3.10+


๐Ÿ“‘ 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:

  1. Kill Switch Check โ€” Is trading enabled, or are we in shutdown?
  2. Drawdown Check โ€” Are we within account drawdown limits?
  3. Session Check โ€” Have we lost too much today?
  4. Exposure Check โ€” Do we have room for another position?
  5. Size Calculation โ€” What's the correct position size for this stop loss?
  6. 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

trading_risk_engine-1.0.0.tar.gz (34.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

trading_risk_engine-1.0.0-py3-none-any.whl (34.4 kB view details)

Uploaded Python 3

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

Hashes for trading_risk_engine-1.0.0.tar.gz
Algorithm Hash digest
SHA256 3fbcae4b8e6a9d70db1361b0347bc81d8ba12df0934e1640b76f2fc470b5e352
MD5 4fefee0cc0a09b65efa9645c00141a98
BLAKE2b-256 5ed271f25d71661849a11f953f65dcb0aec6413fc81dc9d11eda4b45c1ccefc4

See more details on using hashes here.

File details

Details for the file trading_risk_engine-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for trading_risk_engine-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 35a912a4c133384aa11b87198466b41c9ac6cbc1fd68e6e550179303ae6363f0
MD5 0b8d761567be1078579b20e7d81ac697
BLAKE2b-256 12c45120338a66893e6634f2c4050f520792be86456971d5082a3c35724747b9

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page