Skip to main content

nautilus_model/ffi/instruments/
synthetic.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
16use std::ffi::c_char;
17
18use nautilus_core::{
19    UnixNanos,
20    ffi::{
21        abort_on_panic,
22        cvec::CVec,
23        parsing::{bytes_to_string_vec, string_vec_to_bytes},
24        string::{cstr_as_str, str_to_cstr},
25    },
26};
27
28use crate::{
29    identifiers::{InstrumentId, Symbol},
30    instruments::synthetic::SyntheticInstrument,
31    types::{ERROR_PRICE, Price},
32};
33
34/// Creates a new [`SyntheticInstrument`] from the given components and formula.
35///
36/// # Panics
37///
38/// Panics if:
39/// - The components string contains invalid UTF-8 or JSON, or is not an array of instrument IDs.
40/// - An instrument construction check fails, including formula validation.
41///
42/// # Safety
43///
44/// This function assumes:
45/// - `components_ptr` is a valid C string pointer.
46/// - `formula_ptr` is a valid C string pointer.
47///
48/// Returns an owning pointer to the heap-allocated `SyntheticInstrument` which the
49/// caller must eventually pass to [`synthetic_instrument_drop`].
50#[unsafe(no_mangle)]
51pub unsafe extern "C" fn synthetic_instrument_new(
52    symbol: Symbol,
53    price_precision: u8,
54    components_ptr: *const c_char,
55    formula_ptr: *const c_char,
56    ts_event: u64,
57    ts_init: u64,
58) -> *mut SyntheticInstrument {
59    // TODO: There is absolutely no error handling here yet
60    let components = unsafe { bytes_to_string_vec(components_ptr) }
61        .expect("Invalid synthetic instrument components JSON")
62        .into_iter()
63        .map(InstrumentId::from)
64        .collect::<Vec<InstrumentId>>();
65    let formula = unsafe { cstr_as_str(formula_ptr) };
66    let synth = SyntheticInstrument::builder()
67        .symbol(symbol)
68        .price_precision(price_precision)
69        .components(components)
70        .formula(formula)
71        .ts_event(ts_event.into())
72        .ts_init(ts_init.into())
73        .build()
74        .unwrap();
75
76    Box::into_raw(Box::new(synth))
77}
78
79/// # Safety
80///
81/// `synth` must be a live owning pointer returned by [`synthetic_instrument_new`],
82/// and must not be used after this call.
83///
84/// # Panics
85///
86/// Panics if `synth` is null.
87#[unsafe(no_mangle)]
88pub unsafe extern "C" fn synthetic_instrument_drop(synth: *mut SyntheticInstrument) {
89    abort_on_panic(|| {
90        assert!(!synth.is_null(), "`synth` was NULL");
91        // SAFETY: Caller guarantees `synth` was allocated by `synthetic_instrument_new`
92        drop(unsafe { Box::from_raw(synth) }); // Memory freed here
93    });
94}
95
96#[unsafe(no_mangle)]
97pub extern "C" fn synthetic_instrument_id(synth: &SyntheticInstrument) -> InstrumentId {
98    synth.id
99}
100
101#[unsafe(no_mangle)]
102pub extern "C" fn synthetic_instrument_price_precision(synth: &SyntheticInstrument) -> u8 {
103    synth.price_precision
104}
105
106#[unsafe(no_mangle)]
107#[cfg_attr(feature = "high-precision", allow(improper_ctypes_definitions))]
108pub extern "C" fn synthetic_instrument_price_increment(synth: &SyntheticInstrument) -> Price {
109    synth.price_increment
110}
111
112#[unsafe(no_mangle)]
113pub extern "C" fn synthetic_instrument_formula_to_cstr(
114    synth: &SyntheticInstrument,
115) -> *const c_char {
116    str_to_cstr(&synth.formula)
117}
118
119#[unsafe(no_mangle)]
120pub extern "C" fn synthetic_instrument_components_to_cstr(
121    synth: &SyntheticInstrument,
122) -> *const c_char {
123    let components_vec = synth
124        .components
125        .iter()
126        .map(ToString::to_string)
127        .collect::<Vec<String>>();
128
129    string_vec_to_bytes(&components_vec)
130}
131
132#[unsafe(no_mangle)]
133pub extern "C" fn synthetic_instrument_components_count(synth: &SyntheticInstrument) -> usize {
134    synth.components.len()
135}
136
137#[unsafe(no_mangle)]
138pub extern "C" fn synthetic_instrument_ts_event(synth: &SyntheticInstrument) -> UnixNanos {
139    synth.ts_event
140}
141
142#[unsafe(no_mangle)]
143pub extern "C" fn synthetic_instrument_ts_init(synth: &SyntheticInstrument) -> UnixNanos {
144    synth.ts_init
145}
146
147/// Returns 1 if the formula is valid for the components, otherwise 0.
148///
149/// Null pointers and invalid components JSON return 0.
150///
151/// # Panics
152///
153/// Panics if:
154/// - The formula string contains invalid UTF-8.
155/// - A decoded component is not a valid instrument ID.
156///
157/// # Safety
158///
159/// Non-null pointers must reference valid C strings.
160#[unsafe(no_mangle)]
161pub unsafe extern "C" fn synthetic_instrument_is_valid_formula(
162    formula_ptr: *const c_char,
163    components_ptr: *const c_char,
164) -> u8 {
165    if formula_ptr.is_null() || components_ptr.is_null() {
166        return 0;
167    }
168
169    let Ok(components) = (unsafe { bytes_to_string_vec(components_ptr) }) else {
170        return 0;
171    };
172
173    let components = components
174        .into_iter()
175        .map(InstrumentId::from)
176        .collect::<Vec<InstrumentId>>();
177
178    let formula = unsafe { cstr_as_str(formula_ptr) };
179
180    u8::from(SyntheticInstrument::is_valid_formula_for_components(
181        formula,
182        &components,
183    ))
184}
185
186/// # Safety
187///
188/// Assumes `formula_ptr` is a valid C string pointer.
189///
190/// # Panics
191///
192/// Panics if changing the formula fails (i.e., `unwrap()` in `change_formula`).
193#[unsafe(no_mangle)]
194pub unsafe extern "C" fn synthetic_instrument_change_formula(
195    synth: &mut SyntheticInstrument,
196    formula_ptr: *const c_char,
197) {
198    let formula = unsafe { cstr_as_str(formula_ptr) };
199    synth.change_formula(formula).unwrap();
200}
201
202#[unsafe(no_mangle)]
203#[cfg_attr(feature = "high-precision", allow(improper_ctypes_definitions))]
204/// # Safety
205///
206/// `inputs_ptr` must describe initialized `f64` values that remain valid and immutable for the
207/// duration of this call.
208pub unsafe extern "C" fn synthetic_instrument_calculate(
209    synth: &mut SyntheticInstrument,
210    inputs_ptr: &CVec,
211) -> Price {
212    let inputs = unsafe { inputs_ptr.as_slice::<f64>() };
213
214    match synth.calculate(inputs) {
215        Ok(price) => price,
216        Err(_) => ERROR_PRICE,
217    }
218}
219
220#[cfg(test)]
221mod cvec_tests {
222    use std::ffi::CString;
223
224    use nautilus_core::ffi::string::cstr_drop;
225    use rstest::rstest;
226
227    use super::*;
228
229    #[rstest]
230    fn test_synthetic_formula_accepts_valid_components_json() {
231        let synth = SyntheticInstrument::default();
232        let formula = CString::new(synth.formula.as_str()).unwrap();
233        let components = synth
234            .components
235            .iter()
236            .map(ToString::to_string)
237            .collect::<Vec<_>>();
238        let components_ptr = string_vec_to_bytes(&components);
239
240        let valid =
241            unsafe { synthetic_instrument_is_valid_formula(formula.as_ptr(), components_ptr) };
242        unsafe { cstr_drop(components_ptr) };
243
244        assert_eq!(valid, 1);
245    }
246
247    #[rstest]
248    #[case::empty(Vec::new())]
249    #[case::invalid_utf8(vec![0xff])]
250    #[case::invalid_utf8_string(vec![b'[', b'"', 0xff, b'"', b']'])]
251    fn test_synthetic_formula_rejects_invalid_components_json(#[case] bytes: Vec<u8>) {
252        let components = CString::new(bytes).unwrap();
253
254        let valid = unsafe {
255            synthetic_instrument_is_valid_formula(c"BTCUSDT.BINANCE".as_ptr(), components.as_ptr())
256        };
257
258        assert_eq!(valid, 0);
259    }
260
261    #[rstest]
262    fn test_synthetic_calculate_borrows_inputs() {
263        let mut synth = SyntheticInstrument::default();
264        let mut inputs = vec![100.0, 200.0];
265        let cvec = CVec {
266            ptr: inputs.as_mut_ptr().cast(),
267            len: inputs.len(),
268            cap: inputs.capacity(),
269        };
270
271        let price = unsafe { synthetic_instrument_calculate(&mut synth, &cvec) };
272
273        assert_eq!(price, Price::from("150.0"));
274        assert_eq!(inputs, [100.0, 200.0]);
275    }
276}