nautilus_model/instruments/
synthetic.rs1use std::{
17 collections::HashMap,
18 hash::{Hash, Hasher},
19};
20
21use derive_builder::Builder;
22use evalexpr::{ContextWithMutableVariables, HashMapContext, Node, Value};
23use nautilus_core::{UnixNanos, correctness::FAILED};
24use serde::{Deserialize, Serialize};
25
26use crate::{
27 identifiers::{InstrumentId, Symbol, Venue},
28 types::Price,
29};
30#[derive(Clone, Debug, Builder)]
35#[cfg_attr(
36 feature = "python",
37 pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.model")
38)]
39pub struct SyntheticInstrument {
40 pub id: InstrumentId,
42 pub price_precision: u8,
44 pub price_increment: Price,
46 pub components: Vec<InstrumentId>,
48 pub formula: String,
50 pub ts_event: UnixNanos,
52 pub ts_init: UnixNanos,
54 context: HashMapContext,
55 variables: Vec<String>,
56 operator_tree: Node,
57}
58
59impl Serialize for SyntheticInstrument {
60 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
61 where
62 S: serde::Serializer,
63 {
64 use serde::ser::SerializeStruct;
65 let mut state = serializer.serialize_struct("SyntheticInstrument", 7)?;
66 state.serialize_field("id", &self.id)?;
67 state.serialize_field("price_precision", &self.price_precision)?;
68 state.serialize_field("price_increment", &self.price_increment)?;
69 state.serialize_field("components", &self.components)?;
70 state.serialize_field("formula", &self.formula)?;
71 state.serialize_field("ts_event", &self.ts_event)?;
72 state.serialize_field("ts_init", &self.ts_init)?;
73 state.end()
74 }
75}
76
77impl<'de> Deserialize<'de> for SyntheticInstrument {
78 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
79 where
80 D: serde::Deserializer<'de>,
81 {
82 #[derive(Deserialize)]
83 struct Fields {
84 id: InstrumentId,
85 price_precision: u8,
86 price_increment: Price,
87 components: Vec<InstrumentId>,
88 formula: String,
89 ts_event: UnixNanos,
90 ts_init: UnixNanos,
91 }
92
93 let fields = Fields::deserialize(deserializer)?;
94
95 let variables = fields.components.iter().map(ToString::to_string).collect();
96
97 let operator_tree =
98 evalexpr::build_operator_tree(&fields.formula).map_err(serde::de::Error::custom)?;
99
100 Ok(SyntheticInstrument {
101 id: fields.id,
102 price_precision: fields.price_precision,
103 price_increment: fields.price_increment,
104 components: fields.components,
105 formula: fields.formula,
106 ts_event: fields.ts_event,
107 ts_init: fields.ts_init,
108 context: HashMapContext::new(),
109 variables,
110 operator_tree,
111 })
112 }
113}
114
115impl SyntheticInstrument {
116 pub fn new_checked(
125 symbol: Symbol,
126 price_precision: u8,
127 components: Vec<InstrumentId>,
128 formula: String,
129 ts_event: UnixNanos,
130 ts_init: UnixNanos,
131 ) -> anyhow::Result<Self> {
132 let price_increment = Price::new(10f64.powi(-i32::from(price_precision)), price_precision);
133
134 let variables: Vec<String> = components.iter().map(ToString::to_string).collect();
136
137 let operator_tree = evalexpr::build_operator_tree(&formula)?;
138
139 Ok(Self {
140 id: InstrumentId::new(symbol, Venue::synthetic()),
141 price_precision,
142 price_increment,
143 components,
144 formula,
145 context: HashMapContext::new(),
146 variables,
147 operator_tree,
148 ts_event,
149 ts_init,
150 })
151 }
152
153 pub fn new(
159 symbol: Symbol,
160 price_precision: u8,
161 components: Vec<InstrumentId>,
162 formula: String,
163 ts_event: UnixNanos,
164 ts_init: UnixNanos,
165 ) -> Self {
166 Self::new_checked(
167 symbol,
168 price_precision,
169 components,
170 formula,
171 ts_event,
172 ts_init,
173 )
174 .expect(FAILED)
175 }
176
177 #[must_use]
178 pub fn is_valid_formula(&self, formula: &str) -> bool {
179 evalexpr::build_operator_tree(formula).is_ok()
180 }
181
182 pub fn change_formula(&mut self, formula: String) -> anyhow::Result<()> {
186 let operator_tree = evalexpr::build_operator_tree(&formula)?;
187 self.formula = formula;
188 self.operator_tree = operator_tree;
189 Ok(())
190 }
191
192 pub fn calculate_from_map(&mut self, inputs: &HashMap<String, f64>) -> anyhow::Result<Price> {
203 let mut input_values = Vec::new();
204
205 for variable in &self.variables {
206 if let Some(&value) = inputs.get(variable) {
207 input_values.push(value);
208 self.context
209 .set_value(variable.clone(), Value::Float(value))
210 .unwrap_or_else(|e| {
211 panic!("Failed to set value for variable {variable}: {e}");
212 });
213 } else {
214 panic!("Missing price for component: {variable}");
215 }
216 }
217
218 self.calculate(&input_values)
219 }
220
221 pub fn calculate(&mut self, inputs: &[f64]) -> anyhow::Result<Price> {
227 if inputs.len() != self.variables.len() {
228 anyhow::bail!("Invalid number of input values");
229 }
230
231 for (variable, input) in self.variables.iter().zip(inputs) {
232 self.context
233 .set_value(variable.clone(), Value::Float(*input))?;
234 }
235
236 let result: Value = self.operator_tree.eval_with_context(&self.context)?;
237
238 match result {
239 Value::Float(price) => Ok(Price::new(price, self.price_precision)),
240 _ => anyhow::bail!("Failed to evaluate formula to a floating point number"),
241 }
242 }
243}
244
245impl PartialEq<Self> for SyntheticInstrument {
246 fn eq(&self, other: &Self) -> bool {
247 self.id == other.id
248 }
249}
250
251impl Eq for SyntheticInstrument {}
252
253impl Hash for SyntheticInstrument {
254 fn hash<H: Hasher>(&self, state: &mut H) {
255 self.id.hash(state);
256 }
257}
258
259#[cfg(test)]
263mod tests {
264 use rstest::rstest;
265
266 use super::*;
267
268 #[rstest]
269 fn test_calculate_from_map() {
270 let mut synth = SyntheticInstrument::default();
271 let mut inputs = HashMap::new();
272 inputs.insert("BTC.BINANCE".to_string(), 100.0);
273 inputs.insert("LTC.BINANCE".to_string(), 200.0);
274 let price = synth.calculate_from_map(&inputs).unwrap();
275
276 assert_eq!(price, Price::from("150.0"));
277 assert_eq!(
278 synth.formula,
279 "(BTC.BINANCE + LTC.BINANCE) / 2.0".to_string()
280 );
281 }
282
283 #[rstest]
284 fn test_calculate() {
285 let mut synth = SyntheticInstrument::default();
286 let inputs = vec![100.0, 200.0];
287 let price = synth.calculate(&inputs).unwrap();
288 assert_eq!(price, Price::from("150.0"));
289 }
290
291 #[rstest]
292 fn test_change_formula() {
293 let mut synth = SyntheticInstrument::default();
294 let new_formula = "(BTC.BINANCE + LTC.BINANCE) / 4".to_string();
295 synth.change_formula(new_formula.clone()).unwrap();
296
297 let mut inputs = HashMap::new();
298 inputs.insert("BTC.BINANCE".to_string(), 100.0);
299 inputs.insert("LTC.BINANCE".to_string(), 200.0);
300 let price = synth.calculate_from_map(&inputs).unwrap();
301
302 assert_eq!(price, Price::from("75.0"));
303 assert_eq!(synth.formula, new_formula);
304 }
305}