nautilus_model/ffi/instruments/
synthetic.rs1use 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#[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 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#[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 drop(unsafe { Box::from_raw(synth) }); });
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#[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#[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))]
204pub 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}