1use std::{
19 future::Future,
20 time::{Duration, Instant},
21};
22
23use indexmap::IndexMap;
24use nautilus_common::enums::LogLevel;
25use nautilus_core::UnixNanos;
26use nautilus_live::{ExecutionClientCore, task::TaskGroup};
27use nautilus_model::{
28 events::OrderEventAny,
29 identifiers::{AccountId, VenueOrderId},
30 orders::{Order, OrderAny},
31 reports::OrderStatusReport,
32};
33
34pub(crate) fn active_orders(core: &ExecutionClientCore) -> Vec<OrderAny> {
35 let cache = core.cache();
36 cache
37 .orders_refs(Some(&core.venue), None, None, Some(&core.account_id), None)
38 .into_iter()
39 .filter(|order| {
40 (order.is_open() || order.is_inflight())
41 && !order.strategy_id().is_external()
42 && cache.client_id(&order.client_order_id()) == Some(&core.client_id)
43 && (order.ts_submitted().is_some()
44 || order.events().iter().any(|event| {
45 matches!(event, OrderEventAny::Accepted(accepted) if !accepted.reconciliation)
46 }))
47 })
48 .map(|order| order.cloned())
49 .collect()
50}
51
52pub(crate) fn log_report_receipt(count: usize, report_type: &str, level: LogLevel) {
53 let level = match level {
54 LogLevel::Off => return,
55 LogLevel::Trace => log::Level::Trace,
56 LogLevel::Debug => log::Level::Debug,
57 LogLevel::Info => log::Level::Info,
58 LogLevel::Warning => log::Level::Warn,
59 LogLevel::Error => log::Level::Error,
60 };
61 let plural = if count == 1 { "" } else { "s" };
62 log::log!(level, "Received {count} {report_type}{plural}");
63}
64
65pub(crate) fn merge_order_history(
66 reports: &mut IndexMap<VenueOrderId, OrderStatusReport>,
67 history: Vec<OrderStatusReport>,
68 start: Option<UnixNanos>,
69 end: UnixNanos,
70) {
71 for report in history {
72 if !report.order_status.is_closed()
73 || start.is_some_and(|start| report.ts_last < start)
74 || report.ts_last > end
75 {
76 continue;
77 }
78
79 reports.entry(report.venue_order_id).or_insert(report);
80 }
81}
82
83pub fn spawn_task<F>(pending_tasks: &TaskGroup, description: &'static str, fut: F)
85where
86 F: Future<Output = anyhow::Result<()>> + Send + 'static,
87{
88 let future = async move {
89 if let Err(e) = fut.await {
90 log::warn!("{description} failed: {e}");
91 }
92 };
93
94 if let Err(e) = pending_tasks.spawn(future) {
95 log::warn!("Skipping Binance {description} after shutdown began: {e}");
96 }
97}
98
99pub fn abort_pending_tasks(pending_tasks: &TaskGroup) {
101 pending_tasks.begin_shutdown();
102}
103
104pub async fn await_pending_tasks(pending_tasks: &TaskGroup) -> anyhow::Result<()> {
110 pending_tasks.begin_shutdown();
111 pending_tasks
112 .finish_shutdown(Duration::from_secs(1), Duration::from_secs(2))
113 .await
114 .map_err(|e| anyhow::anyhow!("Failed to terminate Binance execution tasks: {e}"))?;
115 Ok(())
116}
117
118pub async fn await_account_registered(
128 core: &ExecutionClientCore,
129 account_id: AccountId,
130 timeout_secs: f64,
131) -> anyhow::Result<()> {
132 if core.cache().account(&account_id).is_some() {
133 log::info!("Account {account_id} registered");
134 return Ok(());
135 }
136
137 let start = Instant::now();
138 let timeout = Duration::from_secs_f64(timeout_secs);
139 let interval = Duration::from_millis(10);
140
141 loop {
142 tokio::time::sleep(interval).await;
143
144 if core.cache().account(&account_id).is_some() {
145 log::info!("Account {account_id} registered");
146 return Ok(());
147 }
148
149 if start.elapsed() >= timeout {
150 anyhow::bail!(
151 "Timeout waiting for account {account_id} to be registered after {timeout_secs}s"
152 );
153 }
154 }
155}
156
157#[cfg(test)]
158mod tests {
159 use std::{cell::RefCell, rc::Rc};
160
161 use nautilus_common::cache::Cache;
162 use nautilus_live::ExecutionClientCore;
163 use nautilus_model::{
164 accounts::{AccountAny, CashAccount},
165 enums::{AccountType, OmsType, OrderSide, OrderStatus, OrderType, TimeInForce},
166 events::AccountState,
167 identifiers::{AccountId, TraderId},
168 orders::{OrderTestBuilder, stubs::TestOrderEventStubs},
169 types::{AccountBalance, Money, Price, Quantity},
170 };
171 use rstest::rstest;
172
173 use super::*;
174 use crate::common::consts::{BINANCE_CLIENT_ID, BINANCE_VENUE};
175
176 #[rstest]
177 #[case::before_start(OrderStatus::Filled, 9, Some(10), false)]
178 #[case::at_start(OrderStatus::Filled, 10, Some(10), true)]
179 #[case::at_end(OrderStatus::Canceled, 20, Some(10), true)]
180 #[case::after_end(OrderStatus::Filled, 21, Some(10), false)]
181 #[case::unbounded_start(OrderStatus::Expired, 1, None, true)]
182 #[case::open(OrderStatus::Accepted, 15, Some(10), false)]
183 #[case::partial(OrderStatus::PartiallyFilled, 15, Some(10), false)]
184 fn test_merge_order_history_bounds(
185 #[case] status: OrderStatus,
186 #[case] timestamp: u64,
187 #[case] start: Option<u64>,
188 #[case] included: bool,
189 ) {
190 let report = OrderStatusReport::new(
191 AccountId::from("BINANCE-001"),
192 "BTCUSDT.BINANCE".into(),
193 Some("history-order".into()),
194 "12345".into(),
195 Some(OrderSide::Buy),
196 OrderType::Limit,
197 TimeInForce::Gtc,
198 status,
199 Quantity::from("0.123"),
200 Quantity::from("0.012"),
201 1.into(),
202 timestamp.into(),
203 30.into(),
204 None,
205 );
206
207 let expected = if included {
208 IndexMap::from([(report.venue_order_id, report.clone())])
209 } else {
210 IndexMap::new()
211 };
212
213 let mut reports = IndexMap::new();
214
215 merge_order_history(
216 &mut reports,
217 vec![report],
218 start.map(UnixNanos::from),
219 20.into(),
220 );
221
222 assert_eq!(reports, expected);
223 }
224
225 #[rstest]
226 fn test_merge_order_history_preserves_authoritative_open_report() {
227 let open = OrderStatusReport::new(
228 AccountId::from("BINANCE-001"),
229 "BTCUSDT.BINANCE".into(),
230 Some("current-order".into()),
231 "12345".into(),
232 Some(OrderSide::Sell),
233 OrderType::Limit,
234 TimeInForce::Ioc,
235 OrderStatus::PartiallyFilled,
236 Quantity::from("0.234"),
237 Quantity::from("0.023"),
238 1.into(),
239 20.into(),
240 30.into(),
241 None,
242 );
243 let mut stale = open.clone();
244 stale.client_order_id = Some("stale-order".into());
245 stale.order_status = OrderStatus::Canceled;
246 stale.ts_last = 15.into();
247 let expected = IndexMap::from([(open.venue_order_id, open)]);
248 let mut reports = expected.clone();
249
250 merge_order_history(
251 &mut reports,
252 vec![stale.clone(), stale],
253 Some(10.into()),
254 20.into(),
255 );
256
257 assert_eq!(reports, expected);
258 }
259
260 #[rstest]
261 #[case::accepted(
262 "BINANCE-001",
263 "BINANCE",
264 "OWNED-002",
265 "BTCUSDT.BINANCE",
266 (true, true, false),
267 false,
268 1
269 )]
270 #[case::submitted(
271 "BINANCE-001",
272 "BINANCE",
273 "OWNED-002",
274 "BTCUSDT.BINANCE",
275 (true, false, false),
276 false,
277 1
278 )]
279 #[case::other_account(
280 "BINANCE-002",
281 "BINANCE",
282 "OWNED-002",
283 "BTCUSDT.BINANCE",
284 (true, true, false),
285 false,
286 0
287 )]
288 #[case::other_client(
289 "BINANCE-001",
290 "OTHER",
291 "OWNED-002",
292 "BTCUSDT.BINANCE",
293 (true, true, false),
294 false,
295 0
296 )]
297 #[case::unbound(
298 "BINANCE-001",
299 "",
300 "OWNED-002",
301 "BTCUSDT.BINANCE",
302 (true, true, false),
303 false,
304 0
305 )]
306 #[case::external(
307 "BINANCE-001",
308 "BINANCE",
309 "EXTERNAL",
310 "BTCUSDT.BINANCE",
311 (true, true, false),
312 false,
313 0
314 )]
315 #[case::other_venue(
316 "BINANCE-001",
317 "BINANCE",
318 "OWNED-002",
319 "BTCUSDT.OTHER",
320 (true, true, false),
321 false,
322 0
323 )]
324 #[case::initialized(
325 "BINANCE-001",
326 "BINANCE",
327 "OWNED-002",
328 "BTCUSDT.BINANCE",
329 (false, false, false),
330 false,
331 0
332 )]
333 #[case::closed(
334 "BINANCE-001",
335 "BINANCE",
336 "OWNED-002",
337 "BTCUSDT.BINANCE",
338 (true, true, true),
339 false,
340 0
341 )]
342 #[case::claimed_external(
343 "BINANCE-001",
344 "BINANCE",
345 "OWNED-002",
346 "BTCUSDT.BINANCE",
347 (false, true, false),
348 true,
349 0
350 )]
351 #[case::reconciled_local(
352 "BINANCE-001",
353 "BINANCE",
354 "OWNED-002",
355 "BTCUSDT.BINANCE",
356 (true, true, false),
357 true,
358 1
359 )]
360 fn test_active_orders_selects_only_retained_local_owners(
361 #[case] account: &str,
362 #[case] client: &str,
363 #[case] strategy: &str,
364 #[case] instrument: &str,
365 #[case] lifecycle: (bool, bool, bool),
366 #[case] reconciled: bool,
367 #[case] expected_count: usize,
368 ) {
369 let (submitted, accepted, closed) = lifecycle;
370 let cache = Rc::new(RefCell::new(Cache::default()));
371 let core = create_test_core(cache.clone(), AccountId::from("BINANCE-001"));
372 let order = OrderTestBuilder::new(OrderType::Limit)
373 .strategy_id(strategy.into())
374 .instrument_id(instrument.into())
375 .quantity(Quantity::from("0.002"))
376 .price(Price::from("45678.90"))
377 .build();
378 let cid = order.client_order_id();
379 cache
380 .borrow_mut()
381 .add_order(
382 order.clone(),
383 None,
384 (!client.is_empty()).then(|| client.into()),
385 false,
386 )
387 .unwrap();
388
389 if submitted {
390 cache
391 .borrow_mut()
392 .update_order(&TestOrderEventStubs::submitted(&order, account.into()))
393 .unwrap();
394 }
395
396 if accepted {
397 let OrderEventAny::Accepted(mut event) =
398 TestOrderEventStubs::accepted(&order, account.into(), "123".into())
399 else {
400 panic!("Expected acceptance stub")
401 };
402
403 event.reconciliation = reconciled;
404 cache
405 .borrow_mut()
406 .update_order(&OrderEventAny::Accepted(event))
407 .unwrap();
408 }
409
410 if closed {
411 cache
412 .borrow_mut()
413 .update_order(&TestOrderEventStubs::canceled(
414 &order,
415 account.into(),
416 Some("123".into()),
417 ))
418 .unwrap();
419 }
420
421 let selected = active_orders(&core);
422 assert_eq!(selected.len(), expected_count);
423
424 if expected_count == 1 {
425 assert_eq!(selected[0], cache.borrow().order_owned(&cid).unwrap());
426 }
427 }
428
429 #[rstest]
430 #[tokio::test]
431 async fn test_spawn_task_unregisters_finished_task_before_shutdown() {
432 let pending_tasks = TaskGroup::new();
433
434 spawn_task(&pending_tasks, "test task", async { Ok(()) });
435 tokio::time::timeout(Duration::from_secs(1), async {
436 while !pending_tasks.all_finished() {
437 tokio::task::yield_now().await;
438 }
439 })
440 .await
441 .expect("task should finish");
442
443 assert!(pending_tasks.is_empty());
444 abort_pending_tasks(&pending_tasks);
445 await_pending_tasks(&pending_tasks)
446 .await
447 .expect("task shutdown");
448 assert!(pending_tasks.is_empty());
449 }
450
451 #[rstest]
452 #[tokio::test]
453 async fn test_abort_pending_tasks_aborts_running_tasks() {
454 let (drop_tx, drop_rx) = tokio::sync::oneshot::channel();
455 let guard = AbortDropSignal { tx: Some(drop_tx) };
456
457 let pending_tasks = TaskGroup::new();
458 pending_tasks
459 .spawn(async move {
460 let _guard = guard;
461 tokio::time::sleep(Duration::from_secs(60)).await;
462 })
463 .expect("task spawn");
464
465 abort_pending_tasks(&pending_tasks);
466 await_pending_tasks(&pending_tasks)
467 .await
468 .expect("task shutdown");
469
470 assert!(pending_tasks.is_empty());
471 tokio::time::timeout(Duration::from_secs(1), drop_rx)
472 .await
473 .expect("Aborted task should drop its future")
474 .expect("Drop signal should be sent");
475 }
476
477 #[rstest]
478 #[tokio::test]
479 async fn test_await_account_registered_returns_when_account_is_added() {
480 let account_id = AccountId::from("BINANCE-001");
481 let cache = Rc::new(RefCell::new(Cache::default()));
482 let core = create_test_core(cache.clone(), account_id);
483
484 let wait_fut = await_account_registered(&core, account_id, 0.5);
485 let register_fut = async move {
486 tokio::time::sleep(Duration::from_millis(20)).await;
487 add_test_account_to_cache(&cache, account_id);
488 };
489
490 let (result, ()) = tokio::join!(wait_fut, register_fut);
491 result.unwrap();
492 }
493
494 #[rstest]
495 #[tokio::test]
496 async fn test_await_account_registered_times_out() {
497 let account_id = AccountId::from("BINANCE-001");
498 let cache = Rc::new(RefCell::new(Cache::default()));
499 let core = create_test_core(cache, account_id);
500
501 let error = await_account_registered(&core, account_id, 0.02)
502 .await
503 .expect_err("Missing account should time out");
504
505 assert!(error.to_string().contains("BINANCE-001"));
506 }
507
508 struct AbortDropSignal {
509 tx: Option<tokio::sync::oneshot::Sender<()>>,
510 }
511
512 impl Drop for AbortDropSignal {
513 fn drop(&mut self) {
514 if let Some(tx) = self.tx.take() {
515 let _ = tx.send(());
516 }
517 }
518 }
519
520 fn create_test_core(cache: Rc<RefCell<Cache>>, account_id: AccountId) -> ExecutionClientCore {
521 ExecutionClientCore::new(
522 TraderId::from("TESTER-001"),
523 *BINANCE_CLIENT_ID,
524 *BINANCE_VENUE,
525 OmsType::Hedging,
526 account_id,
527 AccountType::Cash,
528 None,
529 cache,
530 )
531 }
532
533 fn add_test_account_to_cache(cache: &Rc<RefCell<Cache>>, account_id: AccountId) {
534 let state = AccountState::new(
535 account_id,
536 AccountType::Cash,
537 vec![AccountBalance::new(
538 Money::from("1.0 BTC"),
539 Money::from("0 BTC"),
540 Money::from("1.0 BTC"),
541 )],
542 vec![],
543 true,
544 nautilus_core::UUID4::new(),
545 nautilus_core::UnixNanos::default(),
546 nautilus_core::UnixNanos::default(),
547 None,
548 );
549
550 let account = AccountAny::Cash(CashAccount::new(state, true, false));
551 cache.borrow_mut().add_account(account).unwrap();
552 }
553}