1use jiff::Timestamp;
19use nautilus_core::{
20 nanos::UnixNanos,
21 python::{to_pyruntime_err, to_pyvalue_err},
22};
23use nautilus_model::{
24 data::BarType,
25 enums::{AccountType, OrderSide, OrderType, TimeInForce, TriggerType},
26 identifiers::{AccountId, ClientOrderId, InstrumentId, VenueOrderId},
27 python::instruments::{instrument_any_to_pyobject, pyobject_to_instrument_any},
28 types::{Price, Quantity},
29};
30use pyo3::{
31 conversion::IntoPyObjectExt,
32 prelude::*,
33 types::{PyDict, PyList},
34};
35use rust_decimal::Decimal;
36use ustr::Ustr;
37
38use crate::{
39 common::{credential::KrakenCredential, enums::KrakenEnvironment},
40 http::KrakenSpotHttpClient,
41};
42
43#[pymethods]
44#[pyo3_stub_gen::derive::gen_stub_pymethods]
45impl KrakenSpotHttpClient {
46 #[new]
52 #[pyo3(signature = (api_key=None, api_secret=None, base_url=None, timeout_secs=60, max_retries=None, retry_delay_ms=None, retry_delay_max_ms=None, proxy_url=None, max_requests_per_second=5))]
53 #[expect(clippy::too_many_arguments)]
54 fn py_new(
55 api_key: Option<String>,
56 api_secret: Option<String>,
57 base_url: Option<String>,
58 timeout_secs: u64,
59 max_retries: Option<u32>,
60 retry_delay_ms: Option<u64>,
61 retry_delay_max_ms: Option<u64>,
62 proxy_url: Option<String>,
63 max_requests_per_second: u32,
64 ) -> PyResult<Self> {
65 let environment = KrakenEnvironment::Live;
66
67 if let Some(cred) = KrakenCredential::resolve_spot(api_key, api_secret) {
68 let (k, s) = cred.into_parts();
69 Self::with_credentials(
70 k,
71 s,
72 environment,
73 base_url,
74 timeout_secs,
75 max_retries,
76 retry_delay_ms,
77 retry_delay_max_ms,
78 proxy_url,
79 max_requests_per_second,
80 )
81 .map_err(to_pyvalue_err)
82 } else {
83 Self::new(
84 environment,
85 base_url,
86 timeout_secs,
87 max_retries,
88 retry_delay_ms,
89 retry_delay_max_ms,
90 proxy_url,
91 max_requests_per_second,
92 )
93 .map_err(to_pyvalue_err)
94 }
95 }
96
97 #[getter]
98 #[pyo3(name = "base_url")]
99 #[must_use]
100 pub fn py_base_url(&self) -> String {
101 self.inner.base_url().to_string()
102 }
103
104 #[getter]
105 #[pyo3(name = "api_key")]
106 #[must_use]
107 pub fn py_api_key(&self) -> Option<&str> {
108 self.inner.credential().map(|c| c.api_key())
109 }
110
111 #[getter]
112 #[pyo3(name = "api_key_masked")]
113 #[must_use]
114 pub fn py_api_key_masked(&self) -> Option<String> {
115 self.inner.credential().map(|c| c.api_key_masked())
116 }
117
118 #[pyo3(name = "cache_instrument")]
120 fn py_cache_instrument(&self, py: Python, instrument: Py<PyAny>) -> PyResult<()> {
121 let inst_any = pyobject_to_instrument_any(py, instrument)?;
122 self.cache_instrument(inst_any);
123 Ok(())
124 }
125
126 #[pyo3(name = "cancel_all_requests")]
128 fn py_cancel_all_requests(&self) {
129 self.cancel_all_requests();
130 }
131
132 #[pyo3(name = "get_server_time")]
133 fn py_get_server_time<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
134 let client = self.clone();
135
136 pyo3_async_runtimes::tokio::future_into_py(py, async move {
137 let server_time = client
138 .inner
139 .get_server_time()
140 .await
141 .map_err(to_pyruntime_err)?;
142
143 let json_string = serde_json::to_string(&server_time)
144 .map_err(|e| to_pyruntime_err(format!("Failed to serialize response: {e}")))?;
145
146 Ok(json_string)
147 })
148 }
149
150 #[pyo3(name = "request_instruments")]
155 #[pyo3(signature = (pairs=None))]
156 fn py_request_instruments<'py>(
157 &self,
158 py: Python<'py>,
159 pairs: Option<Vec<String>>,
160 ) -> PyResult<Bound<'py, PyAny>> {
161 let client = self.clone();
162
163 pyo3_async_runtimes::tokio::future_into_py(py, async move {
164 let instruments = client
165 .request_instruments(pairs)
166 .await
167 .map_err(to_pyruntime_err)?;
168
169 Python::attach(|py| {
170 let py_instruments: PyResult<Vec<_>> = instruments
171 .into_iter()
172 .map(|inst| instrument_any_to_pyobject(py, inst))
173 .collect();
174 let pylist = PyList::new(py, py_instruments?)?;
175 Ok(pylist.unbind())
176 })
177 })
178 }
179
180 #[pyo3(name = "request_instrument_statuses")]
186 #[pyo3(signature = (pairs=None))]
187 fn py_request_instrument_statuses<'py>(
188 &self,
189 py: Python<'py>,
190 pairs: Option<Vec<String>>,
191 ) -> PyResult<Bound<'py, PyAny>> {
192 let client = self.clone();
193
194 pyo3_async_runtimes::tokio::future_into_py(py, async move {
195 let statuses = client
196 .request_instrument_statuses(pairs)
197 .await
198 .map_err(to_pyruntime_err)?;
199
200 Python::attach(|py| {
201 let dict = PyDict::new(py);
202 for (instrument_id, action) in statuses {
203 dict.set_item(
204 instrument_id.into_bound_py_any(py)?,
205 action.into_bound_py_any(py)?,
206 )?;
207 }
208 Ok(dict.into_any().unbind())
209 })
210 })
211 }
212
213 #[pyo3(name = "request_trades")]
215 #[pyo3(signature = (instrument_id, start=None, end=None, limit=None))]
216 fn py_request_trades<'py>(
217 &self,
218 py: Python<'py>,
219 instrument_id: InstrumentId,
220 start: Option<Timestamp>,
221 end: Option<Timestamp>,
222 limit: Option<u64>,
223 ) -> PyResult<Bound<'py, PyAny>> {
224 let client = self.clone();
225
226 pyo3_async_runtimes::tokio::future_into_py(py, async move {
227 let trades = client
228 .request_trades(instrument_id, start, end, limit)
229 .await
230 .map_err(to_pyruntime_err)?;
231
232 Python::attach(|py| {
233 let py_trades: PyResult<Vec<_>> = trades
234 .into_iter()
235 .map(|trade| trade.into_py_any(py))
236 .collect();
237 let pylist = PyList::new(py, py_trades?)?.into_any().unbind();
238 Ok(pylist)
239 })
240 })
241 }
242
243 #[pyo3(name = "request_book_snapshot")]
245 #[pyo3(signature = (instrument_id, depth=None))]
246 fn py_request_book_snapshot<'py>(
247 &self,
248 py: Python<'py>,
249 instrument_id: InstrumentId,
250 depth: Option<u32>,
251 ) -> PyResult<Bound<'py, PyAny>> {
252 let client = self.clone();
253
254 pyo3_async_runtimes::tokio::future_into_py(py, async move {
255 let book = client
256 .request_book_snapshot(instrument_id, depth)
257 .await
258 .map_err(to_pyruntime_err)?;
259
260 Python::attach(|py| book.into_py_any(py))
261 })
262 }
263
264 #[pyo3(name = "request_bars")]
266 #[pyo3(signature = (bar_type, start=None, end=None, limit=None))]
267 fn py_request_bars<'py>(
268 &self,
269 py: Python<'py>,
270 bar_type: BarType,
271 start: Option<Timestamp>,
272 end: Option<Timestamp>,
273 limit: Option<u64>,
274 ) -> PyResult<Bound<'py, PyAny>> {
275 let client = self.clone();
276
277 pyo3_async_runtimes::tokio::future_into_py(py, async move {
278 let bars = client
279 .request_bars(bar_type, start, end, limit)
280 .await
281 .map_err(to_pyruntime_err)?;
282
283 Python::attach(|py| {
284 let py_bars: PyResult<Vec<_>> =
285 bars.into_iter().map(|bar| bar.into_py_any(py)).collect();
286 let pylist = PyList::new(py, py_bars?)?.into_any().unbind();
287 Ok(pylist)
288 })
289 })
290 }
291
292 #[pyo3(name = "request_account_state")]
303 #[pyo3(signature = (account_id, account_type = AccountType::Cash, margin_balance_asset = None))]
304 fn py_request_account_state<'py>(
305 &self,
306 py: Python<'py>,
307 account_id: AccountId,
308 account_type: AccountType,
309 margin_balance_asset: Option<String>,
310 ) -> PyResult<Bound<'py, PyAny>> {
311 let client = self.clone();
312
313 pyo3_async_runtimes::tokio::future_into_py(py, async move {
314 let account_state = client
315 .request_account_state(account_id, account_type, margin_balance_asset.as_deref())
316 .await
317 .map_err(to_pyruntime_err)?;
318
319 Python::attach(|py| account_state.into_pyobject(py).map(|o| o.unbind()))
320 })
321 }
322
323 #[pyo3(name = "request_margin_metrics")]
336 #[pyo3(signature = (asset = None))]
337 fn py_request_margin_metrics<'py>(
338 &self,
339 py: Python<'py>,
340 asset: Option<String>,
341 ) -> PyResult<Bound<'py, PyAny>> {
342 let client = self.clone();
343
344 pyo3_async_runtimes::tokio::future_into_py(py, async move {
345 let metrics = client
346 .request_margin_metrics(asset.as_deref())
347 .await
348 .map_err(to_pyruntime_err)?;
349
350 Python::attach(|py| {
351 let dict = pyo3::types::PyDict::new(py);
352 for (k, v) in metrics {
353 dict.set_item(k, v)?;
354 }
355 Ok::<_, PyErr>(dict.unbind().into_any())
356 })
357 })
358 }
359
360 #[pyo3(name = "request_account_state_with_metrics")]
382 #[pyo3(signature = (account_id, account_type = AccountType::Cash, margin_balance_asset = None))]
383 fn py_request_account_state_with_metrics<'py>(
384 &self,
385 py: Python<'py>,
386 account_id: AccountId,
387 account_type: AccountType,
388 margin_balance_asset: Option<String>,
389 ) -> PyResult<Bound<'py, PyAny>> {
390 let client = self.clone();
391
392 pyo3_async_runtimes::tokio::future_into_py(py, async move {
393 let (account_state, metrics) = client
394 .request_account_state_with_metrics(
395 account_id,
396 account_type,
397 margin_balance_asset.as_deref(),
398 )
399 .await
400 .map_err(to_pyruntime_err)?;
401
402 Python::attach(|py| {
403 let state_obj = account_state.into_pyobject(py)?.unbind();
404 let dict = pyo3::types::PyDict::new(py);
405 for (k, v) in metrics {
406 dict.set_item(k, v)?;
407 }
408 let tuple = pyo3::types::PyTuple::new(
409 py,
410 [state_obj.into_any(), dict.unbind().into_any()],
411 )?;
412 Ok::<_, PyErr>(tuple.unbind().into_any())
413 })
414 })
415 }
416
417 #[pyo3(name = "request_order_status_reports")]
419 #[pyo3(signature = (account_id, instrument_id=None, start=None, end=None, open_only=false))]
420 fn py_request_order_status_reports<'py>(
421 &self,
422 py: Python<'py>,
423 account_id: AccountId,
424 instrument_id: Option<InstrumentId>,
425 start: Option<Timestamp>,
426 end: Option<Timestamp>,
427 open_only: bool,
428 ) -> PyResult<Bound<'py, PyAny>> {
429 let client = self.clone();
430
431 pyo3_async_runtimes::tokio::future_into_py(py, async move {
432 let reports = client
433 .request_order_status_reports(account_id, instrument_id, start, end, open_only)
434 .await
435 .map_err(to_pyruntime_err)?;
436
437 Python::attach(|py| {
438 let py_reports: PyResult<Vec<_>> = reports
439 .into_iter()
440 .map(|report| report.into_py_any(py))
441 .collect();
442 let pylist = PyList::new(py, py_reports?)?.into_any().unbind();
443 Ok(pylist)
444 })
445 })
446 }
447
448 #[pyo3(name = "request_fill_reports")]
450 #[pyo3(signature = (account_id, instrument_id=None, start=None, end=None))]
451 fn py_request_fill_reports<'py>(
452 &self,
453 py: Python<'py>,
454 account_id: AccountId,
455 instrument_id: Option<InstrumentId>,
456 start: Option<Timestamp>,
457 end: Option<Timestamp>,
458 ) -> PyResult<Bound<'py, PyAny>> {
459 let client = self.clone();
460
461 pyo3_async_runtimes::tokio::future_into_py(py, async move {
462 let reports = client
463 .request_fill_reports(account_id, instrument_id, start, end)
464 .await
465 .map_err(to_pyruntime_err)?;
466
467 Python::attach(|py| {
468 let py_reports: PyResult<Vec<_>> = reports
469 .into_iter()
470 .map(|report| report.into_py_any(py))
471 .collect();
472 let pylist = PyList::new(py, py_reports?)?.into_any().unbind();
473 Ok(pylist)
474 })
475 })
476 }
477
478 #[pyo3(name = "request_position_status_reports")]
484 #[pyo3(signature = (account_id, instrument_id=None, account_type=AccountType::Cash, use_spot_position_reports=false, quote_currency="USDT"))]
485 fn py_request_position_status_reports<'py>(
486 &self,
487 py: Python<'py>,
488 account_id: AccountId,
489 instrument_id: Option<InstrumentId>,
490 account_type: AccountType,
491 use_spot_position_reports: bool,
492 quote_currency: &str,
493 ) -> PyResult<Bound<'py, PyAny>> {
494 let client = self.clone();
495 let quote_currency = Ustr::from(quote_currency);
496
497 pyo3_async_runtimes::tokio::future_into_py(py, async move {
498 let reports = client
499 .request_position_status_reports(
500 account_id,
501 instrument_id,
502 account_type,
503 use_spot_position_reports,
504 quote_currency,
505 )
506 .await
507 .map_err(to_pyruntime_err)?;
508
509 Python::attach(|py| {
510 let py_reports: PyResult<Vec<_>> = reports
511 .into_iter()
512 .map(|report| report.into_py_any(py))
513 .collect();
514 let pylist = PyList::new(py, py_reports?)?.into_any().unbind();
515 Ok(pylist)
516 })
517 })
518 }
519
520 #[pyo3(name = "submit_order")]
534 #[pyo3(signature = (account_id, instrument_id, client_order_id, order_side, order_type, quantity, time_in_force, expire_time=None, price=None, trigger_price=None, trigger_type=None, trailing_offset=None, limit_offset=None, reduce_only=false, post_only=false, quote_quantity=false, display_qty=None, leverage=None, account_type=AccountType::Cash))]
535 #[expect(clippy::too_many_arguments)]
536 fn py_submit_order<'py>(
537 &self,
538 py: Python<'py>,
539 account_id: AccountId,
540 instrument_id: InstrumentId,
541 client_order_id: ClientOrderId,
542 order_side: OrderSide,
543 order_type: OrderType,
544 quantity: Quantity,
545 time_in_force: TimeInForce,
546 expire_time: Option<u64>,
547 price: Option<Price>,
548 trigger_price: Option<Price>,
549 trigger_type: Option<TriggerType>,
550 trailing_offset: Option<String>,
551 limit_offset: Option<String>,
552 reduce_only: bool,
553 post_only: bool,
554 quote_quantity: bool,
555 display_qty: Option<Quantity>,
556 leverage: Option<u16>,
557 account_type: AccountType,
558 ) -> PyResult<Bound<'py, PyAny>> {
559 let client = self.clone();
560 let expire_time = expire_time.map(UnixNanos::from);
561 let trailing_offset = trailing_offset
562 .map(|s| {
563 Decimal::from_str_exact(&s)
564 .map_err(|e| to_pyvalue_err(format!("invalid trailing_offset: {e}")))
565 })
566 .transpose()?;
567 let limit_offset = limit_offset
568 .map(|s| {
569 Decimal::from_str_exact(&s)
570 .map_err(|e| to_pyvalue_err(format!("invalid limit_offset: {e}")))
571 })
572 .transpose()?;
573
574 pyo3_async_runtimes::tokio::future_into_py(py, async move {
575 let venue_order_id = client
576 .submit_order(
577 account_id,
578 instrument_id,
579 client_order_id,
580 order_side,
581 order_type,
582 quantity,
583 time_in_force,
584 expire_time,
585 price,
586 trigger_price,
587 trigger_type,
588 trailing_offset,
589 limit_offset,
590 reduce_only,
591 post_only,
592 quote_quantity,
593 display_qty,
594 leverage,
595 account_type,
596 )
597 .await
598 .map_err(to_pyruntime_err)?;
599
600 Python::attach(|py| venue_order_id.into_pyobject(py).map(|o| o.unbind()))
601 })
602 }
603
604 #[pyo3(name = "cancel_order")]
614 #[pyo3(signature = (account_id, instrument_id, client_order_id=None, venue_order_id=None))]
615 fn py_cancel_order<'py>(
616 &self,
617 py: Python<'py>,
618 account_id: AccountId,
619 instrument_id: InstrumentId,
620 client_order_id: Option<ClientOrderId>,
621 venue_order_id: Option<VenueOrderId>,
622 ) -> PyResult<Bound<'py, PyAny>> {
623 let client = self.clone();
624
625 pyo3_async_runtimes::tokio::future_into_py(py, async move {
626 client
627 .cancel_order(account_id, instrument_id, client_order_id, venue_order_id)
628 .await
629 .map_err(to_pyruntime_err)
630 })
631 }
632
633 #[pyo3(name = "cancel_all_orders")]
634 fn py_cancel_all_orders<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
635 let client = self.clone();
636
637 pyo3_async_runtimes::tokio::future_into_py(py, async move {
638 let response = client
639 .inner
640 .cancel_all_orders()
641 .await
642 .map_err(to_pyruntime_err)?;
643
644 Ok(response.count)
645 })
646 }
647
648 #[pyo3(name = "cancel_orders_batch")]
650 fn py_cancel_orders_batch<'py>(
651 &self,
652 py: Python<'py>,
653 venue_order_ids: Vec<VenueOrderId>,
654 ) -> PyResult<Bound<'py, PyAny>> {
655 let client = self.clone();
656
657 pyo3_async_runtimes::tokio::future_into_py(py, async move {
658 client
659 .cancel_orders_batch(venue_order_ids)
660 .await
661 .map_err(to_pyruntime_err)
662 })
663 }
664
665 #[pyo3(name = "modify_order")]
680 #[pyo3(signature = (instrument_id, client_order_id=None, venue_order_id=None, quantity=None, price=None, trigger_price=None))]
681 #[expect(clippy::too_many_arguments)]
682 fn py_modify_order<'py>(
683 &self,
684 py: Python<'py>,
685 instrument_id: InstrumentId,
686 client_order_id: Option<ClientOrderId>,
687 venue_order_id: Option<VenueOrderId>,
688 quantity: Option<Quantity>,
689 price: Option<Price>,
690 trigger_price: Option<Price>,
691 ) -> PyResult<Bound<'py, PyAny>> {
692 let client = self.clone();
693
694 pyo3_async_runtimes::tokio::future_into_py(py, async move {
695 let new_venue_order_id = client
696 .modify_order(
697 instrument_id,
698 client_order_id,
699 venue_order_id,
700 quantity,
701 price,
702 trigger_price,
703 )
704 .await
705 .map_err(to_pyruntime_err)?;
706
707 Python::attach(|py| new_venue_order_id.into_pyobject(py).map(|o| o.unbind()))
708 })
709 }
710}
711
712#[pymethods]
716impl KrakenSpotHttpClient {
717 #[pyo3(name = "submit_orders_batch", signature = (orders, leverage=None, account_type=AccountType::Cash, per_order_leverages=None, per_order_reduce_only=None))]
722 #[expect(clippy::type_complexity)]
723 fn py_submit_orders_batch<'py>(
724 &self,
725 py: Python<'py>,
726 orders: Vec<(
727 InstrumentId,
728 ClientOrderId,
729 OrderSide,
730 OrderType,
731 Quantity,
732 TimeInForce,
733 Option<Price>,
734 Option<Price>,
735 Option<TriggerType>,
736 bool,
737 bool,
738 Option<Quantity>,
739 )>,
740 leverage: Option<u16>,
741 account_type: AccountType,
742 per_order_leverages: Option<Vec<Option<u16>>>,
743 per_order_reduce_only: Option<Vec<bool>>,
744 ) -> PyResult<Bound<'py, PyAny>> {
745 let client = self.clone();
746 let n = orders.len();
747
748 if let Some(ref v) = per_order_leverages
749 && v.len() != n
750 {
751 return Err(to_pyvalue_err(format!(
752 "per_order_leverages length must equal orders length, was {} for {n} orders",
753 v.len(),
754 )));
755 }
756
757 if let Some(ref v) = per_order_reduce_only
758 && v.len() != n
759 {
760 return Err(to_pyvalue_err(format!(
761 "per_order_reduce_only length must equal orders length, was {} for {n} orders",
762 v.len(),
763 )));
764 }
765
766 let leverages: Vec<Option<u16>> = match per_order_leverages {
767 Some(per_leverages) => per_leverages.into_iter().map(|v| v.or(leverage)).collect(),
768 None => vec![leverage; n],
769 };
770 let reduce_only_flags = per_order_reduce_only.unwrap_or_else(|| vec![false; n]);
771 let expanded_orders = orders
772 .into_iter()
773 .zip(leverages)
774 .zip(reduce_only_flags)
775 .map(
776 |(
777 (
778 (
779 instrument_id,
780 client_order_id,
781 order_side,
782 order_type,
783 quantity,
784 time_in_force,
785 price,
786 trigger_price,
787 trigger_type,
788 post_only,
789 quote_quantity,
790 display_qty,
791 ),
792 order_leverage,
793 ),
794 order_reduce_only,
795 )| {
796 (
797 instrument_id,
798 client_order_id,
799 order_side,
800 order_type,
801 quantity,
802 time_in_force,
803 None,
804 price,
805 trigger_price,
806 trigger_type,
807 None,
808 None,
809 order_reduce_only,
810 post_only,
811 quote_quantity,
812 display_qty,
813 order_leverage,
814 )
815 },
816 )
817 .collect();
818
819 pyo3_async_runtimes::tokio::future_into_py(py, async move {
820 client
821 .submit_orders_batch(expanded_orders, account_type)
822 .await
823 .map_err(to_pyruntime_err)
824 })
825 }
826}