fix: grid capital-safety and churn fixes (leverage, order validation, dust orders, rebuild cooldown)
Summary
Fixes a set of engineering defects in the AI grid trading bot that were surfaced by cross-checking production logs against live exchange state. The defects caused excessive order churn, fee drag, and silent divergence between recorded and actual order state. This PR is an engineering fix only — it does not change the trading strategy itself.
Defects fixed
1. Leverage applied twice (capital safety).
grid_math.calculate_grid_config already produces amount_per_grid as a leveraged notional value, but order_manager multiplied it by leverage again when sizing the order — so real exposure per grid was leverage× the intended value. A few fills would saturate margin and subsequent orders were rejected for insufficient margin.
Fix: execute_long_limit/execute_short_limit gain an amount_is_notional flag. The grid path uses the notional convention (size = notional / price, no extra leverage multiply); the perpetual-agent path keeps the existing margin convention by default, so it is backward compatible.
2. Rejected orders treated as placed.
Order placement only checked the envelope status == "ok". Hyperliquid returns status: "ok" even when an individual order is rejected, with the real error nested under statuses[].error. Rejected orders (insufficient margin, below min notional) were logged as PLACED, so the bot's view of its own resting orders diverged from the exchange.
Fix: both the limit-order and reduce-order paths now use check_order_success to inspect the nested statuses; rejected orders are no longer counted as success / coverage / PLACED.
3. Dust reduce-only orders.
The reduce-only exit-order size could degrade to the contract step size, far below the exchange minimum notional, so it was always rejected — yet logged as placed, leaving the protective exit layer effectively empty.
Fix: enforce a minimum notional (size × price ≥ exchange minimum) before placing; ceil-round the size to the step so quantization can't drop it back under the minimum; dynamically merge layers for small positions so coverage is still reached; stop placing when even the full remaining position can't form a valid order.
4. Rebuild churn — cooldown was dead code.
grid_rebuild_cooldown_seconds was assigned in __init__ but never read by _should_rebuild_grid; combined with the grid interval re-centering on the current price every cycle, the vast majority of cycles triggered a full cancel-and-replace and resting orders rarely survived to fill.
Fix: _should_rebuild_grid now honors the cooldown (timestamp persisted to survive the auto-restart loop). Safety triggers (first build, insufficient open orders, invalid params) bypass the cooldown.
5. LLM output hardening (grid_agent).
- Parse failures now fall back to
KEEP_GRIDinstead of forcing a NEUTRAL full rebuild (don't amplify an LLM failure into a trading action). actionis validated against a whitelist; invalid values (an invalid enum was observed in production) are no longer passed through.confidenceis now propagated (previously dropped, so the monitoring metric was always 0).- Fixed a literal
\nin the prompt formatter.
6. Graceful shutdown (grid_main).
grid_main had no SIGTERM/SIGINT handling, so a container stop could interrupt the cancel/replace sequence mid-flight and leave an unprotected position. Added signal handling: the handler stops the scheduler non-blocking, and the main thread's finally block waits for the in-flight cycle to finish and flushes the cloud logger.
7. Decision-log status.
main.py hard-coded status=SUCCESS, so an agent error was recorded as a successful decision and also written into the learning history. Status is now derived from the decision/error, and error decisions are excluded from the history. grid_main records ERROR for any non-whitelisted action.
Review feedback addressed
Follow-up commit applies five reviewer suggestions: balance-API-failure fallback to KEEP_GRID; ceil sizing for the min-notional guard; dynamic layer merging for small positions; non-blocking scheduler shutdown inside the signal handler; and defaulting the rebuild timestamp to avoid None in state.
Expected effect
- Margin utilization returns to the intended range; orders are no longer rejected en masse for insufficient margin.
- Full-rebuild frequency drops sharply, so resting orders are no longer cancelled before they can fill — substantially reducing fee drag.
- The reduce-only protection layer holds real orders instead of rejected dust.
- Monitoring is no longer blind to LLM failures and order rejections.
Tests
- New
tests/test_grid_capital_safety.pycovering the notional sizing, nested-status rejection, min-notional / layer-merge reduce orders, rebuild cooldown (including safety-trigger bypass), and the GridAgent fallbacks (parse failure, invalid action, balance-API failure). - Updated
tests/test_grid_manager_exit_orders.pymocks to match the real interfaces (check_order_success,amount_is_notional). - Full suite: 601 passed / 2 skipped.
Notes / follow-ups
- This is an engineering fix, not a strategy change. Validate on testnet before mainnet.
- The audit also found that the backtest harness does not model the exchange minimum notional, margin constraints, fees, or slippage, and has some look-ahead — so the current backtest cannot validate this change. Fixing backtest fidelity is recommended as a follow-up PR.
- Interval hysteresis (skip rebuild while price remains inside the prior range) is not implemented here; the cooldown is the primary churn brake and hysteresis can be a follow-up.
🤖 Generated with Claude Code
Thanks for the review — all five suggestions are addressed in d0fb24a:
- Balance API failure → KEEP_GRID:
grid_agentnow returnsKEEP_GRIDwhenget_available_balance_info().status != "ok", so a balance/network failure can no longer cancel the existing grid and leave it empty. - Ceil sizing for min notional: reduce-order size is now
math.ceil(size / step) * step, so step quantization can't drop it back below the minimum notional; the slight excess is safe underreduce_only. - Dynamic layer merge:
target_layers_leftis capped byremaining / min_notional_size, so small positions merge into fewer valid orders and still reach full coverage. - Non-blocking shutdown in the signal handler: the handler now calls
scheduler.shutdown(wait=False); thefinallyblock performs thewait=Truegraceful drain, so the handler no longer blocks the main thread. last_rebuild_tsdefault: defaults to0.0to keepNoneout of persisted state.
Added tests for the balance-failure fallback and the small-position layer-merge path. Full suite: 601 passed / 2 skipped, lint + format clean.
Addressed the latest round in b92b1f5:
P0 — mock interface alignment
mock_order_manager.execute_long_limit/execute_short_limit now accept amount_is_notional (matching production), so a future grid backtest path passing amount_is_notional=True won't TypeError. When set, the mock sizes as notional/price (no leverage multiply), mirroring production. Added a signature regression test.
P1 — return-value change (acknowledged)
execute_*_limit now returns {"success": False, ...} instead of None on a rejected/invalid order. All current callers use the res and res.get("success") guard, which handles both; the dict form additionally surfaces the rejection reason. Documented in the commit message.
Nits
- Added an up-front
limit_price <= 0guard inexecute_*_limitto prevent a divide-by-zero in the notional sizing path (+ test). HL_MIN_NOTIONAL_USD: added a TODO to source it from per-asset exchange metadata instead of a hardcoded constant.- Signal handler: comment clarifying
scheduler.running/shutdown(wait=False)are non-blocking and safe from the main-thread handler. - Test mocks: comment on the
staticmethod-binding fragility.
Full suite: 603 passed / 2 skipped, lint + format clean.