Architecture Deep Dive
A detailed look at the internal architecture powering GRID's delta-managed liquidity strategy.
System Overview
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Grid Liquidity Bot β
β ββββββββββββββββββ ββββββββββββββββββ β
β β GridCoordinatorβββββββΊβPositionActors β β
β β (orchestrator)β β(per position) β β
β βββββββββ¬βββββββββ ββββββββββ¬ββββββββ β
β β β β
β βββββββββΌβββββββββ ββββββββββββΌββββββββ β
β βLiquidityManagerβ β BalanceActor β β
β β(Orca operations)β β (monitoring) β β
β ββββββββββ¬βββββββββ ββββββββββββββββββββ β
β β β
β ββββββββββΌβββββββββ ββββββββββββββββββββ β
β β Volatility β β Registry β β
β β Regime β β (persistence) β β
β β Detector β β β β
β βββββββββββββββββββ ββββββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββΌβββββββ
β API Server β (HTTP REST)
ββββββββ¬βββββββ
β
βββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββ
β Hedge Engine (TypeScript) β
β ββββββββββββββββ ββββββββββββββββββ ββββββββββββββββ β
β βDelta Monitor βββββΊβPosition ManagerβββββDrift Protocolβ β
β β(calculates) β β(executes hedges)β β (perpetuals)β β
β ββββββββββββββββ ββββββββββββββββββ ββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Actor System (Rust)
The LP engine uses an actor-based architecture for concurrent position management. Each actor operates independently with message-passing for coordination.
GridCoordinator
The central orchestrator managing all position actors:
Message Routing
Routes messages between actors using priority queues. Priorities: Critical β High β Normal β Low. Critical operations (position opening, emergency shutdowns) always execute first.
Balance Coordination
Handles balance requests from position actors via BalanceActor. Requests have 5-second timeout with correlation IDs for response matching.
Supervisor Pattern
Runs health checks every 30 seconds. Automatically restarts failed actors. Circuit breaker opens after consecutive failures to prevent cascading issues.
PositionActor
One actor per liquidity position, handling complete lifecycle:
State Machine:
NotCreated β Pending β Active β OutOfRange β Rebalancing β Active β Closed
β
Error (recoverable/non-recoverable)
Key Operations:
- Initialize: Crash recovery checks for orphaned on-chain positions
- Health Check: Monitors range boundaries, fee accumulation
- Rebalance: Closes position, calculates new range, opens with fresh parameters
- Close: Removes liquidity, harvests fees, burns position NFT
BalanceActor
Dedicated actor for wallet balance monitoring:
- Caching: Balance data cached with configurable TTL to reduce RPC load
- On-chain Fetch: Direct RPC calls for accurate position data when needed
- Circuit Breaker: Tracks failures, opens after threshold, half-opens for tests
Liquidity Management
LiquidityManager
Primary interface for all Orca Whirlpool operations:
| Method | Description |
|---|---|
open_strategic_position() | Opens position with volatility-calculated range |
close_position() | Closes position, returns liquidity to wallet |
harvest_fees() | Collects accumulated trading fees |
increase_liquidity() | Adds more liquidity to existing position |
decrease_liquidity() | Removes liquidity from position |
Position Opening Flow
- Duplicate Check: Verify position doesn't already exist on-chain
- Volatility Fetch: Get 24h historical prices from Pyth
- Range Calculation: EWMA-smoothed volatility β tick range
- Wallet Rebalance: Swap tokens to achieve required ratio
- Liquidity Calculation: Exact token amounts for price range
- Transaction Build: Priority fees + optional Jito bundle
- Submission: Exponential backoff confirmation polling
- Registry Update: Persist NFT mint, ticks, metadata
WalletRebalancer
Ensures correct token ratios before position operations:
Current Balances β Target Calculation β Tolerance Check β Swap Execution β Verification
Features:
- WebSocket balance monitoring (optional, with polling fallback)
- Swap execution through Orca with slippage protection
- Exponential backoff on balance verification
Volatility Analysis
VolatilityConfig
Default parameters for volatility calculation:
| Parameter | Default | Description |
|---|---|---|
| Lookback Hours | 24 | Historical price window |
| Interval Mins | 60 | Price sampling interval |
| Min Observations | 20 | Required data points |
| Max Threshold | 110% | Volatility cap |
| Min Threshold | 5% | Volatility floor |
Volatility Regime Detector
Monitors for significant volatility changes:
| Regime | Volatility | Strategy | Capital Factor |
|---|---|---|---|
| Crab | < 3% daily | Aggressive (tight ranges) | 1.2x |
| Normal | 3-8% daily | Balanced | 1.0x |
| Blast | > 8% daily | Conservative (wide ranges) | 0.7x |
Regime Change Handling:
- Rate limited to prevent excessive rebalancing
- Minimum interval between rebalances enforced
- Emergency threshold for immediate action
Hedge Engine Architecture
Component Overview
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Hedge Engine β
β βββββββββββββββββββ ββββββββββββββββββββ β
β β RustBotClient β β DriftClient β β
β β (delta fetch) β β (perp trading) β β
β ββββββββββ¬βββββββββ ββββββββββ¬ββββββββββ β
β β β β
β ββββββββββΌβββββββββββββββββββββΌββββββββββ β
β β HedgeEngine / DynamicHedge β β
β β β’ Delta calculation β β
β β β’ Hedge decision logic β β
β β β’ Trade execution β β
β ββββββββββββββββββββββ¬βββββββββββββββββββ β
β β β
β ββββββββββββββββββββββΌβββββββββββββββββββ β
β β ExecutionController β β
β β β’ Deadband filter β β
β β β’ Proportional sizing β β
β β β’ Market condition adjustments β β
β ββββββββββββββββββββββ¬βββββββββββββββββββ β
β β β
β ββββββββββββββββββββββΌβββββββββββββββββββ β
β β CollateralManager β β
β β β’ Auto deposit/withdraw β β
β β β’ Ratio maintenance β β
β βββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
MA-Adaptive Policy
Moving average-based hedge ratio adjustment:
regime = price > MA + band ? 'up'
: price < MA - band ? 'down'
: 'neutral';
hedgeRatio = regime === 'up' ? uptrendRatio // e.g., 40%
: regime === 'down' ? downtrendRatio // e.g., 100%
: neutralRatio; // e.g., 70%
Optional Tilts:
- Funding Sensitivity: Reduce hedging when funding is expensive
- Volatility Sensitivity: Adjust based on ATR percentage
Execution Controller Logic
deltaError = targetShort - currentShort
if (|deltaError| < deadband) β skip
if (timeSinceLastTrade < cooldown) β skip
intensity = proportionalGain
intensity *= fundingPenalty // reduce if funding expensive
intensity *= spreadPenalty // reduce if spread wide
intensity *= liquidityScore // reduce in poor liquidity
orderSize = clamp(intensity Γ deltaError, minTrade, maxTrade)
Transaction Management
TransactionManager
Handles all blockchain transaction lifecycle:
Priority Tiers:
| Tier | Use Case | Fee Multiplier |
|---|---|---|
| LOW | Non-urgent operations | 1x |
| MEDIUM | Normal operations | 1.5x |
| HIGH | Time-sensitive trades | 2x |
| TURBO | Critical operations | 5x |
Features:
- Dynamic compute unit estimation
- Jito bundle integration for MEV protection
- Exponential backoff retry logic
- Fresh blockhash on expiration errors
Error Recovery
| Error Type | Recovery Strategy |
|---|---|
| TokenMinSubceeded | Increment slippage tolerance, retry |
| Blockhash Expired | Fetch new blockhash, retry |
| Simulation Failed | Log details, abort transaction |
| Timeout | Exponential backoff, up to max retries |
| RPC Error | Circuit breaker, fallback endpoint |
Resource Management
ResourceManager
Global resource pooling for efficiency:
RPC Client Pool
Reuses RPC clients instead of creating new connections. Max 10 clients in pool. Automatic failover to backup endpoints on failure.
Token Decimals Cache
Token decimals cached permanently (no TTL). Eliminates redundant RPC calls for commonly used tokens.
Whirlpool State Cache
Pool state cached with 5-second TTL. Balances freshness with RPC efficiency for frequently accessed data.
Data Persistence
PositionsRegistry
Thread-safe state management for positions:
Storage Format: TOML files
positions_config.toml: Static configurationpositions_registry.toml: Runtime state (NFTs, liquidity, metrics)
Features:
- Atomic writes prevent corruption
- On-chain sync reconciles local vs blockchain state
- Tracks: fees earned, rebalance count, APR, PnL
Communication Flow
LP Engine β Hedge Engine
GET /api/delta
Response: {
delta: number, // LP delta in USD
lpNotional: number, // Total position value
confidence: number, // Calculation confidence
timestamp: string
}
The hedge engine polls this endpoint, calculates required hedge adjustment, and executes trades on Drift Protocol to maintain target delta.