Skip to content

Risk management ​

Risk control is TodoAI's most serious part. Even if your strategy logic is wrong, risk control can save you.

Two layers ​

1. Global risk (/risk page) ​

Hard caps on the entire account:

FieldDefaultEffect
Max drawdown protection (%)20When total equity drawdown exceeds this, all strategies auto-stop and positions are market-closed
Max leverage limit (x)1Per-trade leverage cap (effective in futures mode)
Default stop-loss (%)2Auto-filled stop-loss for new strategies
Default take-profit (%)4Same for take-profit

Triggering max drawdown is the last resort — once triggered, all strategies STOPPED, all open positions market-closed. Use with care.

2. Per-trade risk (in strategy) ​

Each strategy independently sets:

  • Stop Loss (%): forced close when loss reaches this percentage
  • Take Profit (%): forced close when profit reaches this percentage
  • Trade Amount: per-order size (USDT)

These percentages are based on entry price, not the latest price since open.

Mandatory SL/TP ​

The engine checks every candle:

ts
if (position.side === 'LONG') {
  if (currentLow <= stopLossPrice) → close
  if (currentHigh >= takeProfitPrice) → close
} else {
  // SHORT: mirror logic
  if (currentHigh >= stopLossPrice) → close
  if (currentLow <= takeProfitPrice) → close
}

After triggering, the entire position is market-closed — no partial close.

Cooldown ​

Any fill in any direction (open or close) starts a 60s cooldown window:

ts
export const CROSS_SIDE_COOLDOWN_SECONDS = 60;

During this window, any new trade is blocked regardless of direction. This prevents the "just stopped out, immediately reverse" emotional pattern.

Exchange-side stop-loss custody ​

A dead engine must not mean a dead stop-loss. Since 2026-11, every filled entry simultaneously places a conditional stop order on the exchange (OKX conditional algo / Binance STOP_MARKET):

  • The order credentials (stopLossPrice / stopOrderId) are stored on the position and reconciled every tick
  • If the quantokx process crashes, the server loses network, or the engine is killed outright — the exchange-side stop survives
  • The local engine demotes itself to "accelerator + observer"; the exchange is the airbag
  • Closing (manual / panic / signal) cancels the stop order in the same breath — no orphan orders; reconciliation cleans up any that slip through
  • Support matrix: OKX spot + futures ✓; Binance futures only (spot has no stop-market — skipped automatically, the local stop takes over)
  • A failed stop order never rolls back the entry — the position already exists, so a SYSTEM event says "this position only has the local stop" and the next tick's reconciliation re-places it

User-level kill switch ​

Two server-enforced hard guards on the /risk page (no agent, no caller can bypass them):

FieldEffect
Max daily loss (USDT)Aggregates today's REAL losses on a UTC day boundary; once exceeded, all new entries are refused
Max total exposure (USDT)Once current open exposure exceeds this, new entries are refused

Deliberate design boundaries:

  • OPEN only, never CLOSE — stop-losses, closes and panic execute under any circumstances
  • No auto-panic — triggering stops the bleeding (no more exposure growth) but the decision to flatten stays with the user; auto market-closing would fill the user at the worst price
  • Fail-open on aggregation errors (the worst case of a broken guard is no guard, not a frozen account)

Trade explanation cards (decision audit) ​

Every row in the trade logs page has a "Why" button that expands the real snapshot taken at decision time:

  • Which rules hit and what the factor values were (including the rules that missed — explaining "why nothing happened")
  • The decision candle, effective SL/TP, and the risk trigger (e.g. Stop Loss triggered at …)
  • Data comes from the same source as execution (same cache, same domain core) — numbers are never invented; legacy orders explicitly say "no decision data"

Panic close all ​

Sidebar bottom → red button next to Disconnect (also on top of /trade):

  • Immediately stop all ACTIVE strategies
  • Market orders for all open positions (Real)
  • Simulate price for all open positions (Paper)
  • Write ProfitRecord, push SSE

When to use:

  • Market regime changed, strategy didn't anticipate
  • Unsure what the strategy is currently doing
  • Stepping away and don't want it to keep running

Idempotency lock ​

The engine is single-instance + systemd timer, but a slow tick could still overlap with the next one. The engine has two layers of re-entrancy defense:

  • In-process Set (inflightExecutions): when the same strategyId is already running, return HOLD
  • DB lock (executionLock): if a previous process crashed leaving executionLock=true orphans, the watchdog cleans them at boot

Invariant: no two ticks ever execute the same strategy concurrently.

Encryption key rotation ​

⚠️ Don't change ENCRYPTION_KEY casually. Run the migration script first, or all stored user API keys will fail to decrypt:

bash
# 1. Update ENCRYPTION_KEY in .env.production
# 2. Run migration (safe to run while live, no downtime)
npx tsx scripts/migrate-encryption.ts --old-key="<previous key>"
# 3. After "DONE succeeded=N failed=0" appears, restart the service

The migration script is idempotent — safe to re-run, only processes records not yet at the current version.

User typeMax drawdownPer-trade SLPer-trade TP
Newbie10%1%2%
Normal15%2%4%
Experienced20%3%6%
Never going liveN/AN/AN/A

TodoAI · Turn trading ideas into automated strategies