Risk Controls

Risk Management API
for AI Trading Agents

Autonomous trading agents can generate impressive returns โ€” but without risk controls, a single bad market event can destroy weeks of profit. Purple Flea's risk management API lets you define hard limits your agent can never exceed: drawdown caps, position size limits, daily loss halts, and correlation guards โ€” enforced server-side, in real time.

Add Risk Controls โ†’ View Docs

Why Hard Limits Matter

Soft limits โ€” thresholds checked by your agent's own code โ€” fail under adverse conditions. If your agent crashes, hangs, or receives corrupted price data, its own logic cannot protect it. Purple Flea enforces risk limits server-side: they fire even if your agent is offline.

The 3am Problem
A trading agent running unattended at 3am enters a volatile market event. Its position loses 8% in 20 minutes. Without hard server-side limits, the agent may keep trading โ€” compounding losses. Purple Flea's risk API fires a halt automatically when your drawdown threshold is breached, regardless of what your agent code is doing at that moment.
๐Ÿ”’
Server-Side Enforcement
Risk limits are checked before every order is executed โ€” not after. Your agent cannot exceed them even if it tries. No client-side bypass possible.
โšก
Sub-5ms Latency
Risk checks run in under 5 milliseconds, co-located with the order execution engine. No perceptible latency added to your trading pipeline.
๐Ÿ“Š
Real-Time Monitoring
Query current exposure, drawdown depth, and open position count at any time. Build your own dashboard on top of the risk metrics API.
๐Ÿ””
Webhook Alerts
Get notified the instant a limit is approached (75% threshold) or breached. Integrate with Slack, PagerDuty, or your own incident pipeline.

Risk Primitives

Four core controls that cover the vast majority of trading risk scenarios. Combine them to build a risk profile matching your strategy's tolerance.

๐Ÿ“‰
Drawdown
Max Drawdown Limit
Define a maximum percentage loss from the account's all-time peak. If the account value drops below this threshold, all open orders are cancelled and new order submission is blocked until a human or orchestrator manually lifts the halt.

This is the most important single risk control for an autonomous agent. A 15% max drawdown on a $1,000 account means the agent halts if the account reaches $850 โ€” protecting $850 of capital regardless of what the market does next.
current_drawdown: 4.2% / limit: 15%
โš–๏ธ
Position Sizing
Position Size Cap
Cap the maximum allocation to any single trade as a percentage of the total account. A 20% position cap means no single entry can exceed 20% of current account equity.

This prevents the most common failure mode in autonomous trading: an agent that "discovers" a high-conviction signal and allocates 90% of its account to a single position. Even a correct directional bet can liquidate if sized improperly due to short-term volatility.
largest_position: 12% / limit: 20%
๐Ÿ›‘
Daily Controls
Daily Loss Limit
Set a hard cap on the maximum USD loss allowed within a single calendar day (UTC reset). When the daily P&L falls to the threshold, trading halts for the remainder of the day and resumes automatically at midnight UTC.

Daily loss limits are essential for agents trading high-volatility markets. A bad morning session should not be able to compound into a bad week. The daily reset gives the agent a clean slate while containing single-day damage.
daily_pnl: -$147 / limit: -$200
๐Ÿ”—
Correlation
Correlation Limit
Prevent over-concentration in correlated assets. BTC and ETH move together more than 85% of the time during volatile periods. An agent holding both at full size is effectively running 2x exposure to a single risk factor.

Purple Flea's correlation engine uses 30-day rolling correlations to flag positions that would create excessive correlated exposure. Set a maximum combined correlation-adjusted notional and the API blocks new entries that would breach it.
corr_exposure: 87% / limit: 70%

Python Example

Configure a complete risk profile for your trading agent in a single call, then query real-time exposure before every trade decision.

agent_risk_setup.py Python
# pip install purpleflea
import purpleflea

risk = purpleflea.RiskClient(api_key="YOUR_KEY")

# Configure risk limits for a trading agent
limits = risk.set_limits(
    agent_id="agent_trader_001",
    max_drawdown_pct=15,          # Stop if down 15% from peak
    max_position_pct=20,          # No single position > 20% of account
    daily_loss_limit_usd=200,     # Halt if daily loss exceeds $200
    max_open_positions=5,         # Max 5 concurrent positions
    allowed_markets=["BTC-PERP", "ETH-PERP", "SOL-PERP"]  # Whitelist
)

print(f"Risk profile: {limits['profile_id']}")

# Check current risk exposure before placing a trade
exposure = risk.check_exposure(agent_id="agent_trader_001")
print(f"Current drawdown: {exposure['current_drawdown_pct']:.1f}%")
print(f"Open positions: {exposure['open_position_count']}")
print(f"Safe to trade: {exposure['can_open_new_position']}")

# Register webhook for limit breach notifications
risk.set_webhook(
    agent_id="agent_trader_001",
    url="https://your-server.com/risk-webhook",
    events=["drawdown.warning", "drawdown.breach",
            "daily_loss.breach", "trading.halted"]
)
Exposure Check Response
{
  "agent_id": "agent_trader_001",
  "can_open_new_position": true,
  "current_drawdown_pct": 4.2,
  "daily_pnl_usd": -147.50,
  "open_position_count": 2,
  "largest_position_pct": 12.3,
  "correlation_exposure_pct": 55.1,
  "limits_status": "within_bounds",
  "checked_at": "2026-03-04T09:22:11Z"
}

Risk Event Webhooks

When limits are approached or breached, Purple Flea fires structured webhook events โ€” so your agents, orchestrators, and monitoring systems can respond immediately.

Event Types
Fired in order of severity as thresholds are approached
WARNING
drawdown.warning
Fired when drawdown reaches 75% of the configured limit. Early warning to alert human oversight.
BREACH
drawdown.breach
Max drawdown exceeded. All orders cancelled. New orders blocked. Requires manual lift or auto-resume after cooldown.
BREACH
daily_loss.breach
Daily loss limit hit. Trading suspended until midnight UTC. Positions retained but no new entries allowed.
WARNING
correlation.elevated
Correlated exposure approaching threshold. New positions in correlated assets will be blocked.
RESUME
trading.resumed
Trading re-enabled after a halt โ€” either via manual lift or automatic daily reset.
Webhook Payload Example
{
  "event": "drawdown.breach",
  "agent_id": "agent_trader_001",
  "timestamp": "2026-03-04T03:41:12Z",
  "data": {
    "peak_equity_usd": 1000.00,
    "current_equity_usd": 847.50,
    "drawdown_pct": 15.25,
    "limit_pct": 15.00,
    "action_taken": "trading_halted",
    "open_positions_closed": 3
  },
  "resume_condition": "manual_lift_required"
}
Escalation Integrations
Route risk webhooks to Slack for immediate human visibility, PagerDuty for on-call escalation, or your orchestrator agent for automated response โ€” such as hedging remaining positions, sending alerts to stakeholders, or logging the event to a shared incident ledger.

Kelly Criterion Integration

Optimal position sizing is not arbitrary โ€” it can be calculated mathematically. Purple Flea integrates the Kelly Criterion directly into the order submission flow, so your agents can size positions optimally rather than guessing.

f* = (bp - q) / b
f* = fraction of capital to risk
b = net odds received on the bet
p = probability of winning
q = probability of losing (1 - p)
The Kelly formula tells you exactly what fraction of your account to risk on any trade, given your estimate of the win probability and the payoff ratio. Over-betting (more than Kelly) leads to faster ruin even when your edge is real. Under-betting is safe but leaves returns on the table. See the full Kelly Criterion guide.
Kelly Sizing in Practice
# Agent estimates 60% win rate,
# 2:1 reward-to-risk ratio

sizing = risk.kelly_size(
    agent_id="agent_trader_001",
    win_probability=0.60,
    reward_to_risk=2.0,
    kelly_fraction=0.5  # Half-Kelly for safety
)

print(f"Optimal size: {sizing['position_pct']:.1f}% of account")
print(f"USD amount: ${sizing['position_usd']:.2f}")
print(f"Ruin probability: {sizing['ruin_prob_pct']:.3f}%")

# Output:
# Optimal size: 10.0% of account
# USD amount: $100.00
# Ruin probability: 0.002%

Backtesting Risk Profiles

Before deploying a risk profile to live trading, test it against historical data. Purple Flea's backtest API replays your agent's strategy through historical market conditions and reports exactly when each risk limit would have fired.

Backtest API Example
result = risk.backtest(
    agent_id="agent_trader_001",
    strategy_id="strat_momentum_v2",
    from_date="2025-01-01",
    to_date="2025-12-31",
    risk_profile={
        "max_drawdown_pct": 15,
        "max_position_pct": 20,
        "daily_loss_limit": 200
    }
)

for event in result['limit_breach_events']:
    print(f"{event['date']}: {event['type']}")
2025 Backtest Results โ€” BTC Momentum Strategy
Risk Profile Max DD Hit Halts Triggered Annual Return
No limits -42.3% 0 +87%
DD 30%, pos 40% -28.1% 2 +71%
DD 15%, pos 20% -12.4% 5 +58%
DD 10%, pos 10% -7.2% 9 +34%
Tighter limits reduce drawdown at the cost of some upside โ€” the right balance depends on your capital and risk tolerance.

8 Risk Dimensions

Purple Flea's risk engine monitors all major dimensions of trading risk simultaneously, in real time.

๐Ÿ“‰
Max Drawdown
% loss from peak equity
โš–๏ธ
Position Size
% of account per trade
๐Ÿ—“๏ธ
Daily Loss
Max USD loss per day
๐Ÿ”—
Correlation
Correlated asset exposure
๐Ÿ”ข
Open Positions
Max concurrent trades
๐ŸŒŠ
Volatility Filter
Pause during extreme VIX
๐Ÿฆ
Leverage Cap
Max total notional exposure
๐Ÿ“‹
Market Whitelist
Restrict to approved symbols
8
Risk dimensions monitored
<5ms
Risk check latency
Real-time
Exposure monitoring
1yr
Historical backtest range
Ship With Confidence

Add Risk Controls to Your Agent

Every autonomous trading agent should have hard risk limits before it goes live. Get a free API key and configure your agent's risk profile today โ€” it takes under 5 minutes.