Skip to main content

nautilus_serialization/arrow/instrument/
index_instrument.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//! Arrow serialization for IndexInstrument instruments.
17
18use std::{borrow::Borrow, collections::HashMap, str::FromStr, sync::Arc};
19
20use arrow::{
21    array::{Array, StringArray, StringBuilder, UInt8Array, UInt64Array},
22    datatypes::{DataType, Field, Schema},
23    error::ArrowError,
24    record_batch::RecordBatch,
25};
26use nautilus_core::{Params, UnixNanos};
27use nautilus_model::{
28    identifiers::{InstrumentId, Symbol},
29    instruments::index_instrument::IndexInstrument,
30    types::{price::Price, quantity::Quantity},
31};
32
33use crate::arrow::{
34    ArrowSchemaProvider, EncodeToRecordBatch, EncodingError, KEY_INSTRUMENT_ID,
35    KEY_PRICE_PRECISION, extract_column, extract_column_by_name,
36    extract_optional_string_column_by_name, json_string_field, metadata_with_type_name,
37    optional_ustr_value, record_batch_with_timestamps, record_batch_with_u64_timestamps,
38    timestamp_data_type,
39};
40
41impl ArrowSchemaProvider for IndexInstrument {
42    fn get_schema(metadata: Option<HashMap<String, String>>) -> Schema {
43        let fields = vec![
44            Field::new("id", DataType::Utf8, false),
45            Field::new("raw_symbol", DataType::Utf8, false),
46            Field::new("currency", DataType::Utf8, false),
47            Field::new("price_precision", DataType::UInt8, false),
48            Field::new("price_increment", DataType::Utf8, false),
49            Field::new("size_precision", DataType::UInt8, false),
50            Field::new("size_increment", DataType::Utf8, false),
51            Field::new("tick_scheme", DataType::Utf8, true),
52            json_string_field("info", true),
53            Field::new("ts_event", timestamp_data_type(), false),
54            Field::new("ts_init", timestamp_data_type(), false),
55        ];
56
57        Schema::new_with_metadata(fields, metadata_with_type_name("IndexInstrument", metadata))
58    }
59}
60
61impl EncodeToRecordBatch for IndexInstrument {
62    fn encode_batch<T>(
63        #[allow(unused)] metadata: &HashMap<String, String>,
64        data: &[T],
65    ) -> Result<RecordBatch, ArrowError>
66    where
67        T: std::borrow::Borrow<Self>,
68    {
69        let mut id_builder = StringBuilder::new();
70        let mut raw_symbol_builder = StringBuilder::new();
71        let mut currency_builder = StringBuilder::new();
72        let mut price_precision_builder = UInt8Array::builder(data.len());
73        let mut size_precision_builder = UInt8Array::builder(data.len());
74        let mut price_increment_builder = StringBuilder::new();
75        let mut size_increment_builder = StringBuilder::new();
76        let mut tick_scheme_builder = StringBuilder::new();
77        let mut info_builder = StringBuilder::new();
78        let mut ts_event_builder = UInt64Array::builder(data.len());
79        let mut ts_init_builder = UInt64Array::builder(data.len());
80
81        for index in data.iter().map(Borrow::borrow) {
82            id_builder.append_value(index.id.to_string());
83            raw_symbol_builder.append_value(index.raw_symbol);
84            currency_builder.append_value(index.currency.to_string());
85            price_precision_builder.append_value(index.price_precision);
86            price_increment_builder.append_value(index.price_increment.to_string());
87            size_precision_builder.append_value(index.size_precision);
88            size_increment_builder.append_value(index.size_increment.to_string());
89
90            if let Some(tick_scheme) = index.tick_scheme {
91                tick_scheme_builder.append_value(tick_scheme);
92            } else {
93                tick_scheme_builder.append_null();
94            }
95
96            if let Some(ref info) = index.info {
97                match serde_json::to_string(info) {
98                    Ok(json) => {
99                        info_builder.append_value(json);
100                    }
101                    Err(e) => {
102                        return Err(ArrowError::InvalidArgumentError(format!(
103                            "Failed to serialize info dict to JSON: {e}"
104                        )));
105                    }
106                }
107            } else {
108                info_builder.append_null();
109            }
110
111            ts_event_builder.append_value(index.ts_event.as_u64());
112            ts_init_builder.append_value(index.ts_init.as_u64());
113        }
114
115        record_batch_with_timestamps(
116            Self::get_schema(Some(metadata.clone())).into(),
117            vec![
118                Arc::new(id_builder.finish()),
119                Arc::new(raw_symbol_builder.finish()),
120                Arc::new(currency_builder.finish()),
121                Arc::new(price_precision_builder.finish()),
122                Arc::new(price_increment_builder.finish()),
123                Arc::new(size_precision_builder.finish()),
124                Arc::new(size_increment_builder.finish()),
125                Arc::new(tick_scheme_builder.finish()),
126                Arc::new(info_builder.finish()),
127                Arc::new(ts_event_builder.finish()),
128                Arc::new(ts_init_builder.finish()),
129            ],
130        )
131    }
132
133    fn metadata(&self) -> HashMap<String, String> {
134        let mut metadata = HashMap::new();
135        metadata.insert(KEY_INSTRUMENT_ID.to_string(), self.id.to_string());
136        metadata.insert(
137            KEY_PRICE_PRECISION.to_string(),
138            self.price_precision.to_string(),
139        );
140        metadata
141    }
142}
143
144/// Decodes [`IndexInstrument`] instruments from a record batch.
145///
146/// Not a [`DecodeFromRecordBatch`] implementation because that trait requires `Into<Data>`.
147///
148/// # Errors
149///
150/// Returns an error if the record batch cannot be decoded.
151///
152/// [`DecodeFromRecordBatch`]: crate::arrow::DecodeFromRecordBatch
153pub fn decode_index_instrument_batch(
154    #[allow(unused)] metadata: &HashMap<String, String>,
155    record_batch: &RecordBatch,
156) -> Result<Vec<IndexInstrument>, EncodingError> {
157    let record_batch = record_batch_with_u64_timestamps(record_batch)?;
158    let record_batch = &record_batch;
159    let cols = record_batch.columns();
160    let num_rows = record_batch.num_rows();
161
162    let id_values = extract_column::<StringArray>(cols, "id", 0, DataType::Utf8)?;
163    let raw_symbol_values = extract_column::<StringArray>(cols, "raw_symbol", 1, DataType::Utf8)?;
164    let currency_values = extract_column::<StringArray>(cols, "currency", 2, DataType::Utf8)?;
165    let price_precision_values =
166        extract_column::<UInt8Array>(cols, "price_precision", 3, DataType::UInt8)?;
167    let price_increment_values =
168        extract_column::<StringArray>(cols, "price_increment", 4, DataType::Utf8)?;
169    let size_precision_values =
170        extract_column::<UInt8Array>(cols, "size_precision", 5, DataType::UInt8)?;
171    let size_increment_values =
172        extract_column::<StringArray>(cols, "size_increment", 6, DataType::Utf8)?;
173    let tick_scheme_values = extract_optional_string_column_by_name(record_batch, "tick_scheme")?;
174    let info_values = extract_column_by_name::<StringArray>(record_batch, "info", DataType::Utf8)?;
175    let ts_event_values =
176        extract_column_by_name::<UInt64Array>(record_batch, "ts_event", DataType::UInt64)?;
177    let ts_init_values =
178        extract_column_by_name::<UInt64Array>(record_batch, "ts_init", DataType::UInt64)?;
179
180    let mut result = Vec::with_capacity(num_rows);
181
182    for i in 0..num_rows {
183        let id = InstrumentId::from_str(id_values.value(i))
184            .map_err(|e| EncodingError::ParseError("id", format!("row {i}: {e}")))?;
185        let raw_symbol = Symbol::from(raw_symbol_values.value(i));
186        let currency = super::decode_currency(
187            currency_values.value(i),
188            "currency",
189            "index_instrument.currency",
190            i,
191        )?;
192        let price_prec = price_precision_values.value(i);
193        let size_prec = size_precision_values.value(i);
194
195        let price_increment = Price::from_str(price_increment_values.value(i))
196            .map_err(|e| EncodingError::ParseError("price_increment", format!("row {i}: {e}")))?;
197        let size_increment = Quantity::from_str(size_increment_values.value(i))
198            .map_err(|e| EncodingError::ParseError("size_increment", format!("row {i}: {e}")))?;
199
200        let info = if info_values.is_null(i) {
201            None
202        } else {
203            let info_json = info_values
204                .as_any()
205                .downcast_ref::<StringArray>()
206                .ok_or_else(|| EncodingError::ParseError("info", format!("row {i}: invalid type")))?
207                .value(i);
208
209            match serde_json::from_str::<Params>(info_json) {
210                Ok(info_dict) => Some(info_dict),
211                Err(e) => {
212                    return Err(EncodingError::ParseError(
213                        "info",
214                        format!("row {i}: failed to deserialize JSON: {e}"),
215                    ));
216                }
217            }
218        };
219
220        let ts_event = UnixNanos::from(ts_event_values.value(i));
221        let ts_init = UnixNanos::from(ts_init_values.value(i));
222
223        let tick_scheme = optional_ustr_value(tick_scheme_values, i);
224
225        let index_instrument = IndexInstrument::builder()
226            .instrument_id(id)
227            .raw_symbol(raw_symbol)
228            .currency(currency)
229            .price_precision(price_prec)
230            .size_precision(size_prec)
231            .price_increment(price_increment)
232            .size_increment(size_increment)
233            .maybe_tick_scheme(tick_scheme)
234            .maybe_info(info)
235            .ts_event(ts_event)
236            .ts_init(ts_init)
237            .build()
238            .map_err(|e| super::instrument_validation_error::<IndexInstrument>(i, e))?;
239
240        result.push(index_instrument);
241    }
242
243    Ok(result)
244}