nt-execution 1.0.0

Order execution and broker integration for Neural Trader - supports Alpaca, Interactive Brokers, and more
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
// Order lifecycle management with actor pattern
//
// Features:
// - Async order placement with timeout
// - Fill tracking and reconciliation
// - Partial fill handling
// - Order cancellation
// - Retry logic with exponential backoff

use crate::{BrokerClient, ExecutionError, OrderSide, OrderType, Result, Symbol, TimeInForce};
use chrono::{DateTime, Utc};
use dashmap::DashMap;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{mpsc, oneshot};
use tokio::time::timeout;
use tracing::{debug, error, info, warn};
use uuid::Uuid;

/// Order status enumeration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum OrderStatus {
    /// Order submitted but not yet acknowledged
    Pending,
    /// Order acknowledged by broker
    Accepted,
    /// Order partially filled
    PartiallyFilled,
    /// Order completely filled
    Filled,
    /// Order cancelled
    Cancelled,
    /// Order rejected by broker
    Rejected,
    /// Order expired
    Expired,
}

/// Order request structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrderRequest {
    pub symbol: Symbol,
    pub side: OrderSide,
    pub order_type: OrderType,
    pub quantity: u32,
    pub limit_price: Option<Decimal>,
    pub stop_price: Option<Decimal>,
    pub time_in_force: TimeInForce,
}

/// Order response from broker
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrderResponse {
    pub order_id: String,
    pub client_order_id: String,
    pub status: OrderStatus,
    pub filled_qty: u32,
    pub filled_avg_price: Option<Decimal>,
    pub submitted_at: DateTime<Utc>,
    pub filled_at: Option<DateTime<Utc>>,
}

/// Order update notification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrderUpdate {
    pub order_id: String,
    pub status: OrderStatus,
    pub filled_qty: u32,
    pub filled_avg_price: Option<Decimal>,
    pub timestamp: DateTime<Utc>,
}

/// Tracked order information
#[derive(Debug, Clone)]
struct TrackedOrder {
    request: OrderRequest,
    response: Option<OrderResponse>,
    status: OrderStatus,
    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
}

/// Order manager actor messages
enum OrderMessage {
    PlaceOrder {
        request: OrderRequest,
        response_tx: oneshot::Sender<Result<OrderResponse>>,
    },
    CancelOrder {
        order_id: String,
        response_tx: oneshot::Sender<Result<()>>,
    },
    GetOrderStatus {
        order_id: String,
        response_tx: oneshot::Sender<Result<OrderStatus>>,
    },
    UpdateOrder {
        update: OrderUpdate,
    },
    Shutdown,
}

/// Order manager for managing order lifecycle
pub struct OrderManager {
    message_tx: mpsc::Sender<OrderMessage>,
    orders: Arc<DashMap<String, TrackedOrder>>,
}

impl OrderManager {
    /// Create a new order manager
    pub fn new<B: BrokerClient + 'static>(broker: Arc<B>) -> Self {
        let (message_tx, message_rx) = mpsc::channel(1000);
        let orders = Arc::new(DashMap::new());

        // Spawn actor task
        let orders_clone = Arc::clone(&orders);
        tokio::spawn(async move {
            Self::actor_loop(broker, message_rx, orders_clone).await;
        });

        Self { message_tx, orders }
    }

    /// Place an order asynchronously with timeout
    ///
    /// Target: <10ms end-to-end
    pub async fn place_order(&self, request: OrderRequest) -> Result<OrderResponse> {
        let (response_tx, response_rx) = oneshot::channel();

        self.message_tx
            .send(OrderMessage::PlaceOrder {
                request,
                response_tx,
            })
            .await
            .map_err(|e| ExecutionError::Order(format!("Failed to send message: {}", e)))?;

        // Wait for response with timeout (10 seconds)
        timeout(Duration::from_secs(10), response_rx)
            .await
            .map_err(|_| ExecutionError::Timeout)?
            .map_err(|e| ExecutionError::Order(format!("Failed to receive response: {}", e)))?
    }

    /// Cancel an order
    pub async fn cancel_order(&self, order_id: String) -> Result<()> {
        let (response_tx, response_rx) = oneshot::channel();

        self.message_tx
            .send(OrderMessage::CancelOrder {
                order_id,
                response_tx,
            })
            .await
            .map_err(|e| ExecutionError::Order(format!("Failed to send message: {}", e)))?;

        timeout(Duration::from_secs(5), response_rx)
            .await
            .map_err(|_| ExecutionError::Timeout)?
            .map_err(|e| ExecutionError::Order(format!("Failed to receive response: {}", e)))?
    }

    /// Get order status
    pub async fn get_order_status(&self, order_id: &str) -> Result<OrderStatus> {
        // Fast path: check cache first
        if let Some(order) = self.orders.get(order_id) {
            return Ok(order.status);
        }

        let (response_tx, response_rx) = oneshot::channel();

        self.message_tx
            .send(OrderMessage::GetOrderStatus {
                order_id: order_id.to_string(),
                response_tx,
            })
            .await
            .map_err(|e| ExecutionError::Order(format!("Failed to send message: {}", e)))?;

        timeout(Duration::from_secs(5), response_rx)
            .await
            .map_err(|_| ExecutionError::Timeout)?
            .map_err(|e| ExecutionError::Order(format!("Failed to receive response: {}", e)))?
    }

    /// Handle order update (from WebSocket or polling)
    pub async fn handle_order_update(&self, update: OrderUpdate) -> Result<()> {
        self.message_tx
            .send(OrderMessage::UpdateOrder { update })
            .await
            .map_err(|e| ExecutionError::Order(format!("Failed to send update: {}", e)))?;

        Ok(())
    }

    /// Get all orders
    pub fn get_all_orders(&self) -> Vec<(String, OrderStatus)> {
        self.orders
            .iter()
            .map(|entry| (entry.key().clone(), entry.value().status))
            .collect()
    }

    /// Shutdown the order manager
    pub async fn shutdown(&self) -> Result<()> {
        self.message_tx
            .send(OrderMessage::Shutdown)
            .await
            .map_err(|e| ExecutionError::Order(format!("Failed to send shutdown: {}", e)))?;

        Ok(())
    }

    /// Actor loop that processes messages
    async fn actor_loop<B: BrokerClient + 'static>(
        broker: Arc<B>,
        mut message_rx: mpsc::Receiver<OrderMessage>,
        orders: Arc<DashMap<String, TrackedOrder>>,
    ) {
        info!("Order manager actor started");

        while let Some(message) = message_rx.recv().await {
            match message {
                OrderMessage::PlaceOrder {
                    request,
                    response_tx,
                } => {
                    let result =
                        Self::handle_place_order(Arc::clone(&broker), &orders, request).await;
                    let _ = response_tx.send(result);
                }

                OrderMessage::CancelOrder {
                    order_id,
                    response_tx,
                } => {
                    let result =
                        Self::handle_cancel_order(Arc::clone(&broker), &orders, &order_id).await;
                    let _ = response_tx.send(result);
                }

                OrderMessage::GetOrderStatus {
                    order_id,
                    response_tx,
                } => {
                    let result =
                        Self::handle_get_status(Arc::clone(&broker), &orders, &order_id).await;
                    let _ = response_tx.send(result);
                }

                OrderMessage::UpdateOrder { update } => {
                    Self::handle_order_update_internal(&orders, update);
                }

                OrderMessage::Shutdown => {
                    info!("Order manager actor shutting down");
                    break;
                }
            }
        }

        info!("Order manager actor stopped");
    }

    async fn handle_place_order<B: BrokerClient + 'static>(
        broker: Arc<B>,
        orders: &Arc<DashMap<String, TrackedOrder>>,
        request: OrderRequest,
    ) -> Result<OrderResponse> {
        debug!("Placing order: {:?}", request);

        // Retry with exponential backoff (max 3 attempts)
        let response = retry_with_backoff(
            || {
                let broker = Arc::clone(&broker);
                let req = request.clone();
                Box::pin(async move { broker.place_order(req).await })
            },
            3,
            Duration::from_millis(100),
        )
        .await?;

        info!(
            "Order placed: {} status={:?}",
            response.order_id, response.status
        );

        // Track the order
        orders.insert(
            response.order_id.clone(),
            TrackedOrder {
                request: request.clone(),
                response: Some(response.clone()),
                status: response.status,
                created_at: Utc::now(),
                updated_at: Utc::now(),
            },
        );

        Ok(response)
    }

    async fn handle_cancel_order<B: BrokerClient>(
        broker: Arc<B>,
        orders: &Arc<DashMap<String, TrackedOrder>>,
        order_id: &str,
    ) -> Result<()> {
        debug!("Cancelling order: {}", order_id);

        broker.cancel_order(order_id).await?;

        // Update tracked order
        if let Some(mut order) = orders.get_mut(order_id) {
            order.status = OrderStatus::Cancelled;
            order.updated_at = Utc::now();
        }

        info!("Order cancelled: {}", order_id);
        Ok(())
    }

    async fn handle_get_status<B: BrokerClient>(
        broker: Arc<B>,
        orders: &Arc<DashMap<String, TrackedOrder>>,
        order_id: &str,
    ) -> Result<OrderStatus> {
        // Check cache first
        if let Some(order) = orders.get(order_id) {
            return Ok(order.status);
        }

        // Query broker
        let order = broker.get_order(order_id).await?;

        // Update cache
        if let Some(mut tracked) = orders.get_mut(order_id) {
            tracked.status = order.status;
            tracked.updated_at = Utc::now();
        }

        Ok(order.status)
    }

    fn handle_order_update_internal(orders: &Arc<DashMap<String, TrackedOrder>>, update: OrderUpdate) {
        if let Some(mut order) = orders.get_mut(&update.order_id) {
            order.status = update.status;
            order.updated_at = update.timestamp;

            if let Some(ref mut response) = order.response {
                response.status = update.status;
                response.filled_qty = update.filled_qty;
                response.filled_avg_price = update.filled_avg_price;
            }

            debug!(
                "Order updated: {} status={:?} filled={}",
                update.order_id, update.status, update.filled_qty
            );
        } else {
            warn!("Received update for unknown order: {}", update.order_id);
        }
    }
}

/// Retry an async operation with exponential backoff
async fn retry_with_backoff<F, T, E>(
    mut f: F,
    max_attempts: u32,
    initial_delay: Duration,
) -> Result<T>
where
    F: FnMut() -> std::pin::Pin<Box<dyn std::future::Future<Output = std::result::Result<T, E>> + Send>>,
    E: Into<ExecutionError>,
{
    let mut delay = initial_delay;

    for attempt in 1..=max_attempts {
        match f().await {
            Ok(result) => return Ok(result),
            Err(e) if attempt == max_attempts => {
                error!("All {} retry attempts failed", max_attempts);
                return Err(e.into());
            }
            Err(e) => {
                warn!(
                    "Attempt {} failed, retrying in {:?}...",
                    attempt, delay
                );
                tokio::time::sleep(delay).await;
                delay *= 2; // Exponential backoff
            }
        }
    }

    unreachable!()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_order_request_serialization() {
        let request = OrderRequest {
            symbol: Symbol::new("AAPL").expect("Valid symbol"),
            side: OrderSide::Buy,
            order_type: OrderType::Market,
            quantity: 100,
            limit_price: None,
            stop_price: None,
            time_in_force: TimeInForce::Day,
        };

        let json = serde_json::to_string(&request).unwrap();
        let deserialized: OrderRequest = serde_json::from_str(&json).unwrap();

        assert_eq!(request.symbol, deserialized.symbol);
        assert_eq!(request.quantity, deserialized.quantity);
    }
}