Skip to main content

nautilus_finfeed/http/
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//! Typed queries with endpoint-specific bounds and exact provider time serialization.
17
18use jiff::{Timestamp, civil::Date};
19use serde::{Serialize, Serializer};
20
21use super::error::Error;
22use crate::common::enums::OhlcvInterval;
23
24/// Maximum listing, active-ID, activity, and historical trade/quote/book page size.
25pub const PAGE_LIMIT_MAX: u32 = 10_000;
26/// Maximum market OHLCV page size.
27pub const OHLCV_LIMIT_MAX: u32 = 100_000;
28
29pub(crate) const HOUR_SECONDS: i64 = 3600;
30
31/// Full listings use an opaque cursor, not a page number.
32#[derive(Debug, Clone, Serialize)]
33#[cfg_attr(
34    feature = "python",
35    pyo3::pyclass(
36        name = "FinFeedListingsQuery",
37        module = "nautilus_trader.adapters.finfeed",
38        frozen,
39        from_py_object
40    )
41)]
42#[cfg_attr(
43    feature = "python",
44    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.finfeed")
45)]
46pub struct ListingsQuery {
47    /// Maximum records per page, in `[1, 10000]`.
48    pub limit: u32,
49    /// Nonempty continuation cursor; `None` starts at the first page.
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub cursor: Option<String>,
52}
53
54impl ListingsQuery {
55    pub(super) fn validate(&self) -> Result<(), Error> {
56        validate_limit(self.limit, PAGE_LIMIT_MAX)?;
57
58        if self.cursor.as_ref().is_some_and(|cursor| cursor.is_empty()) {
59            return Err(Error::Validation("cursor must not be empty".into()));
60        }
61
62        Ok(())
63    }
64}
65
66/// Active IDs use a one-based page number.
67#[derive(Debug, Clone, Serialize)]
68#[cfg_attr(
69    feature = "python",
70    pyo3::pyclass(
71        name = "FinFeedActiveQuery",
72        module = "nautilus_trader.adapters.finfeed",
73        frozen,
74        from_py_object
75    )
76)]
77#[cfg_attr(
78    feature = "python",
79    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.finfeed")
80)]
81pub struct ActiveQuery {
82    /// Maximum IDs per page, in `[1, 10000]`.
83    pub limit: u32,
84    /// One-based page number, in `[1, 2147483647]`.
85    pub page: u32,
86}
87
88impl ActiveQuery {
89    pub(super) fn validate(&self) -> Result<(), Error> {
90        validate_limit(self.limit, PAGE_LIMIT_MAX)?;
91
92        if self.page == 0 || self.page > i32::MAX as u32 {
93            return Err(Error::Validation(
94                "page must be a positive signed 32-bit integer".into(),
95            ));
96        }
97
98        Ok(())
99    }
100}
101
102/// Per-list record limit for latest activity.
103#[derive(Debug, Clone, Serialize)]
104#[cfg_attr(
105    feature = "python",
106    pyo3::pyclass(
107        name = "FinFeedActivityQuery",
108        module = "nautilus_trader.adapters.finfeed",
109        frozen,
110        from_py_object
111    )
112)]
113#[cfg_attr(
114    feature = "python",
115    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.finfeed")
116)]
117pub struct ActivityQuery {
118    /// Maximum records in each trade and quote list, independently, in `[1, 10000]`.
119    pub limit: u32,
120}
121
122impl ActivityQuery {
123    pub(super) fn validate(&self) -> Result<(), Error> {
124        validate_limit(self.limit, PAGE_LIMIT_MAX)
125    }
126}
127
128/// One historical response, selected by a date or a start and optional end time.
129///
130/// Date and time bounds are mutually exclusive. No filtering, bound inclusion, or completeness
131/// guarantee is inferred from the provider's response.
132/// Trade, quote, and book history reject bounded selectors within one UTC hour. Use covering
133/// UTC-hour bounds and filter the raw records locally. Date and start-only selectors are accepted.
134#[derive(Debug, Clone, Serialize)]
135#[cfg_attr(
136    feature = "python",
137    pyo3::pyclass(
138        name = "FinFeedHistoryQuery",
139        module = "nautilus_trader.adapters.finfeed",
140        frozen,
141        from_py_object
142    )
143)]
144#[cfg_attr(
145    feature = "python",
146    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.finfeed")
147)]
148pub struct HistoryQuery {
149    /// UTC date selector; mutually exclusive with time bounds.
150    #[serde(skip_serializing_if = "Option::is_none")]
151    pub date: Option<Date>,
152    /// Start timestamp; required when `date` is absent.
153    #[serde(
154        skip_serializing_if = "Option::is_none",
155        serialize_with = "serialize_time"
156    )]
157    pub time_start: Option<Timestamp>,
158    /// Optional end timestamp, strictly after `time_start` when both are present.
159    #[serde(
160        skip_serializing_if = "Option::is_none",
161        serialize_with = "serialize_time"
162    )]
163    pub time_end: Option<Timestamp>,
164    /// Maximum response records, in `[1, 10000]`.
165    pub limit: u32,
166}
167
168impl HistoryQuery {
169    pub(super) fn validate(&self) -> Result<(), Error> {
170        validate_limit(self.limit, PAGE_LIMIT_MAX)?;
171
172        if self.date.is_some() {
173            if self.time_start.is_some() || self.time_end.is_some() {
174                return Err(Error::Validation(
175                    "date and time bounds are mutually exclusive".into(),
176                ));
177            }
178        } else if self.time_start.is_none() {
179            return Err(Error::Validation("date or time_start is required".into()));
180        }
181
182        validate_times(self.time_start, self.time_end)
183    }
184
185    pub(super) fn validate_hourly(&self) -> Result<(), Error> {
186        self.validate()?;
187
188        if self
189            .time_start
190            .zip(self.time_end)
191            .is_some_and(|(start, end)| {
192                start.as_second().div_euclid(HOUR_SECONDS)
193                    == end.as_second().div_euclid(HOUR_SECONDS)
194            })
195        {
196            return Err(Error::Validation(
197                "history time bounds must cross a UTC hour boundary; FinFeed can return empty data for ranges within one hour; use date or covering UTC-hour bounds and filter locally".into(),
198            ));
199        }
200
201        Ok(())
202    }
203}
204
205/// Flat-file OHLCV selected by a date or a start and optional end time.
206///
207/// The provider describes these bars as trade-generated. `period` accepts `1SEC`, `1MIN`,
208/// or `1HRS`. The history limit is in `[1, 10000]`.
209/// This query selects the activity flat-file source, independently of DB-backed OHLCV.
210#[derive(Debug, Clone, Serialize)]
211#[cfg_attr(
212    feature = "python",
213    pyo3::pyclass(
214        name = "FinFeedFlatFileOhlcvQuery",
215        module = "nautilus_trader.adapters.finfeed",
216        frozen,
217        from_py_object
218    )
219)]
220#[cfg_attr(
221    feature = "python",
222    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.finfeed")
223)]
224pub struct FlatFileOhlcvQuery {
225    /// Flat-file aggregation period: `1SEC`, `1MIN`, or `1HRS`.
226    pub period: OhlcvInterval,
227    /// Date or time selectors and response limit for the flat-file source.
228    #[serde(flatten)]
229    pub history: HistoryQuery,
230}
231
232impl FlatFileOhlcvQuery {
233    pub(super) fn validate(&self) -> Result<(), Error> {
234        let period = OhlcvInterval::from(self.period.as_ref());
235
236        if !matches!(
237            period,
238            OhlcvInterval::Second1 | OhlcvInterval::Minute1 | OhlcvInterval::Hour1
239        ) {
240            return Err(Error::Validation(
241                "flat-file period must be 1SEC, 1MIN, or 1HRS".into(),
242            ));
243        }
244
245        self.history.validate()
246    }
247}
248
249/// OHLCV query; `get_ohlcv_latest` rejects time bounds locally.
250///
251/// Exchange-wide history requires both time bounds, at most 24 hours apart, and a limit
252/// in `[1, 10000]`. Per-market operations accept limits in `[1, 100000]`.
253#[derive(Debug, Clone, Serialize)]
254#[cfg_attr(
255    feature = "python",
256    pyo3::pyclass(
257        name = "FinFeedOhlcvQuery",
258        module = "nautilus_trader.adapters.finfeed",
259        frozen,
260        from_py_object
261    )
262)]
263#[cfg_attr(
264    feature = "python",
265    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.finfeed")
266)]
267pub struct OhlcvQuery {
268    /// Nonblank identifier from the provider period catalog.
269    pub period_id: OhlcvInterval,
270    /// Optional start timestamp; required for exchange-wide history and rejected for latest bars.
271    #[serde(
272        skip_serializing_if = "Option::is_none",
273        serialize_with = "serialize_time"
274    )]
275    pub time_start: Option<Timestamp>,
276    /// Optional end timestamp; required for exchange-wide history and rejected for latest bars.
277    #[serde(
278        skip_serializing_if = "Option::is_none",
279        serialize_with = "serialize_time"
280    )]
281    pub time_end: Option<Timestamp>,
282    /// Maximum rows: `[1, 100000]` per market or `[1, 10000]` for exchange-wide history.
283    pub limit: u32,
284}
285
286impl OhlcvQuery {
287    pub(super) fn validate(&self, latest: bool) -> Result<(), Error> {
288        validate_limit(self.limit, OHLCV_LIMIT_MAX)?;
289
290        if self.period_id.as_ref().trim().is_empty()
291            || (latest && (self.time_start.is_some() || self.time_end.is_some()))
292        {
293            return Err(Error::Validation(
294                "period_id is required and latest cannot carry time bounds".into(),
295            ));
296        }
297
298        validate_times(self.time_start, self.time_end)
299    }
300
301    pub(super) fn validate_exchange(&self) -> Result<(), Error> {
302        validate_limit(self.limit, PAGE_LIMIT_MAX)?;
303        self.validate(false)?;
304
305        let (Some(start), Some(end)) = (self.time_start, self.time_end) else {
306            return Err(Error::Validation(
307                "exchange OHLCV requires time_start and time_end".into(),
308            ));
309        };
310
311        if end.as_nanosecond() - start.as_nanosecond() > 86_400_000_000_000 {
312            return Err(Error::Validation(
313                "exchange OHLCV window must not exceed 24 hours".into(),
314            ));
315        }
316
317        Ok(())
318    }
319}
320
321/// Bounds on a complete discovery traversal; exceeding either returns an error.
322#[derive(Debug, Clone, Copy)]
323#[cfg_attr(
324    feature = "python",
325    pyo3::pyclass(
326        name = "FinFeedPagination",
327        module = "nautilus_trader.adapters.finfeed",
328        frozen,
329        from_py_object
330    )
331)]
332#[cfg_attr(
333    feature = "python",
334    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.finfeed")
335)]
336pub struct Pagination {
337    /// Maximum requests in the traversal, including the terminal page; must be positive.
338    pub max_pages: u32,
339    /// Maximum total records retained across pages; must be positive.
340    pub max_records: usize,
341}
342
343impl Pagination {
344    pub(super) fn validate(&self) -> Result<(), Error> {
345        if self.max_pages == 0 || self.max_records == 0 {
346            return Err(Error::Validation(
347                "pagination bounds must be positive".into(),
348            ));
349        }
350
351        Ok(())
352    }
353}
354
355fn validate_limit(limit: u32, maximum: u32) -> Result<(), Error> {
356    if !(1..=maximum).contains(&limit) {
357        return Err(Error::Validation(format!(
358            "limit must be in [1, {maximum}]"
359        )));
360    }
361
362    Ok(())
363}
364
365fn validate_times(start: Option<Timestamp>, end: Option<Timestamp>) -> Result<(), Error> {
366    if start.zip(end).is_some_and(|(start, end)| start >= end) {
367        return Err(Error::Validation("time_start must precede time_end".into()));
368    }
369
370    if start
371        .into_iter()
372        .chain(end)
373        .any(|time| time.subsec_nanosecond() % 100 != 0)
374    {
375        return Err(Error::Validation(
376            "timestamps must fit the provider's 100 ns precision".into(),
377        ));
378    }
379
380    Ok(())
381}
382
383fn serialize_time<S: Serializer>(
384    time: &Option<Timestamp>,
385    serializer: S,
386) -> Result<S::Ok, S::Error> {
387    match time {
388        Some(time) => serializer.collect_str(&format_args!("{time:.7}")),
389        None => serializer.serialize_none(),
390    }
391}
392
393#[cfg(test)]
394mod tests {
395    use rstest::rstest;
396
397    use super::*;
398
399    #[rstest]
400    #[case(OhlcvInterval::Second1, true)]
401    #[case(OhlcvInterval::Minute1, true)]
402    #[case(OhlcvInterval::Hour1, true)]
403    #[case(OhlcvInterval::Other("1SEC".into()), true)]
404    #[case(OhlcvInterval::Other("1MIN".into()), true)]
405    #[case(OhlcvInterval::Other("1HRS".into()), true)]
406    #[case(OhlcvInterval::Second2, false)]
407    #[case(OhlcvInterval::Other("1min".into()), false)]
408    #[case(OhlcvInterval::Other("future-period".into()), false)]
409    fn flat_file_period_validation_preserves_raw_labels(
410        #[case] period: OhlcvInterval,
411        #[case] valid: bool,
412    ) {
413        let query = FlatFileOhlcvQuery {
414            period,
415            history: HistoryQuery {
416                date: Some("2026-10-11".parse().unwrap()),
417                time_start: None,
418                time_end: None,
419                limit: 17,
420            },
421        };
422
423        let expected = if valid {
424            Ok(())
425        } else {
426            Err("Invalid FinFeed request: flat-file period must be 1SEC, 1MIN, or 1HRS".to_owned())
427        };
428
429        assert_eq!(query.validate().map_err(|e| e.to_string()), expected);
430    }
431}