Skip to main content

nautilus_finfeed/python/
query.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.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
16//! Python constructors for the bounded REST queries.
17
18use jiff::Timestamp;
19use nautilus_core::python::to_pyvalue_err;
20use pyo3::prelude::*;
21
22use crate::http::query::{
23    ActiveQuery, ActivityQuery, FlatFileOhlcvQuery, HistoryQuery, ListingsQuery, OhlcvQuery,
24    Pagination,
25};
26
27#[pymethods]
28#[pyo3_stub_gen::derive::gen_stub_pymethods]
29impl ListingsQuery {
30    /// Full listings use an opaque cursor, not a page number.
31    #[new]
32    #[pyo3(signature = (limit, cursor=None))]
33    fn py_new(limit: u32, cursor: Option<String>) -> Self {
34        Self { limit, cursor }
35    }
36
37    /// Maximum records per page, in `[1, 10000]`.
38    #[getter(limit)]
39    fn py_limit(&self) -> u32 {
40        self.limit
41    }
42
43    /// Nonempty continuation cursor; `None` starts at the first page.
44    #[getter(cursor)]
45    fn py_cursor(&self) -> Option<String> {
46        self.cursor.clone()
47    }
48}
49
50#[pymethods]
51#[pyo3_stub_gen::derive::gen_stub_pymethods]
52impl ActiveQuery {
53    /// Active IDs use a one-based page number.
54    #[new]
55    fn py_new(limit: u32, page: u32) -> Self {
56        Self { limit, page }
57    }
58
59    /// Maximum IDs per page, in `[1, 10000]`.
60    #[getter(limit)]
61    fn py_limit(&self) -> u32 {
62        self.limit
63    }
64
65    /// One-based page number, in `[1, 2147483647]`.
66    #[getter(page)]
67    fn py_page(&self) -> u32 {
68        self.page
69    }
70}
71
72#[pymethods]
73#[pyo3_stub_gen::derive::gen_stub_pymethods]
74impl ActivityQuery {
75    /// Per-list record limit for latest activity.
76    #[new]
77    fn py_new(limit: u32) -> Self {
78        Self { limit }
79    }
80
81    /// Maximum records in each trade and quote list, independently, in `[1, 10000]`.
82    #[getter(limit)]
83    fn py_limit(&self) -> u32 {
84        self.limit
85    }
86}
87
88#[pymethods]
89#[pyo3_stub_gen::derive::gen_stub_pymethods]
90impl HistoryQuery {
91    /// One historical response, selected by a date or a start and optional end time.
92    ///
93    /// Date and time bounds are mutually exclusive. No filtering, bound inclusion, or completeness
94    /// guarantee is inferred from the provider's response.
95    /// Trade, quote, and book history reject bounded selectors within one UTC hour. Use covering
96    /// UTC-hour bounds and filter the raw records locally. Date and start-only selectors are accepted.
97    #[new]
98    #[pyo3(signature = (limit, date=None, time_start=None, time_end=None))]
99    fn py_new(
100        limit: u32,
101        date: Option<&str>,
102        time_start: Option<&str>,
103        time_end: Option<&str>,
104    ) -> PyResult<Self> {
105        let date = date
106            .map(str::parse)
107            .transpose()
108            .map_err(|_| to_pyvalue_err("invalid date"))?;
109        let (time_start, time_end) = parse_times(time_start, time_end)?;
110        Ok(Self {
111            date,
112            time_start,
113            time_end,
114            limit,
115        })
116    }
117
118    /// Maximum response records, in `[1, 10000]`.
119    #[getter(limit)]
120    fn py_limit(&self) -> u32 {
121        self.limit
122    }
123
124    /// UTC date selector; mutually exclusive with time bounds.
125    #[getter(date)]
126    fn py_date(&self) -> Option<String> {
127        self.date.map(|date| date.to_string())
128    }
129
130    /// Start timestamp; required when `date` is absent.
131    #[getter(time_start)]
132    fn py_time_start(&self) -> Option<String> {
133        self.time_start.map(|time| time.to_string())
134    }
135
136    /// Optional end timestamp, strictly after `time_start` when both are present.
137    #[getter(time_end)]
138    fn py_time_end(&self) -> Option<String> {
139        self.time_end.map(|time| time.to_string())
140    }
141}
142
143#[pymethods]
144#[pyo3_stub_gen::derive::gen_stub_pymethods]
145impl FlatFileOhlcvQuery {
146    /// Flat-file OHLCV selected by a date or a start and optional end time.
147    ///
148    /// The provider describes these bars as trade-generated. `period` accepts `1SEC`, `1MIN`,
149    /// or `1HRS`. The history limit is in `[1, 10000]`.
150    /// This query selects the activity flat-file source, independently of DB-backed OHLCV.
151    #[new]
152    #[pyo3(signature = (period, limit, date=None, time_start=None, time_end=None))]
153    fn py_new(
154        period: &str,
155        limit: u32,
156        date: Option<&str>,
157        time_start: Option<&str>,
158        time_end: Option<&str>,
159    ) -> PyResult<Self> {
160        let history = HistoryQuery::py_new(limit, date, time_start, time_end)?;
161        Ok(Self {
162            period: period.into(),
163            history,
164        })
165    }
166
167    /// Flat-file aggregation period: `1SEC`, `1MIN`, or `1HRS`.
168    #[getter(period)]
169    fn py_period(&self) -> String {
170        self.period.to_string()
171    }
172
173    /// Maximum response records, in `[1, 10000]`.
174    #[getter(limit)]
175    fn py_limit(&self) -> u32 {
176        self.history.limit
177    }
178
179    /// UTC date selector; mutually exclusive with time bounds.
180    #[getter(date)]
181    fn py_date(&self) -> Option<String> {
182        self.history.py_date()
183    }
184
185    /// Start timestamp; required when `date` is absent.
186    #[getter(time_start)]
187    fn py_time_start(&self) -> Option<String> {
188        self.history.py_time_start()
189    }
190
191    /// Optional end timestamp, strictly after `time_start` when both are present.
192    #[getter(time_end)]
193    fn py_time_end(&self) -> Option<String> {
194        self.history.py_time_end()
195    }
196}
197
198#[pymethods]
199#[pyo3_stub_gen::derive::gen_stub_pymethods]
200impl OhlcvQuery {
201    /// OHLCV query; `get_ohlcv_latest` rejects time bounds locally.
202    ///
203    /// Exchange-wide history requires both time bounds, at most 24 hours apart, and a limit
204    /// in `[1, 10000]`. Per-market operations accept limits in `[1, 100000]`.
205    #[new]
206    #[pyo3(signature = (period_id, limit, time_start=None, time_end=None))]
207    fn py_new(
208        period_id: &str,
209        limit: u32,
210        time_start: Option<&str>,
211        time_end: Option<&str>,
212    ) -> PyResult<Self> {
213        let (time_start, time_end) = parse_times(time_start, time_end)?;
214        Ok(Self {
215            period_id: period_id.into(),
216            time_start,
217            time_end,
218            limit,
219        })
220    }
221
222    /// Nonblank identifier from the provider period catalog.
223    #[getter(period_id)]
224    fn py_period_id(&self) -> String {
225        self.period_id.to_string()
226    }
227
228    /// Maximum rows: `[1, 100000]` per market or `[1, 10000]` for exchange-wide history.
229    #[getter(limit)]
230    fn py_limit(&self) -> u32 {
231        self.limit
232    }
233
234    /// Optional start timestamp; required for exchange-wide history and rejected for latest bars.
235    #[getter(time_start)]
236    fn py_time_start(&self) -> Option<String> {
237        self.time_start.map(|time| time.to_string())
238    }
239
240    /// Optional end timestamp; required for exchange-wide history and rejected for latest bars.
241    #[getter(time_end)]
242    fn py_time_end(&self) -> Option<String> {
243        self.time_end.map(|time| time.to_string())
244    }
245}
246
247#[pymethods]
248#[pyo3_stub_gen::derive::gen_stub_pymethods]
249impl Pagination {
250    /// Bounds on a complete discovery traversal; exceeding either returns an error.
251    #[new]
252    fn py_new(max_pages: u32, max_records: usize) -> Self {
253        Self {
254            max_pages,
255            max_records,
256        }
257    }
258
259    /// Maximum requests in the traversal, including the terminal page; must be positive.
260    #[getter(max_pages)]
261    fn py_max_pages(&self) -> u32 {
262        self.max_pages
263    }
264
265    /// Maximum total records retained across pages; must be positive.
266    #[getter(max_records)]
267    fn py_max_records(&self) -> usize {
268        self.max_records
269    }
270}
271
272pub(super) fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
273    m.add_class::<ListingsQuery>()?;
274    m.add_class::<ActiveQuery>()?;
275    m.add_class::<ActivityQuery>()?;
276    m.add_class::<HistoryQuery>()?;
277    m.add_class::<FlatFileOhlcvQuery>()?;
278    m.add_class::<OhlcvQuery>()?;
279    m.add_class::<Pagination>()?;
280    Ok(())
281}
282
283fn parse_times(
284    start: Option<&str>,
285    end: Option<&str>,
286) -> PyResult<(Option<Timestamp>, Option<Timestamp>)> {
287    let start = start
288        .map(str::parse)
289        .transpose()
290        .map_err(|_| to_pyvalue_err("invalid time_start"))?;
291    let end = end
292        .map(str::parse)
293        .transpose()
294        .map_err(|_| to_pyvalue_err("invalid time_end"))?;
295    Ok((start, end))
296}