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