Skip to main content

nautilus_finfeed/
instruments.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Explicit instrument selection and fresh definitions from one FinFeed source.
17
18use 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/// Exact outcome IDs explicitly selected from one FinFeed exchange.
38///
39/// IDs come from discovery or are supplied directly. Loading does not implicitly include
40/// other outcomes of the same market or event.
41#[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    /// Provider exchange identifier, such as `POLYMARKET`.
53    pub exchange_id: Ustr,
54    /// Exact outcome IDs, including `_YES` or `_NO`; related outcomes are not loaded implicitly.
55    pub market_ids: Vec<Ustr>,
56}
57
58/// Loads and retains provider-owned definitions for caller publication.
59///
60/// Startup loads replace the catalog only after every selection succeeds. Individual requests
61/// always fetch full metadata and replace only their requested definition after validation.
62/// Errors preserve the prior catalog. Returned definitions are the publication boundary;
63/// this provider does not own a message bus or a native adapter's instrument definitions.
64#[derive(Debug, Clone)]
65pub struct FinFeedInstrumentProvider {
66    http: Arc<FinFeedHttpClient>,
67    instruments: HashMap<InstrumentId, BinaryOption>,
68}
69
70impl FinFeedInstrumentProvider {
71    /// Creates an empty provider sharing the caller's REST client and request budget.
72    #[must_use]
73    pub fn new(http: Arc<FinFeedHttpClient>) -> Self {
74        Self {
75            http,
76            instruments: HashMap::new(),
77        }
78    }
79
80    /// Loads exactly the selected outcomes, in selection order, from fresh full metadata.
81    ///
82    /// Callers can build selections using the REST client's bounded listings or active IDs.
83    /// A successful load replaces the retained catalog, including removing prior selections.
84    /// Failures retain the prior catalog and return no definitions.
85    ///
86    /// # Errors
87    ///
88    /// Returns an error if:
89    /// - A selection is empty, duplicate, unknown, or unavailable.
90    /// - Metadata is incomplete, ambiguous, or inconsistent with the requested identity.
91    /// - Two provider IDs map to the same Polymarket outcome token.
92    /// - A REST request fails.
93    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    /// Returns a newly fetched definition, updating only that instrument on success.
128    ///
129    /// A valid FinFeed ID can be requested even when it was not part of startup selection.
130    /// Failures retain the previous cache.
131    ///
132    /// # Errors
133    ///
134    /// Returns an error if:
135    /// - The ID, metadata, or mapping is invalid, unsupported, or unavailable.
136    /// - Another cached ID owns the same Polymarket outcome token.
137    /// - A REST request fails.
138    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    /// Returns the current definition last accepted by a load or fresh request.
150    #[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}