Skip to content

Engine tick flow ​

The engine does not wait for a user to click "Execute" — scripts/cron-tick.ts is triggered by a systemd timer every 30s, iterating over all status = ACTIVE strategies.

Engine Tick

Before every tick: position reconciliation ​

Before running any strategy, each (exchange, user) group diffs the exchange's positions against the local ledger (src/lib/position-reconciliation.ts).

Why it's needed: if you close a position by hand in the OKX / Binance app, or it gets liquidated, the exchange no longer holds it while the local ledger still has the row (a "ghost position"). The engine then believes it still holds — stop-loss and take-profit run against a position that doesn't exist, and the strategy can never open a new position again.

Reconciliation does exactly one thing: it clears the rows where the exchange has no exposure at all, and writes one SYSTEM event to the log explaining how the position disappeared.

⚠️ It does not book P&L. We don't know the fill price (manual close? liquidation?), and inventing a number would pollute the win rate. So the trade never shows up in the P&L stats — it shows up in /logs.

Bounds (deliberately conservative — a false positive costs far more than a miss):

  • The exchange's position is account-level (several of your strategies share one account) → "the amounts don't match" is not enough to act; only "no exposure whatsoever" is;
  • If the exchange can't be reached, the whole round is skipped — "don't know" is not "it isn't there";
  • Only live positions are reconciled: a paper position may be nothing but a local simulation (the fallback when sandbox execution fails).

The 11 steps of one tick ​

1. Load + lock ​

ts
strategy = await prisma.strategy.update({
  where: { id, executionLock: false },
  data:  { executionLock: true },
});

Double-lock mechanism:

  • In-process Set (inflightExecutions): prevents re-entrancy in the same process
  • DB lock (executionLock): prevents multi-instance collisions (currently single-instance)
  • Module-load watchdog: when HMR re-evaluates a module, the previous instance may still hold the lock; the watchdog cleans orphan executionLock: true records

2. Fetch candles ​

ts
candles = await withTimeout(
  TradeService.fetchCandles(...),
  15_000,
  `fetchCandles(${symbol}, ${interval})`
);

withTimeout is a wall-clock timeout; the inner promise is not cancelled (ccxt doesn't support AbortSignal). FETCH_CANDLES_TIMEOUT_MS = 15_000 is configured centrally in src/lib/config.ts.

3. Compute indicators ​

ts
const rsi  = calculateRSI(prices, 14);
const macd = calculateMACD(prices, 12, 26, 9);
// ...

Indicators are cached by fingerprint — when multiple rules in the same tick reference the same indicator, it is only computed once.

4. Evaluate RuleTree ​

ts
const signal = evaluateRuleTree(buyRules, indicatorSnapshot);
// → 'BUY' | 'SELL' | 'HOLD' | error

A RuleTree is an AND/OR-nested tree; leaf nodes are comparisons like left-indicator operator right-value.

5. SL/TP check ​

ts
const longRiskMessage  = existingLong  ? evaluateRisk(existingLong)  : null;
const shortRiskMessage = existingShort ? evaluateRisk(existingShort) : null;

Each side is evaluated on its own: long and short are assessed separately, and whichever side triggers is the side that gets closed.

⚠️ This used to be const watch = existingShort ?? existingLong — so with both sides open, the long side had no stop-loss at all (short won). That contradicts the "enforced SL/TP" promise: users believed both sides were protected while one was running naked.

Stop-loss and take-profit are independent too: the else if (TP > 0) used to hang off "is a stop-loss configured" rather than off "did the stop-loss trigger" — so a strategy with only a take-profit never took profit. When one candle touches both, the stop-loss wins (the order within the wick isn't knowable from the candle, so take the conservative one).

6. Dispatch order ​

ts
const response = await TradeService.execute(user.address, request);

TradeService automatically derives positionSide / reduceOnly from the TradeIntent — the adapter always sees consistent fields.

7. Normalize ccxt error ​

ts
const norm = normalizeExchangeError(err, 'okx');
return { action: 'ERROR', message, remediationCode: norm.code };

The code is an ExchangeErrorCode string, see Error Normalization.

8. Write StrategyEventLog ​

Every tick result is written to StrategyEventLog, with remediationCode (nullable).

9. 1-Click fix (browser) ​

If the event has remediationCode, StrategyTerminal immediately window.dispatchEvent('qt:open-settings'), and the Sidebar auto-opens the Configure modal.

10. Close → ProfitRecord ​

After the close path completes:

  • Write Order (SELL/MARKET/FILLED)
  • Compute PnL by side (gross PnL minus the entry and exit fees — the same formula the backtest engine uses)
  • Write ProfitRecord
  • broadcastProfit(userId, ...) push SSE

11. finally: release lock ​

ts
finally {
  await prisma.strategy.updateMany({
    where: { id: strategyId, executionLock: true },
    data:  { executionLock: false },
  });
}

updateMany is constrained by where: { executionLock: true } to avoid clearing a lock a newer instance has acquired.

Time budgets ​

PhaseTimeout
Fetch candles15s
Per-tick total budget (EXECUTION_BUDGET_MS)30s
Lock expiry (STALE_LOCK_AGE_MS)45s — must be > cron interval
Watchdog scan cycle60s

Key invariants ​

  1. In-process Set + DB lock + watchdog — none of them alone is enough
  2. Indicator memoization by fingerprint — prevents same-tick duplicate computation
  3. Intent dispatch before adapter — engine invariant
  4. Errors carry remediationCode — the 1-click UX depends on it
  5. Side-aware PnL — LONG and SHORT close formulas must not get mixed
  6. finally releases the lock — must run even if the try block throws

TodoAI · Turn trading ideas into automated strategies