1use std::{
19 collections::{HashMap, HashSet},
20 fmt::Debug,
21 sync::{
22 Arc, LazyLock, Mutex,
23 atomic::{AtomicBool, Ordering},
24 },
25};
26
27use nautilus_common::config::ConfigError;
28use nautilus_core::{string::secret::SecretString, time::get_atomic_clock_realtime};
29use nautilus_network::{
30 http::{HttpClient, HttpClientError, HttpRedirectPolicy, HttpResponse, Method},
31 retry::{RetryConfig, RetryError, RetryManager},
32};
33use serde::{Serialize, de::DeserializeOwned};
34use tokio_util::sync::CancellationToken;
35use url::Url;
36
37use super::{
38 error::KalshiHttpError,
39 models::*,
40 parse::{Pages, Pagination, decode_body, decode_response, unexpected_response},
41 query::*,
42 quota::{Bucket, Charge, KalshiQuota},
43};
44use crate::{
45 common::credential::{KalshiCredential, credential_env_vars},
46 config::KalshiDataClientConfig,
47};
48
49static QUOTAS: LazyLock<Mutex<QuotaOwners>> = LazyLock::new(|| Mutex::new(HashMap::new()));
50
51#[derive(Clone)]
60pub struct KalshiHttpClient {
61 client: HttpClient,
62 base_url: SecretString,
63 credential: Option<Arc<KalshiCredential>>,
64 cancellation: CancellationToken,
65 dispatch_check: Option<Arc<dyn Fn() -> bool + Send + Sync>>,
66 quota: Arc<KalshiQuota>,
67 timeout_ms: u64,
68}
69
70impl KalshiHttpClient {
71 pub fn new(config: &KalshiDataClientConfig) -> anyhow::Result<Self> {
79 Self::build(config)
80 }
81
82 pub fn new_authenticated(config: &KalshiDataClientConfig) -> anyhow::Result<Self> {
88 Self::authenticated(config, None)
89 }
90
91 pub fn new_authenticated_with_quota(
100 config: &KalshiDataClientConfig,
101 quota: Arc<KalshiQuota>,
102 ) -> anyhow::Result<Self> {
103 Self::authenticated(config, Some(quota))
104 }
105
106 pub fn new_with_quota(
112 config: &KalshiDataClientConfig,
113 quota: Arc<KalshiQuota>,
114 ) -> anyhow::Result<Self> {
115 let mut client = Self::build(config)?;
116 client.quota = quota;
117 Ok(client)
118 }
119
120 pub async fn refresh_quota(&self) -> Result<(), KalshiHttpError> {
132 let _guard = tokio::select! {
133 biased;
134 () = self.cancellation.cancelled() => return Err(KalshiHttpError::Canceled { dispatched: false }),
135 guard = self.quota.refresh.lock() => guard,
136 };
137
138 if !self.quota.needs_refresh() {
139 return Ok(());
140 }
141
142 let limits = self.get_account_limits().await;
143 let costs = self.get_endpoint_costs().await;
144 if let Err(e) = limits.and(costs.map(|_| ())) {
145 if !self.cancellation.is_cancelled() {
146 self.quota.discovery_failed();
147 }
148
149 return Err(e);
150 }
151
152 Ok(())
153 }
154
155 pub(crate) async fn batch_size(&self, method: Method) -> Result<usize, KalshiHttpError> {
156 self.refresh_quota().await?;
157 let charge = request_charge(
158 &method,
159 &["portfolio", "events", "orders", "batched"],
160 "",
161 None,
162 Operation::Write,
163 )?;
164 self.quota.batch_size(&charge)
165 }
166
167 pub(crate) fn with_dispatch_check(
168 mut self,
169 cancellation: CancellationToken,
170 check: impl Fn() -> bool + Send + Sync + 'static,
171 ) -> Self {
172 self.cancellation = cancellation;
173 self.dispatch_check = Some(Arc::new(check));
174 self
175 }
176
177 pub async fn get_exchange_status(&self) -> Result<HttpResponse, HttpClientError> {
185 self.send_raw(
186 Method::GET,
187 &["exchange", "status"],
188 &(),
189 Option::<&()>::None,
190 false,
191 Operation::Read,
192 )
193 .await
194 .map_err(|e| match e {
195 KalshiHttpError::Transport(e) => e,
196 e => HttpClientError::Error(e.to_string()),
197 })
198 }
199
200 pub async fn get_balance(&self, exchange_index: u32) -> Result<HttpResponse, KalshiHttpError> {
206 let response = self
207 .send_raw(
208 Method::GET,
209 &["portfolio", "balance"],
210 &[("exchange_index", exchange_index)],
211 Option::<&()>::None,
212 true,
213 Operation::Read,
214 )
215 .await?;
216
217 if !response.status.is_success() {
218 return Err(KalshiHttpError::Status(response.status.as_u16()));
219 }
220
221 Ok(response)
222 }
223
224 pub fn cancel(&self) {
228 self.cancellation.cancel();
229 }
230
231 pub async fn get_status(&self) -> Result<ExchangeStatus, KalshiHttpError> {
240 let response = self
241 .send_raw(
242 Method::GET,
243 &["exchange", "status"],
244 &(),
245 Option::<&()>::None,
246 false,
247 Operation::Read,
248 )
249 .await?;
250
251 if matches!(response.status.as_u16(), 500 | 503 | 504) {
252 return decode_body(response.clone()).or_else(|_| decode_response(response));
253 }
254
255 decode_response(response)
256 }
257
258 pub async fn get_markets(
264 &self,
265 query: &MarketsQuery,
266 ) -> Result<MarketsResponse, KalshiHttpError> {
267 self.get(&["markets"], query, false).await
268 }
269
270 pub async fn get_market(&self, ticker: &str) -> Result<MarketResponse, KalshiHttpError> {
276 self.get(&["markets", ticker], &(), false).await
277 }
278
279 pub async fn get_historical_markets(
285 &self,
286 query: &HistoricalMarketsQuery,
287 ) -> Result<MarketsResponse, KalshiHttpError> {
288 self.get(&["historical", "markets"], query, false).await
289 }
290
291 pub async fn get_historical_market(
297 &self,
298 ticker: &str,
299 ) -> Result<MarketResponse, KalshiHttpError> {
300 self.get(&["historical", "markets", ticker], &(), false)
301 .await
302 }
303
304 pub async fn get_events(&self, query: &EventsQuery) -> Result<EventsResponse, KalshiHttpError> {
310 self.get(&["events"], query, false).await
311 }
312
313 pub async fn get_event(
319 &self,
320 ticker: &str,
321 query: &EventQuery,
322 ) -> Result<EventResponse, KalshiHttpError> {
323 self.get(&["events", ticker], query, false).await
324 }
325
326 pub async fn get_series_list(
332 &self,
333 query: &SeriesQuery,
334 ) -> Result<SeriesListResponse, KalshiHttpError> {
335 self.get(&["series"], query, false).await
336 }
337
338 pub async fn get_series(&self, ticker: &str) -> Result<SeriesResponse, KalshiHttpError> {
344 self.get(&["series", ticker], &(), false).await
345 }
346
347 pub async fn get_orderbook(
353 &self,
354 ticker: &str,
355 depth: u32,
356 ) -> Result<OrderbookResponse, KalshiHttpError> {
357 if depth > 100 {
358 return Err(KalshiHttpError::Validation("depth exceeds 100"));
359 }
360
361 self.get(
362 &["markets", ticker, "orderbook"],
363 &[("depth", depth)],
364 false,
365 )
366 .await
367 }
368
369 pub async fn get_trades(&self, query: &TradesQuery) -> Result<TradesResponse, KalshiHttpError> {
375 self.get(&["markets", "trades"], query, false).await
376 }
377
378 pub async fn get_historical_trades(
384 &self,
385 query: &TradesQuery,
386 ) -> Result<TradesResponse, KalshiHttpError> {
387 self.get(&["historical", "trades"], query, false).await
388 }
389
390 pub async fn get_candlesticks(
396 &self,
397 series: &str,
398 ticker: &str,
399 query: &CandlesticksQuery,
400 ) -> Result<CandlesticksResponse, KalshiHttpError> {
401 validate_candlesticks(query)?;
402 self.get(
403 &["series", series, "markets", ticker, "candlesticks"],
404 query,
405 false,
406 )
407 .await
408 }
409
410 pub async fn get_historical_candlesticks(
416 &self,
417 ticker: &str,
418 query: &CandlesticksQuery,
419 ) -> Result<HistoricalCandlesticksResponse, KalshiHttpError> {
420 validate_candlesticks(query)?;
421 self.get(
422 &["historical", "markets", ticker, "candlesticks"],
423 query,
424 false,
425 )
426 .await
427 }
428
429 pub async fn get_historical_cutoff(&self) -> Result<HistoricalCutoff, KalshiHttpError> {
435 self.get(&["historical", "cutoff"], &(), false).await
436 }
437
438 pub async fn get_account_balance(
444 &self,
445 query: &AccountQuery,
446 ) -> Result<Balance, KalshiHttpError> {
447 validate_primary(query.subaccount)?;
448 self.get(&["portfolio", "balance"], query, true).await
449 }
450
451 pub async fn get_positions(
457 &self,
458 query: &PositionsQuery,
459 ) -> Result<PositionsResponse, KalshiHttpError> {
460 validate_primary(query.subaccount)?;
461 self.get(&["portfolio", "positions"], query, true).await
462 }
463
464 pub async fn get_historical_positions(
470 &self,
471 query: &HistoricalPositionsQuery,
472 ) -> Result<PositionsResponse, KalshiHttpError> {
473 validate_primary(query.subaccount)?;
474 self.get(&["historical", "positions"], query, true).await
475 }
476
477 pub async fn get_fills(&self, query: &FillsQuery) -> Result<FillsResponse, KalshiHttpError> {
483 validate_primary(query.subaccount)?;
484 self.get(&["portfolio", "fills"], query, true).await
485 }
486
487 pub async fn get_historical_fills(
493 &self,
494 query: &HistoryQuery,
495 ) -> Result<FillsResponse, KalshiHttpError> {
496 validate_primary(query.subaccount)?;
497 self.get(&["historical", "fills"], query, true).await
498 }
499
500 pub async fn get_orders(&self, query: &OrdersQuery) -> Result<OrdersResponse, KalshiHttpError> {
506 validate_primary(query.subaccount)?;
507 self.get(&["portfolio", "orders"], query, true).await
508 }
509
510 pub async fn get_order(&self, order_id: &str) -> Result<OrderResponse, KalshiHttpError> {
516 self.get(&["portfolio", "orders", order_id], &(), true)
517 .await
518 }
519
520 pub async fn get_historical_orders(
526 &self,
527 query: &HistoryQuery,
528 ) -> Result<OrdersResponse, KalshiHttpError> {
529 validate_primary(query.subaccount)?;
530 self.get(&["historical", "orders"], query, true).await
531 }
532
533 pub async fn get_settlements(
539 &self,
540 query: &SettlementsQuery,
541 ) -> Result<SettlementsResponse, KalshiHttpError> {
542 validate_primary(query.subaccount)?;
543 self.get(&["portfolio", "settlements"], query, true).await
544 }
545
546 pub async fn get_account_limits(&self) -> Result<AccountLimits, KalshiHttpError> {
552 let limits: AccountLimits = self.get(&["account", "limits"], &(), true).await?;
553 self.quota
554 .set_limits(&limits, get_atomic_clock_realtime().get_time_ms() as i64)
555 .map_err(|e| KalshiHttpError::AfterSend(Box::new(e)))?;
556 Ok(limits)
557 }
558
559 pub async fn get_endpoint_costs(&self) -> Result<EndpointCosts, KalshiHttpError> {
565 let costs: EndpointCosts = self.get(&["account", "endpoint_costs"], &(), false).await?;
566 self.quota
567 .set_costs(costs.clone())
568 .map_err(|e| KalshiHttpError::AfterSend(Box::new(e)))?;
569 Ok(costs)
570 }
571
572 pub async fn create_order(
578 &self,
579 request: &CreateOrderRequest,
580 ) -> Result<CreateOrderResponse, KalshiHttpError> {
581 validate_create(request)?;
582 self.send(
583 Method::POST,
584 &["portfolio", "events", "orders"],
585 &(),
586 Some(request),
587 true,
588 )
589 .await
590 }
591
592 pub async fn batch_create_orders(
600 &self,
601 request: &BatchCreateRequest,
602 ) -> Result<BatchCreateResponse, KalshiHttpError> {
603 self.create_batch(request, true).await
604 }
605
606 pub(crate) async fn create_batch(
607 &self,
608 request: &BatchCreateRequest,
609 complete: bool,
610 ) -> Result<BatchCreateResponse, KalshiHttpError> {
611 if request.orders.is_empty() {
612 return Err(KalshiHttpError::Validation("empty order batch"));
613 }
614
615 let mut identities = HashSet::new();
616
617 for order in &request.orders {
618 validate_create(order)?;
619 let identity = order
620 .client_order_id
621 .as_deref()
622 .filter(|id| !id.is_empty())
623 .ok_or(KalshiHttpError::Validation(
624 "batch children require client order identities",
625 ))?;
626
627 if !identities.insert(identity) {
628 return Err(KalshiHttpError::Validation(
629 "duplicate batch client order identity",
630 ));
631 }
632 }
633
634 let raw = self
635 .send_raw(
636 Method::POST,
637 &["portfolio", "events", "orders", "batched"],
638 &(),
639 Some(request),
640 true,
641 Operation::Write,
642 )
643 .await?;
644 let response: BatchCreateResponse = decode_response(raw.clone())?;
645 let mut returned = HashSet::new();
646
647 if complete
648 && (response.orders.len() != identities.len()
649 || response
650 .orders
651 .iter()
652 .any(|order| match &order.client_order_id {
653 Field::Value(identity) => {
654 !identities.contains(identity.as_str())
655 || !returned.insert(identity.as_str())
656 }
657 _ => true,
658 }))
659 {
660 return Err(unexpected_response(
661 raw,
662 "batch create result identities do not match requests",
663 ));
664 }
665
666 Ok(response)
667 }
668
669 pub async fn amend_order(
677 &self,
678 order_id: &str,
679 request: &AmendOrderRequest,
680 ) -> Result<AmendOrderResponse, KalshiHttpError> {
681 validate_order_values(&request.ticker, request.price, request.count)?;
682 self.send(
683 Method::POST,
684 &["portfolio", "events", "orders", order_id, "amend"],
685 &[("subaccount", 0)],
686 Some(request),
687 true,
688 )
689 .await
690 }
691
692 pub async fn decrease_order(
700 &self,
701 order_id: &str,
702 request: &DecreaseOrderRequest,
703 ) -> Result<DecreaseOrderResponse, KalshiHttpError> {
704 match (request.reduce_by, request.reduce_to) {
705 (Some(value), None)
706 if value.0 > rust_decimal::Decimal::ZERO && value.0.scale() <= 2 => {}
707 (None, Some(value))
708 if value.0 >= rust_decimal::Decimal::ZERO && value.0.scale() <= 2 => {}
709 _ => {
710 return Err(KalshiHttpError::Validation(
711 "exactly one valid decrease selector is required",
712 ));
713 }
714 }
715
716 self.send(
717 Method::POST,
718 &["portfolio", "events", "orders", order_id, "decrease"],
719 &[("subaccount", 0)],
720 Some(request),
721 true,
722 )
723 .await
724 }
725
726 pub async fn cancel_order(
734 &self,
735 order_id: &str,
736 query: &AccountQuery,
737 ) -> Result<CancelOrderResponse, KalshiHttpError> {
738 self.cancel_order_for_market(order_id, query, None).await
739 }
740
741 pub(crate) async fn cancel_order_for_market(
742 &self,
743 order_id: &str,
744 query: &AccountQuery,
745 ticker: Option<&str>,
746 ) -> Result<CancelOrderResponse, KalshiHttpError> {
747 validate_primary(query.subaccount)?;
748 self.send(
749 Method::DELETE,
750 &["portfolio", "events", "orders", order_id],
751 &CancelQuery {
752 account: query,
753 market_ticker: ticker,
754 },
755 Option::<&()>::None,
756 true,
757 )
758 .await
759 }
760
761 pub async fn batch_cancel_orders(
769 &self,
770 request: &BatchCancelRequest,
771 ) -> Result<BatchCancelResponse, KalshiHttpError> {
772 self.cancel_batch(request, true).await
773 }
774
775 pub(crate) async fn cancel_batch(
776 &self,
777 request: &BatchCancelRequest,
778 complete: bool,
779 ) -> Result<BatchCancelResponse, KalshiHttpError> {
780 if request.orders.is_empty() {
781 return Err(KalshiHttpError::Validation("empty cancel batch"));
782 }
783
784 let mut identities = HashSet::new();
785
786 for order in &request.orders {
787 validate_primary(order.subaccount)?;
788 if order.order_id.is_empty() {
789 return Err(KalshiHttpError::Validation("empty order identity"));
790 }
791
792 if !identities.insert(order.order_id.as_str()) {
793 return Err(KalshiHttpError::Validation(
794 "duplicate batch cancel order identity",
795 ));
796 }
797 }
798
799 let raw = self
800 .send_raw(
801 Method::DELETE,
802 &["portfolio", "events", "orders", "batched"],
803 &(),
804 Some(request),
805 true,
806 Operation::Write,
807 )
808 .await?;
809 let response: BatchCancelResponse = decode_response(raw.clone())?;
810 let mut returned = HashSet::new();
811
812 if complete
813 && (response.orders.len() != identities.len()
814 || response.orders.iter().any(|order| {
815 !identities.contains(order.order_id.as_str())
816 || !returned.insert(order.order_id.as_str())
817 }))
818 {
819 return Err(unexpected_response(
820 raw,
821 "batch cancel result identities do not match requests",
822 ));
823 }
824
825 Ok(response)
826 }
827
828 pub async fn get_all_markets(
834 &self,
835 query: MarketsQuery,
836 max_pages: u32,
837 ) -> Result<Pages<Market>, KalshiHttpError> {
838 self.collect_pages(
839 query,
840 max_pages,
841 |q| async move { self.get_markets(&q).await },
842 |m| m.ticker.clone(),
843 )
844 .await
845 }
846
847 pub async fn get_all_historical_markets(
853 &self,
854 query: HistoricalMarketsQuery,
855 max_pages: u32,
856 ) -> Result<Pages<Market>, KalshiHttpError> {
857 self.collect_pages(
858 query,
859 max_pages,
860 |q| async move { self.get_historical_markets(&q).await },
861 |m| m.ticker.clone(),
862 )
863 .await
864 }
865
866 pub async fn get_all_events(
872 &self,
873 query: EventsQuery,
874 max_pages: u32,
875 ) -> Result<Pages<Event>, KalshiHttpError> {
876 self.collect_pages(
877 query,
878 max_pages,
879 |q| async move { self.get_events(&q).await },
880 |e| e.event_ticker.clone(),
881 )
882 .await
883 }
884
885 pub async fn get_all_trades(
891 &self,
892 query: TradesQuery,
893 max_pages: u32,
894 ) -> Result<Pages<Trade>, KalshiHttpError> {
895 self.collect_pages(
896 query,
897 max_pages,
898 |q| async move { self.get_trades(&q).await },
899 |t| t.trade_id.clone(),
900 )
901 .await
902 }
903
904 pub async fn get_all_historical_trades(
910 &self,
911 query: TradesQuery,
912 max_pages: u32,
913 ) -> Result<Pages<Trade>, KalshiHttpError> {
914 self.collect_pages(
915 query,
916 max_pages,
917 |q| async move { self.get_historical_trades(&q).await },
918 |t| t.trade_id.clone(),
919 )
920 .await
921 }
922
923 pub async fn get_all_fills(
929 &self,
930 query: FillsQuery,
931 max_pages: u32,
932 ) -> Result<Pages<Fill>, KalshiHttpError> {
933 self.collect_pages(
934 query,
935 max_pages,
936 |q| async move { self.get_fills(&q).await },
937 |f| format!("{}:{}", f.exchange_index, f.fill_id),
938 )
939 .await
940 }
941
942 pub async fn get_all_historical_fills(
948 &self,
949 query: HistoryQuery,
950 max_pages: u32,
951 ) -> Result<Pages<Fill>, KalshiHttpError> {
952 self.collect_pages(
953 query,
954 max_pages,
955 |q| async move { self.get_historical_fills(&q).await },
956 |f| format!("{}:{}", f.exchange_index, f.fill_id),
957 )
958 .await
959 }
960
961 pub async fn get_all_orders(
967 &self,
968 query: OrdersQuery,
969 max_pages: u32,
970 ) -> Result<Pages<Order>, KalshiHttpError> {
971 self.collect_pages(
972 query,
973 max_pages,
974 |q| async move { self.get_orders(&q).await },
975 |o| o.order_id.clone(),
976 )
977 .await
978 }
979
980 pub async fn get_all_historical_orders(
986 &self,
987 query: HistoryQuery,
988 max_pages: u32,
989 ) -> Result<Pages<Order>, KalshiHttpError> {
990 self.collect_pages(
991 query,
992 max_pages,
993 |q| async move { self.get_historical_orders(&q).await },
994 |o| o.order_id.clone(),
995 )
996 .await
997 }
998
999 pub async fn get_all_settlements(
1005 &self,
1006 query: SettlementsQuery,
1007 max_pages: u32,
1008 ) -> Result<Pages<Settlement>, KalshiHttpError> {
1009 self.collect_pages(
1010 query,
1011 max_pages,
1012 |q| async move { self.get_settlements(&q).await },
1013 |s| format!("{}:{}", s.exchange_index, s.ticker),
1014 )
1015 .await
1016 }
1017
1018 pub async fn get_all_positions(
1024 &self,
1025 query: PositionsQuery,
1026 max_pages: u32,
1027 ) -> Result<PositionPages, KalshiHttpError> {
1028 self.collect_positions(
1029 query,
1030 max_pages,
1031 |q| async move { self.get_positions(&q).await },
1032 )
1033 .await
1034 }
1035
1036 pub async fn get_all_historical_positions(
1042 &self,
1043 query: HistoricalPositionsQuery,
1044 max_pages: u32,
1045 ) -> Result<PositionPages, KalshiHttpError> {
1046 self.collect_positions(query, max_pages, |q| async move {
1047 self.get_historical_positions(&q).await
1048 })
1049 .await
1050 }
1051
1052 async fn collect_positions<Q, F, Fut>(
1053 &self,
1054 mut query: Q,
1055 max_pages: u32,
1056 fetch: F,
1057 ) -> Result<PositionPages, KalshiHttpError>
1058 where
1059 Q: CursorQuery,
1060 F: Fn(Q) -> Fut,
1061 Fut: std::future::Future<Output = Result<PositionsResponse, KalshiHttpError>>,
1062 {
1063 if max_pages == 0 {
1064 return Err(KalshiHttpError::Validation("page budget must be positive"));
1065 }
1066
1067 let mut pagination = Pagination::new(query.cursor());
1068
1069 let mut result = PositionPages {
1070 market_positions: Vec::new(),
1071 event_positions: Vec::new(),
1072 complete: false,
1073 next_cursor: query.cursor().map(str::to_owned),
1074 };
1075
1076 for _ in 0..max_pages {
1077 let page = fetch(query.clone()).await?;
1078 let empty = page.market_positions.is_empty() && page.event_positions.is_empty();
1079 let previous = result.market_positions.len() + result.event_positions.len();
1080 result
1081 .market_positions
1082 .extend(page.market_positions.into_iter().filter(|p| {
1083 pagination.retain(format!("market:{}:{}", p.exchange_index, p.ticker))
1084 }));
1085
1086 result.event_positions.extend(
1087 page.event_positions
1088 .into_iter()
1089 .filter(|p| pagination.retain(format!("event:{}", p.event_ticker))),
1090 );
1091 result.next_cursor = pagination.advance(page.cursor, empty)?;
1092 if result.next_cursor.is_none() {
1093 result.complete = true;
1094 break;
1095 }
1096
1097 if result.market_positions.len() + result.event_positions.len() == previous {
1098 return Err(KalshiHttpError::Pagination(
1099 "page contains no new identities",
1100 ));
1101 }
1102
1103 query.set_cursor(result.next_cursor.clone());
1104 }
1105
1106 Ok(result)
1107 }
1108
1109 async fn collect_pages<Q, P, F, Fut>(
1110 &self,
1111 mut query: Q,
1112 max_pages: u32,
1113 fetch: F,
1114 identity: fn(&P::Item) -> String,
1115 ) -> Result<Pages<P::Item>, KalshiHttpError>
1116 where
1117 Q: CursorQuery,
1118 P: CursorPage,
1119 F: Fn(Q) -> Fut,
1120 Fut: std::future::Future<Output = Result<P, KalshiHttpError>>,
1121 {
1122 if max_pages == 0 {
1123 return Err(KalshiHttpError::Validation("page budget must be positive"));
1124 }
1125
1126 let mut pagination = Pagination::new(query.cursor());
1127
1128 let mut result = Pages {
1129 records: Vec::new(),
1130 complete: false,
1131 next_cursor: query.cursor().map(str::to_owned),
1132 };
1133
1134 for _ in 0..max_pages {
1135 let (records, cursor) = fetch(query.clone()).await?.into_parts();
1136 let empty = records.is_empty();
1137 let previous = result.records.len();
1138 result.records.extend(
1139 records
1140 .into_iter()
1141 .filter(|r| pagination.retain(identity(r))),
1142 );
1143 result.next_cursor = pagination.advance(cursor, empty)?;
1144 if result.next_cursor.is_none() {
1145 result.complete = true;
1146 break;
1147 }
1148
1149 if result.records.len() == previous {
1150 return Err(KalshiHttpError::Pagination(
1151 "page contains no new identities",
1152 ));
1153 }
1154
1155 query.set_cursor(result.next_cursor.clone());
1156 }
1157
1158 Ok(result)
1159 }
1160
1161 async fn get<Q: Serialize, R: DeserializeOwned>(
1162 &self,
1163 path: &[&str],
1164 query: &Q,
1165 authenticated: bool,
1166 ) -> Result<R, KalshiHttpError> {
1167 let response = Box::pin(self.send_raw(
1168 Method::GET,
1169 path,
1170 query,
1171 Option::<&()>::None,
1172 authenticated,
1173 Operation::Read,
1174 ))
1175 .await?;
1176 decode_response(response)
1177 }
1178
1179 async fn send<Q: Serialize, B: Serialize, R: DeserializeOwned>(
1180 &self,
1181 method: Method,
1182 path: &[&str],
1183 query: &Q,
1184 body: Option<&B>,
1185 authenticated: bool,
1186 ) -> Result<R, KalshiHttpError> {
1187 let response = self
1188 .send_raw(method, path, query, body, authenticated, Operation::Write)
1189 .await?;
1190 decode_response(response)
1191 }
1192
1193 async fn send_raw<Q: Serialize, B: Serialize>(
1194 &self,
1195 method: Method,
1196 path: &[&str],
1197 query: &Q,
1198 body: Option<&B>,
1199 authenticated: bool,
1200 operation: Operation,
1201 ) -> Result<HttpResponse, KalshiHttpError> {
1202 if self.cancellation.is_cancelled() {
1203 return Err(KalshiHttpError::Canceled { dispatched: false });
1204 }
1205
1206 if authenticated && self.credential.is_none() {
1207 return Err(
1208 ConfigError::invalid_value("credentials", "authenticated client required").into(),
1209 );
1210 }
1211
1212 if path.iter().any(|p| p.is_empty() || *p == "." || *p == "..") {
1213 return Err(KalshiHttpError::Validation(
1214 "empty or relative path component",
1215 ));
1216 }
1217
1218 let mut url = Url::parse(self.base_url.expose_secret())
1219 .map_err(|_| KalshiHttpError::Validation("invalid base URL"))?;
1220 url.path_segments_mut()
1221 .map_err(|()| KalshiHttpError::Validation("invalid base URL"))?
1222 .pop_if_empty()
1223 .extend(path);
1224 let query = serde_urlencoded::to_string(query).map_err(|_| KalshiHttpError::Encoding)?;
1225 if !query.is_empty() {
1226 url.set_query(Some(&query));
1227 }
1228
1229 let value = body
1230 .map(serde_json::to_value)
1231 .transpose()
1232 .map_err(|_| KalshiHttpError::Encoding)?;
1233 let charge = request_charge(&method, path, &query, value.as_ref(), operation)?;
1234 let body = value
1235 .map(stable_object_key_bytes)
1236 .transpose()
1237 .map_err(|_| KalshiHttpError::Encoding)?;
1238 let discovery = matches!(path, ["account", "limits" | "endpoint_costs"]);
1239 self.request(PreparedRequest {
1240 method,
1241 url,
1242 body,
1243 authenticated,
1244 operation,
1245 charge,
1246 discovery,
1247 })
1248 .await
1249 }
1250
1251 async fn request(&self, request: PreparedRequest) -> Result<HttpResponse, KalshiHttpError> {
1252 let dispatched = AtomicBool::new(false);
1253 let last_response = Mutex::new(None);
1254
1255 let retries = RetryManager::new(RetryConfig {
1256 max_retries: 2,
1257 initial_delay_ms: 250,
1258 max_delay_ms: 1_000,
1259 jitter_ms: 0,
1260 operation_timeout_ms: None,
1261 max_elapsed_ms: Some(self.timeout_ms.saturating_mul(3).saturating_add(2_000)),
1262 ..Default::default()
1263 });
1264
1265 let result = retries
1266 .invocation(
1267 "Kalshi HTTP request",
1268 || async {
1269 *last_response.lock().expect("response lock is not poisoned") = None;
1270 let response = self.send_attempt(&request, &dispatched).await?;
1271 if !response.status.is_success() {
1272 let e = decode_response::<serde_json::Value>(response.clone())
1273 .expect_err("non-success response is an error");
1274
1275 if e.is_retryable() && request.operation == Operation::Read {
1276 *last_response.lock().expect("response lock is not poisoned") =
1277 Some(response);
1278 return Err(e);
1279 }
1280 }
1281
1282 Ok(response)
1283 },
1284 |e| request.operation == Operation::Read && e.is_retryable(),
1285 |reason| match reason {
1286 RetryError::Canceled => KalshiHttpError::Canceled {
1287 dispatched: dispatched.load(Ordering::Acquire),
1288 },
1289 reason => KalshiHttpError::Retry {
1290 reason,
1291 dispatched: dispatched.load(Ordering::Acquire),
1292 },
1293 },
1294 )
1295 .cancellation_token(&self.cancellation)
1296 .execute()
1297 .await;
1298
1299 let result = match result {
1300 Err(KalshiHttpError::Http { .. } | KalshiHttpError::Venue { .. }) => Ok(last_response
1301 .into_inner()
1302 .expect("response lock is not poisoned")
1303 .expect("classified response retained")),
1304 result => result,
1305 };
1306
1307 result.map_err(|e| {
1308 if dispatched.load(Ordering::Acquire) && e.is_definitely_not_sent() {
1309 KalshiHttpError::AfterSend(Box::new(e))
1310 } else {
1311 e
1312 }
1313 })
1314 }
1315
1316 async fn send_attempt(
1317 &self,
1318 request: &PreparedRequest,
1319 dispatched: &AtomicBool,
1320 ) -> Result<HttpResponse, KalshiHttpError> {
1321 loop {
1322 if !request.discovery && self.credential.is_some() && self.quota.needs_refresh() {
1323 Box::pin(self.refresh_quota())
1324 .await
1325 .map_err(|e| KalshiHttpError::Discovery(Box::new(e)))?;
1326 }
1327
1328 match self.quota.acquire(&request.charge).await {
1329 Err(_)
1330 if !request.discovery
1331 && self.credential.is_some()
1332 && self.quota.needs_refresh() => {}
1333 result => {
1334 result?;
1335 break;
1336 }
1337 }
1338 }
1339
1340 let mut headers = HashMap::from([("Accept".into(), "application/json".into())]);
1341 if request.body.is_some() {
1342 headers.insert("Content-Type".into(), "application/json".into());
1343 }
1344
1345 if request.authenticated {
1346 let credential = self
1347 .credential
1348 .as_ref()
1349 .expect("authentication checked before quota wait");
1350 headers.extend(
1351 credential
1352 .headers(
1353 get_atomic_clock_realtime().get_time_ms(),
1354 request.method.as_str(),
1355 request.url.path(),
1356 )?
1357 .into_iter()
1358 .map(|(name, value)| (name, value.into_inner())),
1359 );
1360 }
1361
1362 if self.cancellation.is_cancelled()
1363 || request.operation == Operation::Write
1364 && self.dispatch_check.as_ref().is_some_and(|check| !check())
1365 {
1366 return Err(KalshiHttpError::Canceled {
1367 dispatched: dispatched.load(Ordering::Acquire),
1368 });
1369 }
1370
1371 dispatched.store(true, Ordering::Release);
1372 self.client
1373 .request(
1374 request.method.clone(),
1375 request.url.as_str().to_owned(),
1376 None,
1377 Some(headers),
1378 request.body.clone(),
1379 None,
1380 None,
1381 )
1382 .await
1383 .map_err(KalshiHttpError::Transport)
1384 }
1385
1386 fn authenticated(
1387 config: &KalshiDataClientConfig,
1388 quota: Option<Arc<KalshiQuota>>,
1389 ) -> anyhow::Result<Self> {
1390 config.validate()?;
1391 let credential = KalshiCredential::resolve(
1392 config.api_key_id.clone(),
1393 config.private_key.clone(),
1394 config.environment,
1395 )?;
1396
1397 let identity = config
1398 .api_key_id
1399 .clone()
1400 .or_else(|| {
1401 std::env::var(credential_env_vars(config.environment).0)
1402 .ok()
1403 .map(SecretString::from)
1404 })
1405 .ok_or_else(|| anyhow::anyhow!("missing quota credential identity"))?;
1406
1407 let fingerprint = aws_lc_rs::digest::digest(
1408 &aws_lc_rs::digest::SHA256,
1409 identity.expose_secret().as_bytes(),
1410 )
1411 .as_ref()
1412 .to_vec();
1413 let origin = Url::parse(config.http_url())?
1414 .origin()
1415 .ascii_serialization();
1416 let key = (origin, fingerprint);
1417 let mut owners = QUOTAS.lock().expect("quota registry lock is not poisoned");
1418 if let (Some(existing), Some(requested)) = (owners.get(&key), quota.as_ref()) {
1419 anyhow::ensure!(
1420 Arc::ptr_eq(existing, requested),
1421 "credential already has a different quota owner"
1422 );
1423 }
1424
1425 let quota = owners
1426 .entry(key)
1427 .or_insert_with(|| quota.unwrap_or_else(|| Arc::new(KalshiQuota::new())))
1428 .clone();
1429 drop(owners);
1430 let mut client = Self::build(config)?;
1431 client.credential = Some(Arc::new(credential));
1432 client.quota = quota;
1433 Ok(client)
1434 }
1435
1436 fn build(config: &KalshiDataClientConfig) -> anyhow::Result<Self> {
1437 config.validate()?;
1438 let base_url = SecretString::from(config.http_url().trim_end_matches('/'));
1439 let client = HttpClient::builder()
1440 .timeout_secs(config.http_timeout_secs)
1441 .header_keys(vec!["retry-after".into(), "x-request-id".into()])
1442 .maybe_proxy_url(
1443 config
1444 .proxy_url
1445 .as_ref()
1446 .map(|s| s.expose_secret().to_owned()),
1447 )
1448 .redirect_policy(HttpRedirectPolicy::Reject)
1449 .use_system_proxy(false)
1450 .redact_url(true)
1451 .build()
1452 .map_err(|_| anyhow::anyhow!("failed to build Kalshi HTTP transport"))?;
1453 Ok(Self {
1454 client,
1455 base_url,
1456 credential: None,
1457 cancellation: CancellationToken::new(),
1458 dispatch_check: None,
1459 quota: Arc::new(KalshiQuota::new()),
1460 timeout_ms: config.http_timeout_secs.saturating_mul(1_000),
1461 })
1462 }
1463}
1464
1465type QuotaOwners = HashMap<(String, Vec<u8>), Arc<KalshiQuota>>;
1466
1467#[derive(Clone, Copy, PartialEq, Eq)]
1468enum Operation {
1469 Read,
1470 Write,
1471}
1472
1473struct PreparedRequest {
1474 method: Method,
1475 url: Url,
1476 body: Option<Vec<u8>>,
1477 authenticated: bool,
1478 operation: Operation,
1479 charge: Charge,
1480 discovery: bool,
1481}
1482
1483fn request_charge(
1484 method: &Method,
1485 path: &[&str],
1486 query: &str,
1487 body: Option<&serde_json::Value>,
1488 operation: Operation,
1489) -> Result<Charge, KalshiHttpError> {
1490 let batch =
1491 operation == Operation::Write && path == ["portfolio", "events", "orders", "batched"];
1492
1493 let items = if batch {
1494 u32::try_from(
1495 body.and_then(|value| value.get("orders"))
1496 .and_then(serde_json::Value::as_array)
1497 .map_or(0, Vec::len),
1498 )
1499 .map_err(|_| KalshiHttpError::Quota("batch item count overflow"))?
1500 } else {
1501 1
1502 };
1503
1504 let shard = body
1505 .and_then(|value| value.get("exchange_index"))
1506 .and_then(serde_json::Value::as_u64)
1507 .or_else(|| {
1508 url::form_urlencoded::parse(query.as_bytes())
1509 .find(|(name, _)| name == "exchange_index")
1510 .and_then(|(_, value)| value.parse().ok())
1511 });
1512
1513 let bucket = match operation {
1514 Operation::Read if path == ["portfolio", "balance"] => Bucket::Balance,
1515 Operation::Read => Bucket::Read,
1516 Operation::Write if batch => Bucket::Write(0),
1517 Operation::Write => match shard {
1518 Some(shard) => Bucket::Write(
1519 u32::try_from(shard)
1520 .map_err(|_| KalshiHttpError::Quota("invalid exchange shard"))?,
1521 ),
1522 None => Bucket::Auto,
1523 },
1524 };
1525
1526 Ok(Charge {
1527 method: method.as_str().into(),
1528 path: format!("/trade-api/v2/{}", path.join("/")),
1529 bucket,
1530 items,
1531 })
1532}
1533
1534pub fn stable_object_key_bytes(value: serde_json::Value) -> Result<Vec<u8>, serde_json::Error> {
1545 serde_json::to_vec(&sorted_object_keys(value))
1546}
1547
1548fn sorted_object_keys(value: serde_json::Value) -> serde_json::Value {
1549 match value {
1550 serde_json::Value::Object(map) => {
1551 let mut entries: Vec<_> = map.into_iter().collect();
1552 entries.sort_by(|left, right| left.0.cmp(&right.0));
1553 serde_json::Value::Object(
1554 entries
1555 .into_iter()
1556 .map(|(key, child)| (key, sorted_object_keys(child)))
1557 .collect(),
1558 )
1559 }
1560 serde_json::Value::Array(values) => {
1561 serde_json::Value::Array(values.into_iter().map(sorted_object_keys).collect())
1562 }
1563 value => value,
1564 }
1565}
1566
1567trait CursorPage {
1568 type Item;
1569
1570 fn into_parts(self) -> (Vec<Self::Item>, Field<String>);
1571}
1572
1573macro_rules! cursor_page {
1574 ($($response:ty => $field:ident : $record:ty),+ $(,)?) => { $(
1575 impl CursorPage for $response {
1576 type Item = $record;
1577 fn into_parts(self) -> (Vec<Self::Item>, Field<String>) { (self.$field, self.cursor) }
1578 }
1579 )+ };
1580}
1581
1582cursor_page!(MarketsResponse => markets: Market, EventsResponse => events: Event, TradesResponse => trades: Trade, FillsResponse => fills: Fill, OrdersResponse => orders: Order, SettlementsResponse => settlements: Settlement);
1583
1584fn validate_primary(subaccount: u32) -> Result<(), KalshiHttpError> {
1585 if subaccount != 0 {
1586 return Err(KalshiHttpError::Validation(
1587 "only primary subaccount 0 is supported",
1588 ));
1589 }
1590
1591 Ok(())
1592}
1593
1594fn validate_candlesticks(query: &CandlesticksQuery) -> Result<(), KalshiHttpError> {
1595 if query.start_ts > query.end_ts {
1596 return Err(KalshiHttpError::Validation(
1597 "invalid candle window or period",
1598 ));
1599 }
1600
1601 Ok(())
1602}
1603
1604fn validate_order_values(
1605 ticker: &str,
1606 price: FixedPoint,
1607 count: FixedPoint,
1608) -> Result<(), KalshiHttpError> {
1609 use rust_decimal::Decimal;
1610
1611 if ticker.is_empty()
1612 || price.0 < Decimal::ZERO
1613 || price.0 > Decimal::ONE
1614 || price.0.scale() > 4
1615 || count.0 <= Decimal::ZERO
1616 || count.0.scale() > 2
1617 {
1618 return Err(KalshiHttpError::Validation(
1619 "invalid ticker, price, or count",
1620 ));
1621 }
1622
1623 Ok(())
1624}
1625
1626pub fn validate_create(request: &CreateOrderRequest) -> Result<(), KalshiHttpError> {
1633 validate_primary(request.subaccount)?;
1634 validate_order_values(&request.ticker, request.price, request.count)?;
1635 if request.reduce_only == Some(true) && request.time_in_force != TimeInForce::ImmediateOrCancel
1636 {
1637 return Err(KalshiHttpError::Validation(
1638 "reduce-only requires immediate-or-cancel",
1639 ));
1640 }
1641
1642 if request.expiration_time.is_some() && request.time_in_force != TimeInForce::GoodTillCanceled {
1643 return Err(KalshiHttpError::Validation(
1644 "expiration requires good-till-canceled",
1645 ));
1646 }
1647
1648 Ok(())
1649}
1650
1651impl Debug for KalshiHttpClient {
1652 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1653 f.debug_struct(stringify!(KalshiHttpClient))
1654 .field("base_url", &self.base_url)
1655 .finish_non_exhaustive()
1656 }
1657}
1658
1659#[derive(serde::Serialize)]
1660struct CancelQuery<'a> {
1661 #[serde(flatten)]
1662 account: &'a AccountQuery,
1663 #[serde(skip_serializing_if = "Option::is_none")]
1664 market_ticker: Option<&'a str>,
1665}
1666
1667#[cfg(test)]
1668mod tests {
1669 use rstest::rstest;
1670 #[cfg(not(all(feature = "simulation", madsim)))]
1671 use tokio::io::{AsyncReadExt, AsyncWriteExt};
1672
1673 use super::*;
1674
1675 #[rstest]
1676 fn operation_routes_and_batch_counts_follow_wire_scope() {
1677 let requests: serde_json::Value =
1678 serde_json::from_str(include_str!("../../test_data/rest_requests.json")).unwrap();
1679 let single = request_charge(
1680 &Method::POST,
1681 &["portfolio", "events", "orders"],
1682 "",
1683 Some(&requests["create"]),
1684 Operation::Write,
1685 )
1686 .unwrap();
1687 assert_eq!(single.bucket, Bucket::Write(3));
1688 assert_eq!(single.items, 1);
1689 let batch = request_charge(
1690 &Method::POST,
1691 &["portfolio", "events", "orders", "batched"],
1692 "",
1693 Some(&requests["batch_create"]),
1694 Operation::Write,
1695 )
1696 .unwrap();
1697 assert_eq!(batch.bucket, Bucket::Write(0));
1698 assert_eq!(batch.items, 2);
1699 let cancel = request_charge(
1700 &Method::DELETE,
1701 &["portfolio", "events", "orders", "id"],
1702 "exchange_index=2",
1703 None,
1704 Operation::Write,
1705 )
1706 .unwrap();
1707 assert_eq!(cancel.bucket, Bucket::Write(2));
1708 assert_eq!(cancel.method, "DELETE");
1709 assert_eq!(cancel.path, "/trade-api/v2/portfolio/events/orders/id");
1710 let auto = request_charge(
1711 &Method::POST,
1712 &["portfolio", "events", "orders"],
1713 "",
1714 None,
1715 Operation::Write,
1716 )
1717 .unwrap();
1718 assert_eq!(auto.bucket, Bucket::Auto);
1719 let balance = request_charge(
1720 &Method::GET,
1721 &["portfolio", "balance"],
1722 "exchange_index=3",
1723 None,
1724 Operation::Read,
1725 )
1726 .unwrap();
1727 assert_eq!(balance.bucket, Bucket::Balance);
1728 let market = request_charge(
1729 &Method::GET,
1730 &["markets", "batched"],
1731 "",
1732 None,
1733 Operation::Read,
1734 )
1735 .unwrap();
1736 assert_eq!(market.method, "GET");
1737 assert_eq!(market.path, "/trade-api/v2/markets/batched");
1738 assert_eq!(market.bucket, Bucket::Read);
1739 assert_eq!(market.items, 1);
1740 }
1741
1742 #[cfg(not(all(feature = "simulation", madsim)))]
1743 #[tokio::test]
1744 async fn write_dispatch_check_runs_after_quota_admission() {
1745 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1746 let permitted = Arc::new(AtomicBool::new(true));
1747 let check = Arc::clone(&permitted);
1748
1749 let config = KalshiDataClientConfig {
1750 base_url_http: Some(format!("http://{}", listener.local_addr().unwrap()).into()),
1751 ..Default::default()
1752 };
1753
1754 let client = KalshiHttpClient::new(&config)
1755 .unwrap()
1756 .with_dispatch_check(CancellationToken::new(), move || {
1757 check.load(Ordering::Acquire)
1758 });
1759
1760 let mut fixtures: serde_json::Value =
1761 serde_json::from_str(include_str!("../../test_data/rest_responses.json")).unwrap();
1762 fixtures["limits"]["write"]["refill_rate"] = 1.into();
1763 fixtures["limits"]["write"]["bucket_capacity"] = 1.into();
1764 fixtures["costs"]["default_cost"] = 1.into();
1765 let limits = serde_json::from_value(fixtures["limits"].clone()).unwrap();
1766 let costs = serde_json::from_value(fixtures["costs"].clone()).unwrap();
1767 let unix_ms = i64::try_from(get_atomic_clock_realtime().get_time_ms()).unwrap();
1768 client.quota.set_limits(&limits, unix_ms).unwrap();
1769 client.quota.set_costs(costs).unwrap();
1770 let body = serde_json::from_str::<serde_json::Value>(include_str!(
1771 "../../test_data/rest_requests.json"
1772 ))
1773 .unwrap()["quota_batch"]
1774 .clone();
1775 let path = ["portfolio", "events", "orders", "batched"];
1776 let charge =
1777 request_charge(&Method::POST, &path, "", Some(&body), Operation::Write).unwrap();
1778 client.quota.acquire(&charge).await.unwrap();
1779 let request = client.send_raw(
1780 Method::POST,
1781 &path,
1782 &(),
1783 Some(&body),
1784 false,
1785 Operation::Write,
1786 );
1787 tokio::pin!(request);
1788 assert!(futures_util::poll!(request.as_mut()).is_pending());
1789 permitted.store(false, Ordering::Release);
1790 let result = tokio::select! {
1791 result = &mut request => result,
1792 _ = listener.accept() => panic!("Invalidated write reached the HTTP transport"),
1793 };
1794 assert!(matches!(
1795 result,
1796 Err(KalshiHttpError::Canceled { dispatched: false })
1797 ));
1798 permitted.store(true, Ordering::Release);
1799
1800 let peer = tokio::spawn(async move {
1801 let (mut stream, _) = listener.accept().await.unwrap();
1802 let mut data = [0_u8; 1024];
1803 let read = stream.read(&mut data).await.unwrap();
1804 assert!(
1805 std::str::from_utf8(&data[..read])
1806 .unwrap()
1807 .starts_with("POST /portfolio/events/orders/batched ")
1808 );
1809 stream
1810 .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
1811 .await
1812 .unwrap();
1813 });
1814
1815 let response = client
1816 .send_raw(
1817 Method::POST,
1818 &path,
1819 &(),
1820 Some(&body),
1821 false,
1822 Operation::Write,
1823 )
1824 .await
1825 .unwrap();
1826 assert_eq!(response.status.as_u16(), 200);
1827 peer.await.unwrap();
1828 }
1829}