nautilus_trading/python/
sessions.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3//  https://poseitrader.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::str::FromStr;
17
18use chrono::{DateTime, Utc};
19use chrono_tz::Tz;
20use nautilus_core::python::to_pyvalue_err;
21use nautilus_model::python::common::EnumIterator;
22use pyo3::{PyTypeInfo, prelude::*, types::PyType};
23
24use crate::sessions::{
25    ForexSession, fx_local_from_utc, fx_next_end, fx_next_start, fx_prev_end, fx_prev_start,
26};
27
28#[pymethods]
29impl ForexSession {
30    #[new]
31    fn py_new(py: Python<'_>, value: &Bound<'_, PyAny>) -> PyResult<Self> {
32        let t = Self::type_object(py);
33        Self::py_from_str(&t, value)
34    }
35
36    const fn __hash__(&self) -> isize {
37        *self as isize
38    }
39
40    fn __repr__(&self) -> String {
41        format!(
42            "<{}.{}: '{}'>",
43            stringify!(PositionSide),
44            self.name(),
45            self.value(),
46        )
47    }
48
49    fn __str__(&self) -> String {
50        self.to_string()
51    }
52
53    #[getter]
54    #[must_use]
55    pub fn name(&self) -> String {
56        self.to_string()
57    }
58
59    #[getter]
60    #[must_use]
61    pub const fn value(&self) -> u8 {
62        *self as u8
63    }
64
65    #[classmethod]
66    fn variants(_: &Bound<'_, PyType>, py: Python<'_>) -> EnumIterator {
67        EnumIterator::new::<Self>(py)
68    }
69
70    #[classmethod]
71    #[pyo3(name = "from_str")]
72    fn py_from_str(_: &Bound<'_, PyType>, data: &Bound<'_, PyAny>) -> PyResult<Self> {
73        let data_str: &str = data.extract()?;
74        let tokenized = data_str.to_uppercase();
75        Self::from_str(&tokenized).map_err(to_pyvalue_err)
76    }
77
78    #[classattr]
79    #[pyo3(name = "SYDNEY")]
80    const fn py_no_position_side() -> Self {
81        Self::Sydney
82    }
83
84    #[classattr]
85    #[pyo3(name = "TOKYO")]
86    const fn py_flat() -> Self {
87        Self::Tokyo
88    }
89
90    #[classattr]
91    #[pyo3(name = "LONDON")]
92    const fn py_long() -> Self {
93        Self::London
94    }
95
96    #[classattr]
97    #[pyo3(name = "NEW_YORK")]
98    const fn py_short() -> Self {
99        Self::NewYork
100    }
101}
102
103/// Converts a UTC timestamp to the local time for the given Forex session.
104///
105/// The `time_now` must be timezone-aware with its tzinfo set to a built-in `datetime.timezone`
106/// (e.g. `datetime.timezone.utc`). Third-party tzinfo objects (like those from `pytz`) are not supported.
107///
108/// # Errors
109///
110/// Returns a `PyErr` if an error occurs during session conversion or value conversion to Python.
111#[pyfunction]
112#[pyo3(name = "fx_local_from_utc")]
113pub fn py_fx_local_from_utc(
114    session: ForexSession,
115    time_now: DateTime<Utc>,
116) -> PyResult<DateTime<Tz>> {
117    Ok(fx_local_from_utc(session, time_now))
118}
119
120/// Returns the next session start time in UTC.
121///
122/// The `time_now` must be timezone-aware with its tzinfo set to a built-in `datetime.timezone`
123/// (e.g. `datetime.timezone.utc`). Third-party tzinfo objects (like those from `pytz`) are not supported.
124///
125/// # Errors
126///
127/// Returns a `PyErr` if an error occurs during session conversion or value conversion to Python.
128#[pyfunction]
129#[pyo3(name = "fx_next_start")]
130pub fn py_fx_next_start(session: ForexSession, time_now: DateTime<Utc>) -> PyResult<DateTime<Utc>> {
131    Ok(fx_next_start(session, time_now))
132}
133
134/// Returns the next session end time in UTC.
135///
136/// The `time_now` must be timezone-aware with its tzinfo set to a built-in `datetime.timezone`
137/// (e.g. `datetime.timezone.utc`). Third-party tzinfo objects (like those from `pytz`) are not supported.
138///
139/// # Errors
140///
141/// Returns a `PyErr` if an error occurs during session conversion or value conversion to Python.
142#[pyfunction]
143#[pyo3(name = "fx_next_end")]
144pub fn py_fx_next_end(session: ForexSession, time_now: DateTime<Utc>) -> PyResult<DateTime<Utc>> {
145    Ok(fx_next_end(session, time_now))
146}
147
148/// Returns the previous session start time in UTC.
149///
150/// The `time_now` must be timezone-aware with its tzinfo set to a built-in `datetime.timezone`
151/// (e.g. `datetime.timezone.utc`). Third-party tzinfo objects (like those from `pytz`) are not supported.
152///
153/// # Errors
154///
155/// Returns a `PyErr` if an error occurs during session conversion or value conversion to Python.
156#[pyfunction]
157#[pyo3(name = "fx_prev_start")]
158pub fn py_fx_prev_start(session: ForexSession, time_now: DateTime<Utc>) -> PyResult<DateTime<Utc>> {
159    Ok(fx_prev_start(session, time_now))
160}
161
162/// Returns the previous session end time in UTC.
163///
164/// The `time_now` must be timezone-aware with its tzinfo set to a built-in `datetime.timezone`
165/// (e.g. `datetime.timezone.utc`). Third-party tzinfo objects (like those from `pytz`) are not supported.
166///
167/// # Errors
168///
169/// Returns a `PyErr` if an error occurs during session conversion or value conversion to Python.
170#[pyfunction]
171#[pyo3(name = "fx_prev_end")]
172pub fn py_fx_prev_end(session: ForexSession, time_now: DateTime<Utc>) -> PyResult<DateTime<Utc>> {
173    Ok(fx_prev_end(session, time_now))
174}