nautilus_common/python/
clock.rs

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
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2024 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

use nautilus_core::nanos::UnixNanos;
use pyo3::prelude::*;

use super::timer::TimeEventHandler_Py;
use crate::{
    clock::{Clock, LiveClock, TestClock},
    timer::{TimeEvent, TimeEventCallback},
};

/// PyO3 compatible interface for an underlying [`TestClock`].
///
/// This struct wraps `TestClock` in a way that makes it possible to create
/// Python bindings for it.
///
/// It implements the `Deref` trait, allowing instances of `TestClock_API` to be
/// dereferenced to `TestClock`, providing access to `TestClock`'s methods without
/// having to manually access the underlying `TestClock` instance.
#[allow(non_camel_case_types)]
#[pyo3::pyclass(
    module = "nautilus_trader.core.nautilus_pyo3.common",
    name = "TestClock"
)]
pub struct TestClock_Py(Box<TestClock>);

#[pymethods]
impl TestClock_Py {
    #[new]
    fn py_new() -> Self {
        Self(Box::new(TestClock::new()))
    }

    fn advance_time(&mut self, to_time_ns: u64, set_time: bool) -> Vec<TimeEvent> {
        self.0.advance_time(to_time_ns.into(), set_time)
    }

    fn match_handlers(&self, events: Vec<TimeEvent>) -> Vec<TimeEventHandler_Py> {
        self.0
            .match_handlers(events)
            .into_iter()
            .map(Into::into)
            .collect()
    }

    fn register_default_handler(&mut self, callback: PyObject) {
        self.0
            .register_default_handler(TimeEventCallback::from(callback));
    }

    #[pyo3(signature = (name, alert_time_ns, callback=None))]
    fn set_time_alert_ns(&mut self, name: &str, alert_time_ns: u64, callback: Option<PyObject>) {
        self.0.set_time_alert_ns(
            name,
            alert_time_ns.into(),
            callback.map(TimeEventCallback::from),
        );
    }

    #[pyo3(signature = (name, interval_ns, start_time_ns, stop_time_ns=None, callback=None))]
    fn set_timer_ns(
        &mut self,
        name: &str,
        interval_ns: u64,
        start_time_ns: u64,
        stop_time_ns: Option<u64>,
        callback: Option<PyObject>,
    ) {
        self.0.set_timer_ns(
            name,
            interval_ns,
            start_time_ns.into(),
            stop_time_ns.map(UnixNanos::from),
            callback.map(TimeEventCallback::from),
        );
    }

    fn next_time_ns(&self, name: &str) -> u64 {
        *self.0.next_time_ns(name)
    }

    fn cancel_timer(&mut self, name: &str) {
        self.0.cancel_timer(name);
    }

    fn cancel_timers(&mut self) {
        self.0.cancel_timers();
    }
}

/// PyO3 compatible interface for an underlying [`LiveClock`].
///
/// This struct wraps `LiveClock` in a way that makes it possible to create
/// Python bindings for it.
///
/// It implements the `Deref` trait, allowing instances of `LiveClock_Py` to be
/// dereferenced to `LiveClock`, providing access to `LiveClock`'s methods without
/// having to manually access the underlying `LiveClock` instance.
#[allow(non_camel_case_types)]
#[pyo3::pyclass(
    module = "nautilus_trader.core.nautilus_pyo3.common",
    name = "LiveClock"
)]
pub struct LiveClock_Py(Box<LiveClock>);

#[pymethods]
impl LiveClock_Py {
    #[new]
    fn py_new() -> Self {
        Self(Box::new(LiveClock::new()))
    }

    fn register_default_handler(&mut self, callback: PyObject) {
        self.0
            .register_default_handler(TimeEventCallback::from(callback));
    }

    #[pyo3(signature = (name, alert_time_ns, callback=None))]
    fn set_time_alert_ns(&mut self, name: &str, alert_time_ns: u64, callback: Option<PyObject>) {
        self.0.set_time_alert_ns(
            name,
            alert_time_ns.into(),
            callback.map(TimeEventCallback::from),
        );
    }

    #[pyo3(signature = (name, interval_ns, start_time_ns, stop_time_ns=None, callback=None))]
    fn set_timer_ns(
        &mut self,
        name: &str,
        interval_ns: u64,
        start_time_ns: u64,
        stop_time_ns: Option<u64>,
        callback: Option<PyObject>,
    ) {
        self.0.set_timer_ns(
            name,
            interval_ns,
            start_time_ns.into(),
            stop_time_ns.map(UnixNanos::from),
            callback.map(TimeEventCallback::from),
        );
    }

    fn next_time_ns(&self, name: &str) -> u64 {
        *self.0.next_time_ns(name)
    }

    fn cancel_timer(&mut self, name: &str) {
        self.0.cancel_timer(name);
    }

    fn cancel_timers(&mut self) {
        self.0.cancel_timers();
    }
}

////////////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////////////
#[cfg(test)]
mod tests {
    use nautilus_core::nanos::UnixNanos;
    use pyo3::{prelude::*, types::PyList};
    use rstest::*;

    use crate::{
        clock::{Clock, TestClock},
        timer::TimeEventCallback,
    };

    #[fixture]
    pub fn test_clock() -> TestClock {
        TestClock::new()
    }

    pub fn test_callback() -> TimeEventCallback {
        Python::with_gil(|py| {
            let py_list = PyList::empty_bound(py);
            let py_append = Py::from(py_list.getattr("append").unwrap());
            TimeEventCallback::from(py_append.into_py(py))
        })
    }

    #[rstest]
    fn test_set_timer_ns_py(mut test_clock: TestClock) {
        pyo3::prepare_freethreaded_python();

        Python::with_gil(|_py| {
            let callback = test_callback();
            test_clock.register_default_handler(callback);

            let timer_name = "TEST_TIME1";
            test_clock.set_timer_ns(timer_name, 10, 0.into(), None, None);

            assert_eq!(test_clock.timer_names(), [timer_name]);
            assert_eq!(test_clock.timer_count(), 1);
        });
    }

    #[rstest]
    fn test_cancel_timer(mut test_clock: TestClock) {
        pyo3::prepare_freethreaded_python();

        Python::with_gil(|_py| {
            let callback = test_callback();
            test_clock.register_default_handler(callback);

            let timer_name = "TEST_TIME1";
            test_clock.set_timer_ns(timer_name, 10, 0.into(), None, None);
            test_clock.cancel_timer(timer_name);

            assert!(test_clock.timer_names().is_empty());
            assert_eq!(test_clock.timer_count(), 0);
        });
    }

    #[rstest]
    fn test_cancel_timers(mut test_clock: TestClock) {
        pyo3::prepare_freethreaded_python();

        Python::with_gil(|_py| {
            let callback = test_callback();
            test_clock.register_default_handler(callback);

            let timer_name = "TEST_TIME1";
            test_clock.set_timer_ns(timer_name, 10, 0.into(), None, None);
            test_clock.cancel_timers();

            assert!(test_clock.timer_names().is_empty());
            assert_eq!(test_clock.timer_count(), 0);
        });
    }

    #[rstest]
    fn test_advance_within_stop_time_py(mut test_clock: TestClock) {
        pyo3::prepare_freethreaded_python();

        Python::with_gil(|_py| {
            let callback = test_callback();
            test_clock.register_default_handler(callback);

            let timer_name = "TEST_TIME1";
            test_clock.set_timer_ns(timer_name, 1, 1.into(), Some(UnixNanos::from(3)), None);
            test_clock.advance_time(2.into(), true);

            assert_eq!(test_clock.timer_names(), [timer_name]);
            assert_eq!(test_clock.timer_count(), 1);
        });
    }

    #[rstest]
    fn test_advance_time_to_stop_time_with_set_time_true(mut test_clock: TestClock) {
        pyo3::prepare_freethreaded_python();

        Python::with_gil(|_py| {
            let callback = test_callback();
            test_clock.register_default_handler(callback);

            test_clock.set_timer_ns("TEST_TIME1", 2, 0.into(), Some(UnixNanos::from(3)), None);
            test_clock.advance_time(3.into(), true);

            assert_eq!(test_clock.timer_names().len(), 1);
            assert_eq!(test_clock.timer_count(), 1);
            assert_eq!(test_clock.get_time_ns(), 3);
        });
    }

    #[rstest]
    fn test_advance_time_to_stop_time_with_set_time_false(mut test_clock: TestClock) {
        pyo3::prepare_freethreaded_python();

        Python::with_gil(|_py| {
            let callback = test_callback();
            test_clock.register_default_handler(callback);

            test_clock.set_timer_ns("TEST_TIME1", 2, 0.into(), Some(UnixNanos::from(3)), None);
            test_clock.advance_time(3.into(), false);

            assert_eq!(test_clock.timer_names().len(), 1);
            assert_eq!(test_clock.timer_count(), 1);
            assert_eq!(test_clock.get_time_ns(), 0);
        });
    }
}