nautilus_adapters/tardis/http/
parse.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2024 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

use std::str::FromStr;

use chrono::{DateTime, Utc};
use nautilus_core::{nanos::UnixNanos, parsing::precision_from_str};
use nautilus_model::{
    currencies::CURRENCY_MAP,
    enums::{AssetClass, CurrencyType},
    identifiers::Symbol,
    instruments::{
        any::InstrumentAny, crypto_future::CryptoFuture, crypto_perpetual::CryptoPerpetual,
        currency_pair::CurrencyPair, options_contract::OptionsContract,
    },
    types::{currency::Currency, price::Price, quantity::Quantity},
};
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use ustr::Ustr;

use super::types::InstrumentInfo;
use crate::tardis::{
    enums::InstrumentType,
    parse::{normalize_instrument_id, parse_instrument_id, parse_option_kind},
};

#[must_use]
pub fn parse_instrument_any(
    info: InstrumentInfo,
    ts_init: UnixNanos,
    normalize_symbols: bool,
) -> InstrumentAny {
    match info.instrument_type {
        InstrumentType::Spot => parse_spot_instrument(info, ts_init, normalize_symbols),
        InstrumentType::Perpetual => parse_perp_instrument(info, ts_init, normalize_symbols),
        InstrumentType::Future => parse_future_instrument(info, ts_init, normalize_symbols),
        InstrumentType::Option => parse_option_instrument(info, ts_init, normalize_symbols),
    }
}

fn parse_spot_instrument(
    info: InstrumentInfo,
    ts_init: UnixNanos,
    normalize_symbols: bool,
) -> InstrumentAny {
    let instrument_id = if normalize_symbols {
        normalize_instrument_id(&info.exchange, &info.id, info.instrument_type, info.inverse)
    } else {
        parse_instrument_id(&info.exchange, &info.id)
    };

    let raw_symbol = Symbol::new(&info.id);
    let price_increment = get_price_increment(info.price_increment);
    let size_increment = get_size_increment(info.amount_increment);

    let instrument = CurrencyPair::new(
        instrument_id,
        raw_symbol,
        get_currency(info.base_currency.to_uppercase().as_str()),
        get_currency(info.quote_currency.to_uppercase().as_str()),
        price_increment.precision,
        size_increment.precision,
        price_increment,
        size_increment,
        Decimal::from_str(info.taker_fee.to_string().as_str()).expect("Invalid decimal value"),
        Decimal::from_str(info.maker_fee.to_string().as_str()).expect("Invalid decimal value"),
        dec!(0), // TBD
        dec!(0), // TBD
        None,    // TBD
        None,
        Some(Quantity::from(info.min_trade_amount.to_string().as_str())),
        None,
        None,
        None,
        None,
        ts_init, // ts_event same as ts_init (no local timestamp)
        ts_init,
    );

    InstrumentAny::CurrencyPair(instrument)
}

fn parse_perp_instrument(
    info: InstrumentInfo,
    ts_init: UnixNanos,
    normalize_symbols: bool,
) -> InstrumentAny {
    let instrument_id = if normalize_symbols {
        normalize_instrument_id(&info.exchange, &info.id, info.instrument_type, info.inverse)
    } else {
        parse_instrument_id(&info.exchange, &info.id)
    };

    let raw_symbol = Symbol::new(&info.id);
    let price_increment = get_price_increment(info.price_increment);
    let size_increment = get_size_increment(info.amount_increment);

    let instrument = CryptoPerpetual::new(
        instrument_id,
        raw_symbol,
        get_currency(info.base_currency.to_uppercase().as_str()),
        get_currency(info.quote_currency.to_uppercase().as_str()),
        get_currency(
            info.settlement_currency
                .unwrap_or(info.quote_currency)
                .to_uppercase()
                .as_str(),
        ),
        info.inverse.expect("Perpetual should have `inverse` field"),
        price_increment.precision,
        size_increment.precision,
        price_increment,
        size_increment,
        Decimal::from_str(info.taker_fee.to_string().as_str()).expect("Invalid decimal value"),
        Decimal::from_str(info.maker_fee.to_string().as_str()).expect("Invalid decimal value"),
        dec!(0), // TBD
        dec!(0), // TBD
        None,    // TBD
        None,    // TBD
        None,
        Some(Quantity::from(info.min_trade_amount.to_string().as_str())),
        None,
        None,
        None,
        None,
        ts_init, // ts_event same as ts_init (no local timestamp)
        ts_init,
    );

    InstrumentAny::CryptoPerpetual(instrument)
}

fn parse_future_instrument(
    info: InstrumentInfo,
    ts_init: UnixNanos,
    normalize_symbols: bool,
) -> InstrumentAny {
    let instrument_id = if normalize_symbols {
        normalize_instrument_id(&info.exchange, &info.id, info.instrument_type, info.inverse)
    } else {
        parse_instrument_id(&info.exchange, &info.id)
    };

    let raw_symbol = Symbol::new(&info.id);
    let price_increment = get_price_increment(info.price_increment);
    let size_increment = get_size_increment(info.amount_increment);
    let activation = parse_datetime_to_unix_nanos(Some(&info.available_since), "available_since");
    let expiration = parse_datetime_to_unix_nanos(info.expiry.as_deref(), "expiry");

    let instrument = CryptoFuture::new(
        instrument_id,
        raw_symbol,
        get_currency(info.base_currency.to_uppercase().as_str()),
        get_currency(info.quote_currency.to_uppercase().as_str()),
        get_currency(info.base_currency.to_uppercase().as_str()),
        info.inverse.expect("Future should have `inverse` field"),
        activation,
        expiration,
        price_increment.precision,
        size_increment.precision,
        price_increment,
        size_increment,
        Decimal::from_str(info.taker_fee.to_string().as_str()).expect("Invalid decimal value"),
        Decimal::from_str(info.maker_fee.to_string().as_str()).expect("Invalid decimal value"),
        dec!(0), // TBD
        dec!(0), // TBD
        None,    // TBD
        None,    // TBD
        None,
        Some(Quantity::from(info.min_trade_amount.to_string().as_str())),
        None,
        None,
        None,
        None,
        ts_init, // ts_event same as ts_init (no local timestamp)
        ts_init,
    );

    InstrumentAny::CryptoFuture(instrument)
}

fn parse_option_instrument(
    info: InstrumentInfo,
    ts_init: UnixNanos,
    normalize_symbols: bool,
) -> InstrumentAny {
    let instrument_id = if normalize_symbols {
        normalize_instrument_id(&info.exchange, &info.id, info.instrument_type, info.inverse)
    } else {
        parse_instrument_id(&info.exchange, &info.id)
    };

    let raw_symbol = Symbol::new(&info.id);
    let price_increment = get_price_increment(info.price_increment);

    let activation = parse_datetime_to_unix_nanos(Some(&info.available_since), "available_since");
    let expiration = parse_datetime_to_unix_nanos(info.expiry.as_deref(), "expiry");

    let instrument = OptionsContract::new(
        instrument_id,
        raw_symbol,
        AssetClass::Cryptocurrency,
        Some(Ustr::from(instrument_id.venue.as_str())),
        Ustr::from(info.base_currency.to_string().to_uppercase().as_str()),
        parse_option_kind(
            info.option_type
                .expect("Option should have `option_type` field"),
        ),
        Price::new(
            info.strike_price
                .expect("Option should have `strike_price` field"),
            price_increment.precision,
        ),
        get_currency(info.quote_currency.to_uppercase().as_str()),
        activation,
        expiration,
        price_increment.precision,
        price_increment,
        Quantity::from(1),
        Quantity::from(1),
        None, // TBD
        Some(Quantity::from(info.min_trade_amount.to_string().as_str())),
        None, // TBD
        None,
        None,
        None,
        ts_init, // ts_event same as ts_init (no local timestamp)
        ts_init,
    );

    InstrumentAny::OptionsContract(instrument)
}

/// Returns the price increment from the given `value` limiting to a maximum precision of 9.
fn get_price_increment(value: f64) -> Price {
    let value_str = value.to_string();
    let precision = precision_from_str(&value_str);
    match precision {
        ..9 => Price::from(value_str.as_str()),
        _ => Price::from("0.000000001"),
    }
}

/// Returns the size increment from the given `value` limiting to a maximum precision of 9.
fn get_size_increment(value: f64) -> Quantity {
    let value_str = value.to_string();
    let precision = precision_from_str(&value_str);
    match precision {
        ..9 => Quantity::from(value_str.as_str()),
        _ => Quantity::from("0.000000001"),
    }
}

/// Returns the currency either from the internal currency map or creates a default crypto.
fn get_currency(code: &str) -> Currency {
    CURRENCY_MAP
        .lock()
        .unwrap()
        .get(code)
        .copied()
        .unwrap_or(Currency::new(code, 8, 0, code, CurrencyType::Crypto))
}

/// Parses the given RFC 3339 datetime string (UTC) into a `UnixNanos` timestamp.
/// If `value` is `None`, then defaults to the UNIX epoch (0 nanoseconds).
fn parse_datetime_to_unix_nanos(value: Option<&str>, field: &str) -> UnixNanos {
    value
        .map(|dt| {
            UnixNanos::from(
                DateTime::parse_from_rfc3339(dt)
                    .unwrap_or_else(|_| panic!("Failed to parse `{field}`"))
                    .with_timezone(&Utc)
                    .timestamp_nanos_opt()
                    .unwrap_or(0) as u64,
            )
        })
        .unwrap_or_default()
}

////////////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////////////
#[cfg(test)]
mod tests {
    use nautilus_model::identifiers::InstrumentId;
    use rstest::rstest;

    use super::*;
    use crate::tardis::tests::load_test_json;

    #[rstest]
    fn test_parse_instrument_crypto_perpetual() {
        let json_data = load_test_json("instrument_perpetual.json");
        let info: InstrumentInfo = serde_json::from_str(&json_data).unwrap();

        let instrument = parse_instrument_any(info, UnixNanos::default(), false);

        assert_eq!(instrument.id(), InstrumentId::from("XBTUSD.BITMEX"));
        assert_eq!(instrument.raw_symbol(), Symbol::from("XBTUSD"));
        assert_eq!(instrument.underlying(), None);
        assert_eq!(instrument.base_currency(), Some(Currency::BTC()));
        assert_eq!(instrument.quote_currency(), Currency::USD());
        assert_eq!(instrument.settlement_currency(), Currency::USD());
        assert!(instrument.is_inverse());
        assert_eq!(instrument.price_precision(), 1);
        assert_eq!(instrument.size_precision(), 0);
        assert_eq!(instrument.price_increment(), Price::from("0.5"));
        assert_eq!(instrument.size_increment(), Quantity::from(1));
        assert_eq!(instrument.multiplier(), Quantity::from(1));
        assert_eq!(instrument.activation_ns(), None);
        assert_eq!(instrument.expiration_ns(), None);
    }

    // TODO: test_parse_instrument_currency_pair
    // TODO: test_parse_instrument_crypto_future
    // TODO: test_parse_instrument_crypto_option
}