nautilus_finfeed/
instruments.rs1use std::{
19 collections::{HashMap, HashSet},
20 sync::Arc,
21};
22
23use nautilus_core::UnixNanos;
24use nautilus_model::{identifiers::InstrumentId, instruments::BinaryOption};
25use serde::{Deserialize, Serialize};
26use ustr::Ustr;
27
28use crate::{
29 common::symbol::{from_instrument_id, to_instrument_id},
30 http::{
31 client::FinFeedHttpClient,
32 error::Error,
33 parse::{TOKEN_ID_KEY, kalshi_identity, parse_instrument, parse_kalshi},
34 },
35};
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
42#[serde(deny_unknown_fields)]
43#[cfg_attr(
44 feature = "python",
45 pyo3::pyclass(module = "nautilus_trader.adapters.finfeed", from_py_object)
46)]
47#[cfg_attr(
48 feature = "python",
49 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.finfeed")
50)]
51pub struct FinFeedInstrumentSelection {
52 pub exchange_id: Ustr,
54 pub market_ids: Vec<Ustr>,
56}
57
58#[derive(Debug, Clone)]
65pub struct FinFeedInstrumentProvider {
66 http: Arc<FinFeedHttpClient>,
67 instruments: HashMap<InstrumentId, BinaryOption>,
68}
69
70impl FinFeedInstrumentProvider {
71 #[must_use]
73 pub fn new(http: Arc<FinFeedHttpClient>) -> Self {
74 Self {
75 http,
76 instruments: HashMap::new(),
77 }
78 }
79
80 pub async fn load(
94 &mut self,
95 selections: &[FinFeedInstrumentSelection],
96 ts_init: UnixNanos,
97 ) -> Result<Vec<BinaryOption>, Error> {
98 let ids = selected_ids(selections)?;
99 let exchanges = self.http.get_exchanges().await?;
100 let available: HashSet<_> = exchanges
101 .iter()
102 .filter_map(|exchange| exchange.exchange_id.as_deref())
103 .collect();
104
105 for selection in selections {
106 if !available.contains(selection.exchange_id.as_str()) {
107 return Err(Error::Validation(format!(
108 "selected exchange {} is unavailable",
109 selection.exchange_id
110 )));
111 }
112 }
113
114 let mut instruments = HashMap::new();
115 let mut loaded = Vec::with_capacity(ids.len());
116 for instrument_id in ids {
117 let instrument = fetch_instrument(&self.http, instrument_id, ts_init).await?;
118 check_duplicate_outcome(&instruments, &instrument)?;
119 instruments.insert(instrument.id, instrument.clone());
120 loaded.push(instrument);
121 }
122
123 self.instruments = instruments;
124 Ok(loaded)
125 }
126
127 pub async fn request_instrument(
139 &mut self,
140 instrument_id: InstrumentId,
141 ts_init: UnixNanos,
142 ) -> Result<BinaryOption, Error> {
143 let instrument = fetch_instrument(&self.http, instrument_id, ts_init).await?;
144 check_duplicate_outcome(&self.instruments, &instrument)?;
145 self.instruments.insert(instrument.id, instrument.clone());
146 Ok(instrument)
147 }
148
149 #[must_use]
151 pub fn get(&self, instrument_id: InstrumentId) -> Option<&BinaryOption> {
152 self.instruments.get(&instrument_id)
153 }
154}
155
156pub(crate) async fn fetch_instrument(
157 http: &FinFeedHttpClient,
158 instrument_id: InstrumentId,
159 ts_init: UnixNanos,
160) -> Result<BinaryOption, Error> {
161 let (exchange_id, market_id) = from_instrument_id(instrument_id)?;
162 let market = match http.get_market(&exchange_id, &market_id).await {
163 Err(Error::Http { status: 404, .. }) => return Err(Error::Unavailable(instrument_id)),
164 result => result?,
165 };
166
167 if market.exchange_id.as_deref() != Some(exchange_id.as_str())
168 || market.market_id.as_deref() != Some(market_id.as_str())
169 {
170 return Err(Error::Definition {
171 exchange_id,
172 market_id,
173 field: "identity",
174 reason: "does not match the requested outcome",
175 });
176 }
177
178 if exchange_id == "KALSHI" {
179 let (ticker, event_ticker) = kalshi_identity(&market)?;
180 let (native, event) = http.kalshi_metadata(&ticker, &event_ticker).await?;
181 parse_kalshi(&market, &native, &event, ts_init)
182 } else {
183 parse_instrument(&market, ts_init)
184 }
185}
186
187pub(crate) fn selected_ids(
188 selections: &[FinFeedInstrumentSelection],
189) -> Result<Vec<InstrumentId>, Error> {
190 if selections.is_empty() {
191 return Err(Error::Validation("instrument selection is empty".into()));
192 }
193 let mut seen = HashSet::new();
194 let mut ids = Vec::new();
195
196 for selection in selections {
197 if selection.market_ids.is_empty() {
198 return Err(Error::Validation("selected market IDs are empty".into()));
199 }
200
201 for market_id in &selection.market_ids {
202 let id = to_instrument_id(&selection.exchange_id, market_id)?;
203 if !seen.insert(id) {
204 return Err(Error::Validation(format!("duplicate selection {id}")));
205 }
206 ids.push(id);
207 }
208 }
209 Ok(ids)
210}
211
212pub(crate) fn check_duplicate_outcome(
213 instruments: &HashMap<InstrumentId, BinaryOption>,
214 instrument: &BinaryOption,
215) -> Result<(), Error> {
216 let token = instrument
217 .info
218 .as_ref()
219 .and_then(|info| info.get(TOKEN_ID_KEY));
220 if instruments.values().any(|existing| {
221 existing.id != instrument.id
222 && token.is_some()
223 && existing
224 .info
225 .as_ref()
226 .and_then(|info| info.get(TOKEN_ID_KEY))
227 == token
228 }) {
229 return Err(Error::Validation(format!(
230 "duplicate outcome mapping for {}",
231 instrument.id
232 )));
233 }
234 Ok(())
235}