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, parse_instrument},
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 parse_instrument(&market, ts_init)
179}
180
181pub(crate) fn selected_ids(
182 selections: &[FinFeedInstrumentSelection],
183) -> Result<Vec<InstrumentId>, Error> {
184 if selections.is_empty() {
185 return Err(Error::Validation("instrument selection is empty".into()));
186 }
187 let mut seen = HashSet::new();
188 let mut ids = Vec::new();
189
190 for selection in selections {
191 if selection.market_ids.is_empty() {
192 return Err(Error::Validation("selected market IDs are empty".into()));
193 }
194
195 for market_id in &selection.market_ids {
196 let id = to_instrument_id(&selection.exchange_id, market_id)?;
197 if !seen.insert(id) {
198 return Err(Error::Validation(format!("duplicate selection {id}")));
199 }
200 ids.push(id);
201 }
202 }
203 Ok(ids)
204}
205
206pub(crate) fn check_duplicate_outcome(
207 instruments: &HashMap<InstrumentId, BinaryOption>,
208 instrument: &BinaryOption,
209) -> Result<(), Error> {
210 let token = instrument
211 .info
212 .as_ref()
213 .and_then(|info| info.get(TOKEN_ID_KEY));
214 if instruments.values().any(|existing| {
215 existing.id != instrument.id
216 && token.is_some()
217 && existing
218 .info
219 .as_ref()
220 .and_then(|info| info.get(TOKEN_ID_KEY))
221 == token
222 }) {
223 return Err(Error::Validation(format!(
224 "duplicate outcome mapping for {}",
225 instrument.id
226 )));
227 }
228 Ok(())
229}