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