nautilus_finfeed/python/http.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//! Async Python access to the read-only prediction-market client.
17
18use std::sync::Arc;
19
20use nautilus_core::python::{to_pyruntime_err, to_pyvalue_err};
21use pyo3::prelude::*;
22
23use super::models::{
24 PyFinFeedActivityBatch, PyFinFeedActivityCurrent, PyFinFeedBook, PyFinFeedBookEvent,
25 PyFinFeedExchange, PyFinFeedMarket, PyFinFeedMarketsPage, PyFinFeedOhlcv, PyFinFeedOhlcvPeriod,
26 PyFinFeedQuote, PyFinFeedTrade,
27};
28use crate::{
29 config::FinFeedDataClientConfig,
30 http::{
31 client::FinFeedHttpClient,
32 error::Error,
33 query::{
34 ActiveQuery, ActivityQuery, FlatFileOhlcvQuery, HistoryQuery, ListingsQuery,
35 OhlcvQuery, Pagination,
36 },
37 },
38};
39
40/// Read-only REST access with the HTTP controls from `FinFeedDataClientConfig`.
41///
42/// Construction resolves credentials but sends no requests. Instrument selections and polling
43/// settings are not used. Results retain raw provider semantics; `FinFeedMarket.to_instrument`
44/// performs the separate checked Nautilus mapping. Timestamps use RFC 3339 strings to retain
45/// sub-microsecond precision. Canceling an awaitable cancels that call; `cancel` permanently
46/// cancels all pending and future calls on this client.
47#[derive(Debug)]
48#[pyclass(
49 name = "FinFeedHttpClient",
50 module = "nautilus_trader.adapters.finfeed",
51 frozen
52)]
53#[pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.finfeed")]
54pub struct PyFinFeedHttpClient {
55 inner: Arc<FinFeedHttpClient>,
56}
57
58#[pymethods]
59#[pyo3_stub_gen::derive::gen_stub_pymethods]
60impl PyFinFeedHttpClient {
61 /// Authenticated read-only client returning provider models with exact decimal values.
62 ///
63 /// Construction resolves credentials without sending requests. Callers share pacing,
64 /// concurrency, retries, and a finite attempt allowance. Requests preserve provider response
65 /// order and values without native instrument mapping or automatic historical continuation.
66 #[new]
67 fn py_new(config: FinFeedDataClientConfig) -> PyResult<Self> {
68 let inner = FinFeedHttpClient::new(config.api_key, config.http).map_err(to_pyvalue_err)?;
69 Ok(Self {
70 inner: Arc::new(inner),
71 })
72 }
73
74 /// Returns the remaining local managed attempt allowance.
75 #[getter]
76 fn attempts_remaining(&self) -> u64 {
77 self.inner.attempts_remaining()
78 }
79
80 /// Permanently cancels pending and future requests, including local admission and retry waits.
81 ///
82 /// Construct a new client to make further requests.
83 fn cancel(&self) {
84 self.inner.cancel();
85 }
86
87 /// Returns the constant representation `FinFeedHttpClient`.
88 fn __repr__(&self) -> &'static str {
89 "FinFeedHttpClient"
90 }
91
92 /// Retrieves supported exchanges.
93 ///
94 /// # Errors
95 ///
96 /// Returns an error if:
97 /// - Admission, transport, HTTP status, or response decoding fails.
98 /// - The local allowance is exhausted, a deadline expires, or the request is canceled.
99 #[gen_stub(
100 override_return_type(
101 type_repr = "typing.Awaitable[list[FinFeedExchange]]",
102 imports = ("typing",),
103 ),
104 )]
105 fn get_exchanges<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
106 let client = self.inner.clone();
107 pyo3_async_runtimes::tokio::future_into_py(py, async move {
108 client
109 .get_exchanges()
110 .await
111 .map(|records| {
112 records
113 .into_iter()
114 .map(PyFinFeedExchange::from)
115 .collect::<Vec<_>>()
116 })
117 .map_err(python_error)
118 })
119 }
120
121 /// Retrieves one exchange.
122 ///
123 /// # Errors
124 ///
125 /// Returns an error if:
126 /// - Request validation, transport, HTTP status, or decoding fails.
127 /// - The local allowance is exhausted, a deadline expires, or the request is canceled.
128 #[gen_stub(
129 override_return_type(
130 type_repr = "typing.Awaitable[FinFeedExchange]",
131 imports = ("typing",),
132 ),
133 )]
134 fn get_exchange<'py>(
135 &self,
136 py: Python<'py>,
137 exchange_id: String,
138 ) -> PyResult<Bound<'py, PyAny>> {
139 let client = self.inner.clone();
140 pyo3_async_runtimes::tokio::future_into_py(py, async move {
141 client
142 .get_exchange(&exchange_id)
143 .await
144 .map(PyFinFeedExchange::from)
145 .map_err(python_error)
146 })
147 }
148
149 /// Retrieves one cursor listing page.
150 ///
151 /// # Errors
152 ///
153 /// Returns an error if:
154 /// - Request validation, transport, HTTP status, or decoding fails.
155 /// - The local allowance is exhausted, a deadline expires, or the request is canceled.
156 /// - A response exceeds the requested record limit.
157 #[gen_stub(
158 override_return_type(
159 type_repr = "typing.Awaitable[FinFeedMarketsPage]",
160 imports = ("typing",),
161 ),
162 )]
163 fn get_listings<'py>(
164 &self,
165 py: Python<'py>,
166 exchange_id: String,
167 query: ListingsQuery,
168 ) -> PyResult<Bound<'py, PyAny>> {
169 let client = self.inner.clone();
170 pyo3_async_runtimes::tokio::future_into_py(py, async move {
171 client
172 .get_listings(&exchange_id, &query)
173 .await
174 .map(PyFinFeedMarketsPage::from)
175 .map_err(python_error)
176 })
177 }
178
179 /// Retrieves one page of active IDs; absence alone does not establish resolution.
180 ///
181 /// # Errors
182 ///
183 /// Returns an error if:
184 /// - Request validation, transport, HTTP status, or decoding fails.
185 /// - The local allowance is exhausted, a deadline expires, or the request is canceled.
186 /// - A response exceeds the requested record limit.
187 #[gen_stub(
188 override_return_type(
189 type_repr = "typing.Awaitable[list[str]]",
190 imports = ("typing",),
191 ),
192 )]
193 fn get_active<'py>(
194 &self,
195 py: Python<'py>,
196 exchange_id: String,
197 query: ActiveQuery,
198 ) -> PyResult<Bound<'py, PyAny>> {
199 let client = self.inner.clone();
200 pyo3_async_runtimes::tokio::future_into_py(py, async move {
201 client
202 .get_active(&exchange_id, &query)
203 .await
204 .map(|ids| ids.iter().map(ToString::to_string).collect::<Vec<_>>())
205 .map_err(python_error)
206 })
207 }
208
209 /// Retrieves an outcome definition without native instrument mapping.
210 ///
211 /// # Errors
212 ///
213 /// Returns an error if:
214 /// - Request validation, transport, HTTP status, or decoding fails.
215 /// - The local allowance is exhausted, a deadline expires, or the request is canceled.
216 #[gen_stub(
217 override_return_type(
218 type_repr = "typing.Awaitable[FinFeedMarket]",
219 imports = ("typing",),
220 ),
221 )]
222 fn get_market<'py>(
223 &self,
224 py: Python<'py>,
225 exchange_id: String,
226 market_id: String,
227 ) -> PyResult<Bound<'py, PyAny>> {
228 let client = self.inner.clone();
229 pyo3_async_runtimes::tokio::future_into_py(py, async move {
230 client
231 .get_market(&exchange_id, &market_id)
232 .await
233 .map(PyFinFeedMarket::from)
234 .map_err(python_error)
235 })
236 }
237
238 /// Retrieves the latest trade and quote independently.
239 ///
240 /// # Errors
241 ///
242 /// Returns an error if:
243 /// - Request validation, transport, HTTP status, or decoding fails.
244 /// - The local allowance is exhausted, a deadline expires, or the request is canceled.
245 #[gen_stub(
246 override_return_type(
247 type_repr = "typing.Awaitable[FinFeedActivityCurrent]",
248 imports = ("typing",),
249 ),
250 )]
251 fn get_current<'py>(
252 &self,
253 py: Python<'py>,
254 exchange_id: String,
255 market_id: String,
256 ) -> PyResult<Bound<'py, PyAny>> {
257 let client = self.inner.clone();
258 pyo3_async_runtimes::tokio::future_into_py(py, async move {
259 client
260 .get_current(&exchange_id, &market_id)
261 .await
262 .map(PyFinFeedActivityCurrent::from)
263 .map_err(python_error)
264 })
265 }
266
267 /// Retrieves bounded activity with no continuation or continuity guarantee.
268 ///
269 /// # Errors
270 ///
271 /// Returns an error if:
272 /// - Request validation, transport, HTTP status, or decoding fails.
273 /// - The local allowance is exhausted, a deadline expires, or the request is canceled.
274 /// - A response exceeds the requested record limit.
275 #[gen_stub(
276 override_return_type(
277 type_repr = "typing.Awaitable[FinFeedActivityBatch]",
278 imports = ("typing",),
279 ),
280 )]
281 fn get_latest<'py>(
282 &self,
283 py: Python<'py>,
284 exchange_id: String,
285 market_id: String,
286 query: ActivityQuery,
287 ) -> PyResult<Bound<'py, PyAny>> {
288 let client = self.inner.clone();
289 pyo3_async_runtimes::tokio::future_into_py(py, async move {
290 client
291 .get_latest(&exchange_id, &market_id, &query)
292 .await
293 .map(PyFinFeedActivityBatch::from)
294 .map_err(python_error)
295 })
296 }
297
298 /// Retrieves one raw trade-history response without completeness or short-window guarantees.
299 ///
300 /// # Errors
301 ///
302 /// Returns an error if:
303 /// - Request validation, transport, HTTP status, or decoding fails.
304 /// - The local allowance is exhausted, a deadline expires, or the request is canceled.
305 /// - A response exceeds the requested record limit.
306 #[gen_stub(
307 override_return_type(
308 type_repr = "typing.Awaitable[list[FinFeedTrade]]",
309 imports = ("typing",),
310 ),
311 )]
312 fn get_trades_history<'py>(
313 &self,
314 py: Python<'py>,
315 exchange_id: String,
316 market_id: String,
317 query: HistoryQuery,
318 ) -> PyResult<Bound<'py, PyAny>> {
319 let client = self.inner.clone();
320 pyo3_async_runtimes::tokio::future_into_py(py, async move {
321 client
322 .get_trades_history(&exchange_id, &market_id, &query)
323 .await
324 .map(|records| {
325 records
326 .into_iter()
327 .map(PyFinFeedTrade::from)
328 .collect::<Vec<_>>()
329 })
330 .map_err(python_error)
331 })
332 }
333
334 /// Retrieves one raw quote-history response without completeness or short-window guarantees.
335 ///
336 /// # Errors
337 ///
338 /// Returns an error if:
339 /// - Request validation, transport, HTTP status, or decoding fails.
340 /// - The local allowance is exhausted, a deadline expires, or the request is canceled.
341 /// - A response exceeds the requested record limit.
342 #[gen_stub(
343 override_return_type(
344 type_repr = "typing.Awaitable[list[FinFeedQuote]]",
345 imports = ("typing",),
346 ),
347 )]
348 fn get_quotes_history<'py>(
349 &self,
350 py: Python<'py>,
351 exchange_id: String,
352 market_id: String,
353 query: HistoryQuery,
354 ) -> PyResult<Bound<'py, PyAny>> {
355 let client = self.inner.clone();
356 pyo3_async_runtimes::tokio::future_into_py(py, async move {
357 client
358 .get_quotes_history(&exchange_id, &market_id, &query)
359 .await
360 .map(|records| {
361 records
362 .into_iter()
363 .map(PyFinFeedQuote::from)
364 .collect::<Vec<_>>()
365 })
366 .map_err(python_error)
367 })
368 }
369
370 /// Retrieves a current book snapshot.
371 ///
372 /// # Errors
373 ///
374 /// Returns an error if:
375 /// - Request validation, transport, HTTP status, or decoding fails.
376 /// - The local allowance is exhausted, a deadline expires, or the request is canceled.
377 #[gen_stub(
378 override_return_type(
379 type_repr = "typing.Awaitable[FinFeedBook]",
380 imports = ("typing",),
381 ),
382 )]
383 fn get_book<'py>(
384 &self,
385 py: Python<'py>,
386 exchange_id: String,
387 market_id: String,
388 ) -> PyResult<Bound<'py, PyAny>> {
389 let client = self.inner.clone();
390 pyo3_async_runtimes::tokio::future_into_py(py, async move {
391 client
392 .get_book(&exchange_id, &market_id)
393 .await
394 .map(PyFinFeedBook::from)
395 .map_err(python_error)
396 })
397 }
398
399 /// Retrieves one bounded array of raw historical book events in response order.
400 ///
401 /// Date/time selectors use provider processing time, which may be absent from the events.
402 /// Numeric actions remain uninterpreted. A saturated response may be truncated; a short or
403 /// empty response does not establish coverage. No snapshot or continuation is inferred.
404 ///
405 /// # Errors
406 ///
407 /// Returns an error if:
408 /// - Request validation, transport, HTTP status, or decoding fails.
409 /// - The local allowance is exhausted, a deadline expires, or the request is canceled.
410 /// - A response exceeds the requested record limit.
411 #[gen_stub(
412 override_return_type(
413 type_repr = "typing.Awaitable[list[FinFeedBookEvent]]",
414 imports = ("typing",),
415 ),
416 )]
417 fn get_book_history<'py>(
418 &self,
419 py: Python<'py>,
420 exchange_id: String,
421 market_id: String,
422 query: HistoryQuery,
423 ) -> PyResult<Bound<'py, PyAny>> {
424 let client = self.inner.clone();
425 pyo3_async_runtimes::tokio::future_into_py(py, async move {
426 client
427 .get_book_history(&exchange_id, &market_id, &query)
428 .await
429 .map(|records| {
430 records
431 .into_iter()
432 .map(PyFinFeedBookEvent::from)
433 .collect::<Vec<_>>()
434 })
435 .map_err(python_error)
436 })
437 }
438
439 /// Retrieves supported OHLCV periods.
440 ///
441 /// # Errors
442 ///
443 /// Returns an error if:
444 /// - Request validation, transport, HTTP status, or decoding fails.
445 /// - The local allowance is exhausted, a deadline expires, or the request is canceled.
446 #[gen_stub(
447 override_return_type(
448 type_repr = "typing.Awaitable[list[FinFeedOhlcvPeriod]]",
449 imports = ("typing",),
450 ),
451 )]
452 fn get_periods<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
453 let client = self.inner.clone();
454 pyo3_async_runtimes::tokio::future_into_py(py, async move {
455 client
456 .get_periods()
457 .await
458 .map(|records| {
459 records
460 .into_iter()
461 .map(PyFinFeedOhlcvPeriod::from)
462 .collect::<Vec<_>>()
463 })
464 .map_err(python_error)
465 })
466 }
467
468 /// Retrieves one historical market OHLCV response without completeness or short-window
469 /// guarantees.
470 ///
471 /// # Errors
472 ///
473 /// Returns an error if:
474 /// - Request validation, transport, HTTP status, or decoding fails.
475 /// - The local allowance is exhausted, a deadline expires, or the request is canceled.
476 /// - A response exceeds the requested record limit.
477 #[gen_stub(
478 override_return_type(
479 type_repr = "typing.Awaitable[list[FinFeedOhlcv]]",
480 imports = ("typing",),
481 ),
482 )]
483 fn get_ohlcv_history<'py>(
484 &self,
485 py: Python<'py>,
486 exchange_id: String,
487 market_id: String,
488 query: OhlcvQuery,
489 ) -> PyResult<Bound<'py, PyAny>> {
490 let client = self.inner.clone();
491 pyo3_async_runtimes::tokio::future_into_py(py, async move {
492 client
493 .get_ohlcv_history(&exchange_id, &market_id, &query)
494 .await
495 .map(|records| {
496 records
497 .into_iter()
498 .map(PyFinFeedOhlcv::from)
499 .collect::<Vec<_>>()
500 })
501 .map_err(python_error)
502 })
503 }
504
505 /// Retrieves OHLCV from the provider's flat-file activity source.
506 ///
507 /// The provider describes this source as trade-generated. Returns one response without filtering,
508 /// pagination, or fallback to DB-backed OHLCV. A saturated response may be truncated; no
509 /// continuation or bound inclusion is inferred. Short or empty responses do not establish
510 /// source coverage or completeness.
511 ///
512 /// # Errors
513 ///
514 /// Returns an error if:
515 /// - Request validation, transport, HTTP status, or decoding fails.
516 /// - The local allowance is exhausted, a deadline expires, or the request is canceled.
517 /// - A response exceeds the requested record limit.
518 #[gen_stub(
519 override_return_type(
520 type_repr = "typing.Awaitable[list[FinFeedOhlcv]]",
521 imports = ("typing",),
522 ),
523 )]
524 fn get_ohlcv_flat_file_history<'py>(
525 &self,
526 py: Python<'py>,
527 exchange_id: String,
528 market_id: String,
529 query: FlatFileOhlcvQuery,
530 ) -> PyResult<Bound<'py, PyAny>> {
531 let client = self.inner.clone();
532 pyo3_async_runtimes::tokio::future_into_py(py, async move {
533 client
534 .get_ohlcv_flat_file_history(&exchange_id, &market_id, &query)
535 .await
536 .map(|records| {
537 records
538 .into_iter()
539 .map(PyFinFeedOhlcv::from)
540 .collect::<Vec<_>>()
541 })
542 .map_err(python_error)
543 })
544 }
545
546 /// Retrieves one exchange-wide OHLCV response with market identifiers retained.
547 ///
548 /// Both time bounds are required, at most 24 hours apart, with a limit in `[1, 10000]`.
549 /// Returns every response row in provider order, without time filtering or native mapping.
550 /// Callers partition longer windows explicitly; saturation may truncate markets at the
551 /// same timestamp, so advancing by the last timestamp cannot establish completeness.
552 ///
553 /// # Errors
554 ///
555 /// Returns an error if:
556 /// - Request validation, transport, HTTP status, or decoding fails.
557 /// - The local allowance is exhausted, a deadline expires, or the request is canceled.
558 /// - A response exceeds the requested row limit.
559 #[gen_stub(
560 override_return_type(
561 type_repr = "typing.Awaitable[list[FinFeedOhlcv]]",
562 imports = ("typing",),
563 ),
564 )]
565 fn get_ohlcv_exchange_history<'py>(
566 &self,
567 py: Python<'py>,
568 exchange_id: String,
569 query: OhlcvQuery,
570 ) -> PyResult<Bound<'py, PyAny>> {
571 let client = self.inner.clone();
572 pyo3_async_runtimes::tokio::future_into_py(py, async move {
573 client
574 .get_ohlcv_exchange_history(&exchange_id, &query)
575 .await
576 .map(|records| {
577 records
578 .into_iter()
579 .map(PyFinFeedOhlcv::from)
580 .collect::<Vec<_>>()
581 })
582 .map_err(python_error)
583 })
584 }
585
586 /// Retrieves the newest market OHLCV bars without time bounds.
587 ///
588 /// # Errors
589 ///
590 /// Returns an error if:
591 /// - Request validation, transport, HTTP status, or decoding fails.
592 /// - The local allowance is exhausted, a deadline expires, or the request is canceled.
593 /// - A response exceeds the requested record limit.
594 #[gen_stub(
595 override_return_type(
596 type_repr = "typing.Awaitable[list[FinFeedOhlcv]]",
597 imports = ("typing",),
598 ),
599 )]
600 fn get_ohlcv_latest<'py>(
601 &self,
602 py: Python<'py>,
603 exchange_id: String,
604 market_id: String,
605 query: OhlcvQuery,
606 ) -> PyResult<Bound<'py, PyAny>> {
607 let client = self.inner.clone();
608 pyo3_async_runtimes::tokio::future_into_py(py, async move {
609 client
610 .get_ohlcv_latest(&exchange_id, &market_id, &query)
611 .await
612 .map(|records| {
613 records
614 .into_iter()
615 .map(PyFinFeedOhlcv::from)
616 .collect::<Vec<_>>()
617 })
618 .map_err(python_error)
619 })
620 }
621
622 /// Collects listings until a null or omitted cursor, rejecting cycles and exceeded traversal
623 /// bounds.
624 ///
625 /// # Errors
626 ///
627 /// Returns an error if a page fails, a cursor is empty or repeats, or a pagination bound
628 /// is exceeded.
629 #[gen_stub(
630 override_return_type(
631 type_repr = "typing.Awaitable[list[FinFeedMarket]]",
632 imports = ("typing",),
633 ),
634 )]
635 fn get_listings_all<'py>(
636 &self,
637 py: Python<'py>,
638 exchange_id: String,
639 query: ListingsQuery,
640 bounds: Pagination,
641 ) -> PyResult<Bound<'py, PyAny>> {
642 let client = self.inner.clone();
643 pyo3_async_runtimes::tokio::future_into_py(py, async move {
644 client
645 .get_listings_all(&exchange_id, &query, bounds)
646 .await
647 .map(|records| {
648 records
649 .into_iter()
650 .map(PyFinFeedMarket::from)
651 .collect::<Vec<_>>()
652 })
653 .map_err(python_error)
654 })
655 }
656
657 /// Collects active IDs until an empty page, rejecting duplicate IDs and exceeded bounds.
658 ///
659 /// A short page alone does not establish exhaustion. Results are observations of a changing
660 /// catalog, not a consistent snapshot.
661 ///
662 /// # Errors
663 ///
664 /// Returns an error if a page fails, an ID is empty or repeats, or a pagination bound
665 /// is exceeded.
666 #[gen_stub(
667 override_return_type(
668 type_repr = "typing.Awaitable[list[str]]",
669 imports = ("typing",),
670 ),
671 )]
672 fn get_active_all<'py>(
673 &self,
674 py: Python<'py>,
675 exchange_id: String,
676 query: ActiveQuery,
677 bounds: Pagination,
678 ) -> PyResult<Bound<'py, PyAny>> {
679 let client = self.inner.clone();
680 pyo3_async_runtimes::tokio::future_into_py(py, async move {
681 client
682 .get_active_all(&exchange_id, &query, bounds)
683 .await
684 .map(|ids| ids.iter().map(ToString::to_string).collect::<Vec<_>>())
685 .map_err(python_error)
686 })
687 }
688}
689
690fn python_error(e: Error) -> PyErr {
691 match e {
692 Error::Validation(_) | Error::Definition { .. } | Error::Unavailable(_) => {
693 to_pyvalue_err(e)
694 }
695 _ => to_pyruntime_err(e),
696 }
697}
698
699pub(super) fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
700 m.add_class::<PyFinFeedHttpClient>()?;
701 Ok(())
702}