Execution Flow
Live Order Execution
Creating Orders
Orders are placed via the Lighter SignerClient with Immediate-Or-Cancel (IOC) time-in-force.src/server/features/trading/createPosition.ts:456
Key Parameters:
baseAmount: Quantity scaled by market decimals (e.g., 1.5 BTC → 150000000)price: Limit price with 1% buffer for market orders (prevents rejection)isAsk:falsefor LONG (buy),truefor SHORT (sell)orderType:ORDER_TYPE_MARKET(0) for immediate executiontimeInForce:IMMEDIATE_OR_CANCELfills immediately or cancels unfilled portion
Fill Tracking
ThetrackFill function uses exponential backoff polling to verify order execution and extract actual fill details.
src/server/features/trading/fillTracker.ts:72
Transaction Status Codes:
waitForTransaction(): Poll transaction until status is EXECUTED (3)checkOrderStatus(): Query OrderAPI for fill amount and average price- Fallback: If order status unavailable, fetch recent trades from AccountAPI
- Conservative assumption: If all else fails, assume full fill (logged as warning)
Partial Fills
Partial fills occur when order book depth is insufficient to fill the entire order.- System accepts partial fills and creates position with actual filled quantity
- Logs warning:
Partial fill: requested=X, filled=Y - Database stores actual filled quantity, not requested quantity
Simulated Execution
The simulator matches orders against cached order book snapshots using a realistic matching engine.src/server/features/simulator/orderMatching.ts:21
Matching Algorithm:
- Identify aggressing side (buy → asks, sell → bids)
- Walk order book levels from best price
- Fill against each level until quantity exhausted or book empty
- Calculate weighted average price from all fills
- Return partial fill if remaining quantity > 0
- Actual order book depth from Lighter API
- Partial fills when liquidity insufficient
- Volume-weighted average price calculation
- Slippage modeling through multi-level fills
Position Scaling
When opening a position for a symbol with an existing OPEN position of the same side, the system scales into the position rather than creating a new one.src/server/features/trading/createPosition.ts:569
Weighted Average Entry Price:
- Existing position: 1.0 BTC @ $50,000
- New execution: 0.5 BTC @ $51,000
- Result: 1.5 BTC @ $50,333 (weighted average)
When scaling in, SL/TP orders are cancelled and replaced with new orders reflecting the updated quantity and average entry price.
Closing Positions
Closing a position places a reverse order (LONG → sell, SHORT → buy) withreduceOnly: true.
src/server/features/trading/closePosition.ts:226
Close Flow:
- Cancel any existing SL/TP orders
- Place reverse market order with
reduceOnly: true - Track fill to get actual exit price
- Calculate realized P&L
- Update
Orderstable: setstatus=CLOSED,exitPrice,realizedPnl,closedAt
Error Handling
Order Creation Failures
Order Creation Failures
Causes:
- Invalid market parameters
- Insufficient account balance
- Exchange connectivity issues
- Return error in
PositionResult - Log error message
- Do not persist to database
- Agent receives error and can retry with different parameters
Transaction Timeouts
Transaction Timeouts
Causes:
- Network congestion
- Exchange processing delays
- Transaction stuck in pending state
waitForTransaction()times out after 30 seconds- Return error: “Transaction tracking failed: timeout”
- Position creation aborted
- Agent can retry in next invocation
Fill Verification Failures
Fill Verification Failures
Causes:
- Order API unavailable
- Order not indexed yet
- Authentication token issues
- Try fallback: fetch recent trades from AccountAPI
- If fallback fails: assume full fill (logged as warning)
- Position persisted with conservative assumption
- Monitor logs for frequent fallback usage
Partial Fills
Partial Fills
Causes:
- Insufficient order book depth
- Large order size relative to liquidity
- Accept partial fill
- Create position with actual filled quantity
- Log warning for monitoring
- Database stores actual quantity, not requested
Best Practices
Always Track Fills
Never assume order execution succeeded. Always use
trackFill() to verify actual filled quantity and average price.Handle Partial Fills
Design your system to gracefully handle partial fills. Store actual filled quantities, not requested amounts.
Use Reduce-Only for Closes
Always set
reduceOnly: true when closing positions to prevent accidental position flips.Cancel SL/TP Before Close
Always cancel existing SL/TP orders before manually closing a position to prevent race conditions.
Next Steps
Position Management
Learn about position tracking and exit plans
Risk Controls
Explore risk management and position sizing

