Skip to content

OrderExecutionManager

Orchestrates trade execution with a three-phase commit: alert pre-registration, transaction commit, and old alert cleanup.

Purpose

OrderExecutionManager is the primary entry point for opening and closing positions. It is a stateless orchestrator that delegates all state management to specialized managers while owning the execution flow, error boundaries, and consistency guarantees.

High-Level Design

Three-Phase Commit Pattern

The core executeOrder method ensures consistency between position state and PriceAlert registrations:

┌─────────────────────────────────────────────────────────────────────┐
│                        executeOrder()                               │
│                                                                     │
│  ┌───────────────────────┐                                          │
│  │ Phase 1:              │  Register liquidation, SL, TP alerts     │
│  │ Pre-register Alerts   │  Store alert IDs + instance on position  │
│  │                       │  ⚠ ABORT entire order on failure         │
│  └──────────┬────────────┘                                          │
│             │ success                                               │
│  ┌──────────▼────────────┐                                          │
│  │ Phase 2:              │  transactionSync {                       │
│  │ Atomic Transaction    │    Position netting (3-case algorithm)   │
│  │                       │    Apply PnL + fee to balance            │
│  │                       │    Update volume tier, trade stats       │
│  │                       │    Persist trade, save/delete position   │
│  │                       │  }                                       │
│  └──────────┬────────────┘                                          │
│             │                                                       │
│  ┌──────────▼────────────┐                                          │
│  │ Phase 3:              │  Deregister old alerts (non-critical)    │
│  │ Best-Effort Cleanup   │  Sync to PublicTradesFeed                │
│  │                       │  Update AccountValueTracker coefficients │
│  │                       │  ⚠ Failures logged, never block          │
│  └───────────────────────┘                                          │
└─────────────────────────────────────────────────────────────────────┘

Why three phases? Phase 1 failure aborts everything (no orphaned positions without alerts). Phase 3 failures are non-critical (orphaned alerts don't affect trading). This is a safety-first pattern where the critical path never depends on cleanup success.

Immediate vs Pending Execution

Every order targets a deterministic timestamp (Math.floor(Date.now() / 1000)). This is never "latest available price" -- always a specific second. This enables retry idempotency: re-executing the same order always gets the same price.

                  handleOpenPositionRPC / handleClosePositionRPC


                        ┌───────────────────────────────┐
                        │ PriceFetchManager             │
                        │ fetchPriceForOrder(timestamp) │
                        └───────────┬───────────────────┘

                    ┌───────────────┴───────────────┐
                    │                               │
             Price Available                Price Unavailable
                    │                               │
                    ▼                               ▼
        ┌────────────────────┐         ┌───────────────────────────┐
        │ Validate & Execute │         │ PendingOrderManager       │
        │ executeOrder()     │         │ createPendingOrder()      │
        │ → Three-phase      │         │ → Reserve margin in DB    │
        │   commit           │         │ → Register price arrival  │
        └────────────────────┘         │   alert with PriceAlert   │
                    │                  └───────────────────────────┘
                    ▼                               │
         { status: "EXECUTED" }           { status: "PENDING" }

                                        (later, when price arrives)


                                        PriceAlert → onPriceArrival()
                                        → PendingOrderManager executes
                                        → Three-phase commit

Fee Adjustment

Orders always execute, even with insufficient balance for the full fee:

actualFee = min(calculatedFee, max(availableBalance, 0))

This prevents order rejection due to rounding or marginal balance shortfalls.

Alert Instance Load Balancing

10 PriceAlert instances (0-9) are available per geo-location. On each order execution, an instance is selected and stored with the position. All subsequent alert operations (SL, TP, liquidation watch) route to that same instance, enabling correct deregistration later.

Challenge MLL Detection After Close

handleClosePositionRPC performs a post-execution MLL check via checkAccountValueForChallenge(). This catches a subtle edge case: a position closes profitably (challenge passes), but unrealized losses on other positions push real account value below MLL. The check can revert a PASSED challenge to FAILED.

Edge Cases & Error Handling

  • Fee adjusted to available balance: orders always execute even if fee cannot be fully paid.
  • Phase 1 failure aborts the entire order (no partial state).
  • Phase 3 failures are logged but non-critical (orphaned alerts are harmless).
  • Close-all cancels pending OPEN orders first to prevent new positions during close.
  • Partial close validates remaining position >= min order size.
  • checkAccountValueForChallenge can revert a PASSED challenge to FAILED if real account value is below MLL.
  • Public feed sync is fire-and-forget in production, awaited in testing.
  • Pending orders from a previous account session are rejected via accountId mismatch (stale alert validation).

See Also