1use std::{cell::RefCell, rc::Rc};
17
18use chrono::{DateTime, Duration, Utc};
19use nautilus_core::{UnixNanos, python::to_pyvalue_err};
20use pyo3::prelude::*;
21
22use crate::{
23 clock::{Clock, LiveClock, TestClock},
24 timer::TimeEventCallback,
25};
26
27#[allow(non_camel_case_types)]
37#[pyo3::pyclass(
38 module = "nautilus_trader.core.nautilus_pyo3.common",
39 name = "Clock",
40 unsendable
41)]
42#[derive(Debug, Clone)]
43pub struct PyClock(Rc<RefCell<dyn Clock>>);
44
45#[pymethods]
46impl PyClock {
47 #[pyo3(name = "register_default_handler")]
48 fn py_register_default_handler(&mut self, callback: Py<PyAny>) {
49 self.0
50 .borrow_mut()
51 .register_default_handler(TimeEventCallback::from(callback));
52 }
53
54 #[pyo3(
55 name = "set_time_alert",
56 signature = (name, alert_time, callback=None, allow_past=None)
57 )]
58 fn py_set_time_alert(
59 &mut self,
60 name: &str,
61 alert_time: DateTime<Utc>,
62 callback: Option<Py<PyAny>>,
63 allow_past: Option<bool>,
64 ) -> PyResult<()> {
65 self.0
66 .borrow_mut()
67 .set_time_alert(
68 name,
69 alert_time,
70 callback.map(TimeEventCallback::from),
71 allow_past,
72 )
73 .map_err(to_pyvalue_err)
74 }
75
76 #[pyo3(
77 name = "set_time_alert_ns",
78 signature = (name, alert_time_ns, callback=None, allow_past=None)
79 )]
80 fn py_set_time_alert_ns(
81 &mut self,
82 name: &str,
83 alert_time_ns: u64,
84 callback: Option<Py<PyAny>>,
85 allow_past: Option<bool>,
86 ) -> PyResult<()> {
87 self.0
88 .borrow_mut()
89 .set_time_alert_ns(
90 name,
91 alert_time_ns.into(),
92 callback.map(TimeEventCallback::from),
93 allow_past,
94 )
95 .map_err(to_pyvalue_err)
96 }
97
98 #[allow(clippy::too_many_arguments)]
99 #[pyo3(
100 name = "set_timer",
101 signature = (name, interval, start_time=None, stop_time=None, callback=None, allow_past=None, fire_immediately=None)
102 )]
103 fn py_set_timer(
104 &mut self,
105 name: &str,
106 interval: Duration,
107 start_time: Option<DateTime<Utc>>,
108 stop_time: Option<DateTime<Utc>>,
109 callback: Option<Py<PyAny>>,
110 allow_past: Option<bool>,
111 fire_immediately: Option<bool>,
112 ) -> PyResult<()> {
113 let interval_ns_i64 = interval
114 .num_nanoseconds()
115 .ok_or_else(|| pyo3::exceptions::PyValueError::new_err("Interval too large"))?;
116 if interval_ns_i64 <= 0 {
117 return Err(pyo3::exceptions::PyValueError::new_err(
118 "Interval must be positive",
119 ));
120 }
121 let interval_ns = interval_ns_i64 as u64;
122
123 self.0
124 .borrow_mut()
125 .set_timer_ns(
126 name,
127 interval_ns,
128 start_time.map(UnixNanos::from),
129 stop_time.map(UnixNanos::from),
130 callback.map(TimeEventCallback::from),
131 allow_past,
132 fire_immediately,
133 )
134 .map_err(to_pyvalue_err)
135 }
136
137 #[allow(clippy::too_many_arguments)]
138 #[pyo3(
139 name = "set_timer_ns",
140 signature = (name, interval_ns, start_time_ns=None, stop_time_ns=None, callback=None, allow_past=None, fire_immediately=None)
141 )]
142 fn py_set_timer_ns(
143 &mut self,
144 name: &str,
145 interval_ns: u64,
146 start_time_ns: Option<u64>,
147 stop_time_ns: Option<u64>,
148 callback: Option<Py<PyAny>>,
149 allow_past: Option<bool>,
150 fire_immediately: Option<bool>,
151 ) -> PyResult<()> {
152 self.0
153 .borrow_mut()
154 .set_timer_ns(
155 name,
156 interval_ns,
157 start_time_ns.map(UnixNanos::from),
158 stop_time_ns.map(UnixNanos::from),
159 callback.map(TimeEventCallback::from),
160 allow_past,
161 fire_immediately,
162 )
163 .map_err(to_pyvalue_err)
164 }
165
166 #[pyo3(name = "next_time_ns")]
167 fn py_next_time_ns(&self, name: &str) -> Option<u64> {
168 self.0.borrow().next_time_ns(name).map(|t| t.as_u64())
169 }
170
171 #[pyo3(name = "cancel_timer")]
172 fn py_cancel_timer(&mut self, name: &str) {
173 self.0.borrow_mut().cancel_timer(name);
174 }
175
176 #[pyo3(name = "cancel_timers")]
177 fn py_cancel_timers(&mut self) {
178 self.0.borrow_mut().cancel_timers();
179 }
180}
181
182impl PyClock {
183 #[must_use]
185 pub fn from_rc(rc: Rc<RefCell<dyn Clock>>) -> Self {
186 Self(rc)
187 }
188
189 #[must_use]
191 pub fn new_test() -> Self {
192 Self(Rc::new(RefCell::new(TestClock::default())))
193 }
194
195 #[must_use]
197 pub fn new_live() -> Self {
198 Self(Rc::new(RefCell::new(LiveClock::default())))
199 }
200
201 #[must_use]
203 pub fn inner(&self) -> std::cell::Ref<'_, dyn Clock> {
204 self.0.borrow()
205 }
206
207 #[must_use]
209 pub fn inner_mut(&mut self) -> std::cell::RefMut<'_, dyn Clock> {
210 self.0.borrow_mut()
211 }
212}
213
214#[cfg(test)]
218mod tests {
219 use std::sync::Arc;
220
221 use chrono::{Duration, Utc};
222 use nautilus_core::{UnixNanos, python::IntoPyObjectNautilusExt};
223 use pyo3::{prelude::*, types::PyList};
224 use rstest::*;
225
226 use crate::{
227 clock::{Clock, TestClock},
228 python::clock::PyClock,
229 runner::{TimeEventSender, set_time_event_sender},
230 timer::{TimeEventCallback, TimeEventHandlerV2},
231 };
232
233 fn ensure_sender() {
234 if crate::runner::try_get_time_event_sender().is_none() {
235 set_time_event_sender(Arc::new(DummySender));
236 }
237 }
238
239 #[derive(Debug)]
241 struct DummySender;
242
243 impl TimeEventSender for DummySender {
244 fn send(&self, _handler: TimeEventHandlerV2) {}
245 }
246
247 #[fixture]
248 pub fn test_clock() -> TestClock {
249 TestClock::new()
250 }
251
252 pub fn test_callback() -> TimeEventCallback {
253 Python::initialize();
254 Python::attach(|py| {
255 let py_list = PyList::empty(py);
256 let py_append = Py::from(py_list.getattr("append").unwrap());
257 let py_append = py_append.into_py_any_unwrap(py);
258 TimeEventCallback::from(py_append)
259 })
260 }
261
262 pub fn test_py_callback() -> Py<PyAny> {
263 Python::initialize();
264 Python::attach(|py| {
265 let py_list = PyList::empty(py);
266 let py_append = Py::from(py_list.getattr("append").unwrap());
267 py_append.into_py_any_unwrap(py)
268 })
269 }
270
271 #[rstest]
276 fn test_test_clock_py_set_time_alert() {
277 Python::initialize();
278 Python::attach(|_py| {
279 let mut py_clock = PyClock::new_test();
280 let callback = test_py_callback();
281 py_clock.py_register_default_handler(callback);
282 let dt = Utc::now() + Duration::seconds(1);
283 py_clock
284 .py_set_time_alert("ALERT1", dt, None, None)
285 .expect("set_time_alert failed");
286 });
287 }
288
289 #[rstest]
290 fn test_test_clock_py_set_timer() {
291 Python::initialize();
292 Python::attach(|_py| {
293 let mut py_clock = PyClock::new_test();
294 let callback = test_py_callback();
295 py_clock.py_register_default_handler(callback);
296 let interval = Duration::seconds(2);
297 py_clock
298 .py_set_timer("TIMER1", interval, None, None, None, None, None)
299 .expect("set_timer failed");
300 });
301 }
302
303 #[rstest]
304 fn test_test_clock_py_set_time_alert_ns() {
305 Python::initialize();
306 Python::attach(|_py| {
307 let mut py_clock = PyClock::new_test();
308 let callback = test_py_callback();
309 py_clock.py_register_default_handler(callback);
310 let ts_ns = (Utc::now() + Duration::seconds(1))
311 .timestamp_nanos_opt()
312 .unwrap() as u64;
313 py_clock
314 .py_set_time_alert_ns("ALERT_NS", ts_ns, None, None)
315 .expect("set_time_alert_ns failed");
316 });
317 }
318
319 #[rstest]
320 fn test_test_clock_py_set_timer_ns() {
321 Python::initialize();
322 Python::attach(|_py| {
323 let mut py_clock = PyClock::new_test();
324 let callback = test_py_callback();
325 py_clock.py_register_default_handler(callback);
326 py_clock
327 .py_set_timer_ns("TIMER_NS", 1_000_000, None, None, None, None, None)
328 .expect("set_timer_ns failed");
329 });
330 }
331
332 #[rstest]
333 fn test_test_clock_raw_set_timer_ns(mut test_clock: TestClock) {
334 Python::initialize();
335 Python::attach(|_py| {
336 let callback = test_callback();
337 test_clock.register_default_handler(callback);
338
339 let timer_name = "TEST_TIME1";
340 test_clock
341 .set_timer_ns(timer_name, 10, None, None, None, None, None)
342 .unwrap();
343
344 assert_eq!(test_clock.timer_names(), [timer_name]);
345 assert_eq!(test_clock.timer_count(), 1);
346 });
347 }
348
349 #[rstest]
350 fn test_test_clock_cancel_timer(mut test_clock: TestClock) {
351 Python::initialize();
352 Python::attach(|_py| {
353 let callback = test_callback();
354 test_clock.register_default_handler(callback);
355
356 let timer_name = "TEST_TIME1";
357 test_clock
358 .set_timer_ns(timer_name, 10, None, None, None, None, None)
359 .unwrap();
360 test_clock.cancel_timer(timer_name);
361
362 assert!(test_clock.timer_names().is_empty());
363 assert_eq!(test_clock.timer_count(), 0);
364 });
365 }
366
367 #[rstest]
368 fn test_test_clock_cancel_timers(mut test_clock: TestClock) {
369 Python::initialize();
370 Python::attach(|_py| {
371 let callback = test_callback();
372 test_clock.register_default_handler(callback);
373
374 let timer_name = "TEST_TIME1";
375 test_clock
376 .set_timer_ns(timer_name, 10, None, None, None, None, None)
377 .unwrap();
378 test_clock.cancel_timers();
379
380 assert!(test_clock.timer_names().is_empty());
381 assert_eq!(test_clock.timer_count(), 0);
382 });
383 }
384
385 #[rstest]
386 fn test_test_clock_advance_within_stop_time_py(mut test_clock: TestClock) {
387 Python::initialize();
388 Python::attach(|_py| {
389 let callback = test_callback();
390 test_clock.register_default_handler(callback);
391
392 let timer_name = "TEST_TIME1";
393 test_clock
394 .set_timer_ns(
395 timer_name,
396 1,
397 Some(UnixNanos::from(1)),
398 Some(UnixNanos::from(3)),
399 None,
400 None,
401 None,
402 )
403 .unwrap();
404 test_clock.advance_time(2.into(), true);
405
406 assert_eq!(test_clock.timer_names(), [timer_name]);
407 assert_eq!(test_clock.timer_count(), 1);
408 });
409 }
410
411 #[rstest]
412 fn test_test_clock_advance_time_to_stop_time_with_set_time_true(mut test_clock: TestClock) {
413 Python::initialize();
414 Python::attach(|_py| {
415 let callback = test_callback();
416 test_clock.register_default_handler(callback);
417
418 test_clock
419 .set_timer_ns(
420 "TEST_TIME1",
421 2,
422 None,
423 Some(UnixNanos::from(3)),
424 None,
425 None,
426 None,
427 )
428 .unwrap();
429 test_clock.advance_time(3.into(), true);
430
431 assert_eq!(test_clock.timer_names().len(), 1);
432 assert_eq!(test_clock.timer_count(), 1);
433 assert_eq!(test_clock.get_time_ns(), 3);
434 });
435 }
436
437 #[rstest]
438 fn test_test_clock_advance_time_to_stop_time_with_set_time_false(mut test_clock: TestClock) {
439 Python::initialize();
440 Python::attach(|_py| {
441 let callback = test_callback();
442 test_clock.register_default_handler(callback);
443
444 test_clock
445 .set_timer_ns(
446 "TEST_TIME1",
447 2,
448 None,
449 Some(UnixNanos::from(3)),
450 None,
451 None,
452 None,
453 )
454 .unwrap();
455 test_clock.advance_time(3.into(), false);
456
457 assert_eq!(test_clock.timer_names().len(), 1);
458 assert_eq!(test_clock.timer_count(), 1);
459 assert_eq!(test_clock.get_time_ns(), 0);
460 });
461 }
462
463 #[rstest]
468 fn test_live_clock_py_set_time_alert() {
469 ensure_sender();
470
471 Python::initialize();
472 Python::attach(|_py| {
473 let mut py_clock = PyClock::new_live();
474 let callback = test_py_callback();
475 py_clock.py_register_default_handler(callback);
476 let dt = Utc::now() + Duration::seconds(1);
477
478 py_clock
479 .py_set_time_alert("ALERT1", dt, None, None)
480 .expect("live set_time_alert failed");
481 });
482 }
483
484 #[rstest]
485 fn test_live_clock_py_set_timer() {
486 ensure_sender();
487
488 Python::initialize();
489 Python::attach(|_py| {
490 let mut py_clock = PyClock::new_live();
491 let callback = test_py_callback();
492 py_clock.py_register_default_handler(callback);
493 let interval = Duration::seconds(3);
494
495 py_clock
496 .py_set_timer("TIMER1", interval, None, None, None, None, None)
497 .expect("live set_timer failed");
498 });
499 }
500
501 #[rstest]
502 fn test_live_clock_py_set_time_alert_ns() {
503 ensure_sender();
504
505 Python::initialize();
506 Python::attach(|_py| {
507 let mut py_clock = PyClock::new_live();
508 let callback = test_py_callback();
509 py_clock.py_register_default_handler(callback);
510 let dt_ns = (Utc::now() + Duration::seconds(1))
511 .timestamp_nanos_opt()
512 .unwrap() as u64;
513
514 py_clock
515 .py_set_time_alert_ns("ALERT_NS", dt_ns, None, None)
516 .expect("live set_time_alert_ns failed");
517 });
518 }
519
520 #[rstest]
521 fn test_live_clock_py_set_timer_ns() {
522 ensure_sender();
523
524 Python::initialize();
525 Python::attach(|_py| {
526 let mut py_clock = PyClock::new_live();
527 let callback = test_py_callback();
528 py_clock.py_register_default_handler(callback);
529 let interval_ns = 1_000_000_000_u64; py_clock
532 .py_set_timer_ns("TIMER_NS", interval_ns, None, None, None, None, None)
533 .expect("live set_timer_ns failed");
534 });
535 }
536}