kalshi_rust/collection/
mod.rs

1//! collection.rs – wrappers for Kalshi Trade API → collection (multivariate)
2use crate::{kalshi_error::*, Kalshi};
3use serde::Deserialize;
4use serde_json::Value;
5
6impl Kalshi {
7    /// Retrieves a list of multivariate event collections from the Kalshi exchange.
8    ///
9    /// This method fetches multiple multivariate event collections, allowing for
10    /// pagination. Collections group related markets together for analysis.
11    ///
12    /// # Arguments
13    ///
14    /// * `limit` - An optional integer to limit the number of collections returned.
15    /// * `cursor` - An optional string for pagination cursor.
16    ///
17    /// # Returns
18    ///
19    /// - `Ok((Option<String>, Vec<Collection>))`: A tuple containing an optional pagination cursor
20    ///   and a vector of `Collection` objects on successful retrieval.
21    /// - `Err(KalshiError)`: An error if the user is not authenticated or if there is an issue with the request.
22    ///
23    /// # Example
24    ///
25    /// ```
26    /// // Assuming `kalshi_instance` is an already authenticated instance of `Kalshi`
27    /// let (cursor, collections) = kalshi_instance.get_multivariate_event_collections(
28    ///     Some(10), None
29    /// ).await.unwrap();
30    /// ```
31    ///
32    pub async fn get_multivariate_event_collections(
33        &self,
34        limit: Option<i64>,
35        cursor: Option<String>,
36    ) -> Result<(Option<String>, Vec<Collection>), KalshiError> {
37        let mut p = Vec::new();
38        add_param!(p, "limit", limit);
39        add_param!(p, "cursor", cursor);
40        let path = if p.is_empty() {
41            "/multivariate_event_collections".to_string()
42        } else {
43            format!(
44                "/multivariate_event_collections?{}",
45                serde_urlencoded::to_string(&p)?
46            )
47        };
48        let res: CollectionListResponse = self.signed_get(&path).await?;
49        Ok((res.cursor, res.multivariate_event_collections))
50    }
51
52    /// Retrieves detailed information about a specific multivariate event collection.
53    ///
54    /// This method fetches data for a single multivariate event collection identified
55    /// by its collection ticker. Collections group related markets together for analysis.
56    ///
57    /// # Arguments
58    ///
59    /// * `collection_ticker` - A string slice referencing the collection's unique ticker identifier.
60    ///
61    /// # Returns
62    ///
63    /// - `Ok(Collection)`: Detailed information about the specified collection on successful retrieval.
64    /// - `Err(KalshiError)`: An error if the user is not authenticated or if there is an issue with the request.
65    ///
66    /// # Example
67    ///
68    /// ```
69    /// // Assuming `kalshi_instance` is an already authenticated instance of `Kalshi`
70    /// let collection_ticker = "SOME-COLLECTION";
71    /// let collection = kalshi_instance.get_multivariate_event_collection(collection_ticker).await.unwrap();
72    /// ```
73    ///
74    pub async fn get_multivariate_event_collection(
75        &self,
76        collection_ticker: &str,
77    ) -> Result<Collection, KalshiError> {
78        let path = format!("/multivariate_event_collections/{collection_ticker}");
79        let res: SingleCollectionResponse = self.signed_get(&path).await?;
80        Ok(res.multivariate_event_collection)
81    }
82
83    /// Retrieves the lookup history for a multivariate event collection.
84    ///
85    /// This method fetches the historical lookup data for a collection, allowing for
86    /// pagination. Lookup history shows how markets within the collection have been
87    /// queried over time.
88    ///
89    /// # Arguments
90    ///
91    /// * `collection_ticker` - A string slice referencing the collection's unique ticker identifier.
92    /// * `limit` - An optional integer to limit the number of lookup entries returned.
93    /// * `cursor` - An optional string for pagination cursor.
94    ///
95    /// # Returns
96    ///
97    /// - `Ok((Option<String>, Vec<LookupEntry>))`: A tuple containing an optional pagination cursor
98    ///   and a vector of `LookupEntry` objects on successful retrieval.
99    /// - `Err(KalshiError)`: An error if the user is not authenticated or if there is an issue with the request.
100    ///
101    /// # Example
102    ///
103    /// ```
104    /// // Assuming `kalshi_instance` is an already authenticated instance of `Kalshi`
105    /// let (cursor, lookups) = kalshi_instance.get_collection_lookup_history(
106    ///     "SOME-COLLECTION", Some(50), None
107    /// ).await.unwrap();
108    /// ```
109    ///
110    pub async fn get_collection_lookup_history(
111        &self,
112        collection_ticker: &str,
113        limit: Option<i64>,
114        cursor: Option<String>,
115    ) -> Result<(Option<String>, Vec<LookupEntry>), KalshiError> {
116        let mut p = Vec::new();
117        add_param!(p, "limit", limit);
118        add_param!(p, "cursor", cursor);
119        let query = if p.is_empty() {
120            String::new()
121        } else {
122            format!("?{}", serde_urlencoded::to_string(&p)?)
123        };
124        let path = format!("/multivariate_event_collections/{collection_ticker}/lookup{query}");
125        let res: LookupHistoryResponse = self.signed_get(&path).await?;
126        Ok((res.cursor, res.lookups))
127    }
128
129    /// Creates a new market within a multivariate event collection.
130    ///
131    /// This method adds a new market to an existing collection. The market data
132    /// is provided as a JSON value in the request body.
133    ///
134    /// # Arguments
135    ///
136    /// * `collection_ticker` - A string slice referencing the collection's unique ticker identifier.
137    /// * `body` - A reference to a JSON value containing the market data to be added.
138    ///
139    /// # Returns
140    ///
141    /// - `Ok(Collection)`: The updated collection object after adding the market on successful creation.
142    /// - `Err(KalshiError)`: An error if the user is not authenticated or if there is an issue with the request.
143    ///
144    /// # Example
145    ///
146    /// ```
147    /// // Assuming `kalshi_instance` is an already authenticated instance of `Kalshi`
148    /// use serde_json::json;
149    /// let market_data = json!({
150    ///     "market_ticker": "NEW-MARKET-2024",
151    ///     "title": "New Market Title"
152    /// });
153    /// let updated_collection = kalshi_instance.create_market_in_collection(
154    ///     "SOME-COLLECTION", &market_data
155    /// ).await.unwrap();
156    /// ```
157    ///
158    pub async fn create_market_in_collection(
159        &self,
160        collection_ticker: &str,
161        body: &Value,
162    ) -> Result<Collection, KalshiError> {
163        let path = format!("/multivariate_event_collections/{collection_ticker}");
164        let res: SingleCollectionResponse = self.signed_post(&path, body).await?;
165        Ok(res.multivariate_event_collection)
166    }
167
168    /// Performs a batch lookup for market tickers within a collection.
169    ///
170    /// This method allows querying multiple market tickers within a collection
171    /// in a single request, returning the updated collection with lookup results.
172    ///
173    /// # Arguments
174    ///
175    /// * `collection_ticker` - A string slice referencing the collection's unique ticker identifier.
176    /// * `body` - A reference to a JSON value containing the market tickers to lookup
177    ///   (e.g., `{"market_tickers": ["A", "B", "C"]}`).
178    ///
179    /// # Returns
180    ///
181    /// - `Ok(Collection)`: The updated collection object with lookup results on successful operation.
182    /// - `Err(KalshiError)`: An error if the user is not authenticated or if there is an issue with the request.
183    ///
184    /// # Example
185    ///
186    /// ```
187    /// // Assuming `kalshi_instance` is an already authenticated instance of `Kalshi`
188    /// use serde_json::json;
189    /// let tickers = json!({
190    ///     "market_tickers": ["MARKET-A", "MARKET-B", "MARKET-C"]
191    /// });
192    /// let result = kalshi_instance.lookup_tickers_for_market(
193    ///     "SOME-COLLECTION", &tickers
194    /// ).await.unwrap();
195    /// ```
196    ///
197    pub async fn lookup_tickers_for_market(
198        &self,
199        collection_ticker: &str,
200        body: &Value,
201    ) -> Result<Collection, KalshiError> {
202        let path = format!("/multivariate_event_collections/{collection_ticker}/tickers");
203        let res: SingleCollectionResponse = self.signed_put(&path, Some(body)).await?;
204        Ok(res.multivariate_event_collection)
205    }
206}
207
208// -------- public models --------
209
210/// Represents a multivariate event collection on the Kalshi exchange.
211///
212/// Collections group related markets together for analysis and management.
213/// The schema is currently untyped as it's not publicly documented.
214pub type Collection = Value;
215
216/// Represents a lookup entry in a collection's history.
217///
218/// Lookup entries track how markets within a collection have been queried.
219/// The schema is currently untyped as it's not publicly documented.
220pub type LookupEntry = Value;
221
222// -------- response wrappers --------
223
224#[derive(Debug, Deserialize)]
225struct CollectionListResponse {
226    cursor: Option<String>,
227    multivariate_event_collections: Vec<Collection>,
228}
229
230#[derive(Debug, Deserialize)]
231struct SingleCollectionResponse {
232    multivariate_event_collection: Collection,
233}
234
235#[derive(Debug, Deserialize)]
236struct LookupHistoryResponse {
237    cursor: Option<String>,
238    lookups: Vec<LookupEntry>,
239}