180 lines
5.2 KiB
Markdown
180 lines
5.2 KiB
Markdown
# Exchange Kernel API
|
|
|
|
A Kubernetes-style declarative API for managing orders across different exchanges.
|
|
|
|
## Architecture Overview
|
|
|
|
The Exchange Kernel maintains two separate views of order state:
|
|
|
|
1. **Desired State (Intent)**: What the strategy kernel wants
|
|
2. **Actual State (Reality)**: What currently exists on the exchange
|
|
|
|
A reconciliation loop continuously works to bring actual state into alignment with desired state, handling errors, retries, and edge cases automatically.
|
|
|
|
## Core Components
|
|
|
|
### Models (`models.py`)
|
|
|
|
- **OrderIntent**: Desired order state from strategy kernel
|
|
- **OrderState**: Actual current order state on exchange
|
|
- **Position**: Current position (spot, margin, perp, futures, options)
|
|
- **Asset**: Asset holdings with metadata
|
|
- **AccountState**: Complete account snapshot (balances, positions, margin)
|
|
- **AssetMetadata**: Asset type descriptions and trading parameters
|
|
|
|
### Events (`events.py`)
|
|
|
|
Order lifecycle events:
|
|
- `OrderSubmitted`, `OrderAccepted`, `OrderRejected`
|
|
- `OrderPartiallyFilled`, `OrderFilled`, `OrderCanceled`
|
|
- `OrderModified`, `OrderExpired`
|
|
|
|
Position events:
|
|
- `PositionOpened`, `PositionModified`, `PositionClosed`
|
|
|
|
Account events:
|
|
- `AccountBalanceUpdated`, `MarginCallWarning`
|
|
|
|
### Base Interface (`base.py`)
|
|
|
|
Abstract `ExchangeKernel` class defining:
|
|
|
|
**Command API**:
|
|
- `place_order()`, `place_order_group()` - Create order intents
|
|
- `cancel_order()`, `modify_order()` - Update intents
|
|
- `cancel_all_orders()` - Bulk cancellation
|
|
|
|
**Query API**:
|
|
- `get_order_intent()`, `get_order_state()` - Query single order
|
|
- `get_all_intents()`, `get_all_orders()` - Query all orders
|
|
- `get_positions()`, `get_account_state()` - Query positions/balances
|
|
- `get_symbol_metadata()`, `get_asset_metadata()` - Query market info
|
|
|
|
**Event API**:
|
|
- `subscribe_events()`, `unsubscribe_events()` - Event notifications
|
|
|
|
**Lifecycle**:
|
|
- `start()`, `stop()` - Kernel lifecycle
|
|
- `health_check()` - Connection status
|
|
- `force_reconciliation()` - Manual reconciliation trigger
|
|
|
|
### State Management (`state.py`)
|
|
|
|
- **IntentStateStore**: Storage for desired state (durable, survives restarts)
|
|
- **ActualStateStore**: Storage for actual exchange state (ephemeral cache)
|
|
- **ReconciliationEngine**: Framework for intent→reality reconciliation
|
|
- **InMemory implementations**: For testing/prototyping
|
|
|
|
## Standard Order Model
|
|
|
|
Defined in `schema/order_spec.py`:
|
|
|
|
```python
|
|
StandardOrder(
|
|
symbol_id="BTC/USD",
|
|
side=Side.BUY,
|
|
amount=1.0,
|
|
amount_type=AmountType.BASE, # or QUOTE for exact-out
|
|
limit_price=50000.0, # None for market orders
|
|
time_in_force=TimeInForce.GTC,
|
|
conditional_trigger=ConditionalTrigger(...), # Optional stop-loss/take-profit
|
|
conditional_mode=ConditionalOrderMode.UNIFIED_ADJUSTING,
|
|
reduce_only=False,
|
|
post_only=False,
|
|
iceberg_qty=None,
|
|
)
|
|
```
|
|
|
|
## Symbol Metadata
|
|
|
|
Markets describe their capabilities via `SymbolMetadata`:
|
|
|
|
- **AmountConstraints**: Min/max order size, step size
|
|
- **PriceConstraints**: Tick size, tick spacing mode (fixed/dynamic/continuous)
|
|
- **MarketCapabilities**:
|
|
- Supported sides (BUY, SELL)
|
|
- Supported amount types (BASE, QUOTE, or both)
|
|
- Market vs limit order support
|
|
- Time-in-force options (GTC, IOC, FOK, DAY, GTD)
|
|
- Conditional order support (stop-loss, take-profit, trailing stops)
|
|
- Advanced features (post-only, reduce-only, iceberg)
|
|
|
|
## Asset Types
|
|
|
|
Comprehensive asset type system supporting:
|
|
- **SPOT**: Cash markets
|
|
- **MARGIN**: Margin trading
|
|
- **PERP**: Perpetual futures
|
|
- **FUTURE**: Dated futures
|
|
- **OPTION**: Options contracts
|
|
- **SYNTHETIC**: Derived instruments
|
|
|
|
Each asset has metadata describing contract specs, settlement, margin requirements, etc.
|
|
|
|
## Usage Pattern
|
|
|
|
```python
|
|
# Create exchange kernel for specific exchange
|
|
kernel = SomeExchangeKernel(exchange_id="binance_main")
|
|
|
|
# Subscribe to events
|
|
kernel.subscribe_events(my_event_handler)
|
|
|
|
# Start kernel
|
|
await kernel.start()
|
|
|
|
# Place order (creates intent, kernel handles execution)
|
|
intent_id = await kernel.place_order(
|
|
StandardOrder(
|
|
symbol_id="BTC/USD",
|
|
side=Side.BUY,
|
|
amount=1.0,
|
|
amount_type=AmountType.BASE,
|
|
limit_price=50000.0,
|
|
)
|
|
)
|
|
|
|
# Query desired state
|
|
intent = await kernel.get_order_intent(intent_id)
|
|
|
|
# Query actual state
|
|
state = await kernel.get_order_state(intent_id)
|
|
|
|
# Modify order (updates intent, kernel reconciles)
|
|
await kernel.modify_order(intent_id, new_order)
|
|
|
|
# Cancel order
|
|
await kernel.cancel_order(intent_id)
|
|
|
|
# Query positions
|
|
positions = await kernel.get_positions()
|
|
|
|
# Query account state
|
|
account = await kernel.get_account_state()
|
|
```
|
|
|
|
## Implementation Status
|
|
|
|
✅ **Complete**:
|
|
- Data models and type definitions
|
|
- Event definitions
|
|
- Abstract interface
|
|
- State store framework
|
|
- In-memory stores for testing
|
|
|
|
⏳ **TODO** (Exchange-specific implementations):
|
|
- Concrete ExchangeKernel implementations per exchange
|
|
- Reconciliation engine implementation
|
|
- Exchange API adapters
|
|
- Persistent state storage (database)
|
|
- Error handling and retry logic
|
|
- Monitoring and observability
|
|
|
|
## Next Steps
|
|
|
|
1. Create concrete implementations for specific exchanges (Binance, Uniswap, etc.)
|
|
2. Implement reconciliation engine with proper error handling
|
|
3. Add persistent storage backend for intents
|
|
4. Build integration tests
|
|
5. Add monitoring/metrics collection
|