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 = "posei_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 .expect("TODO: Unable to set value");
211 } else {
212 panic!("Missing price for component: {variable}");
213 }
214 }
215
216 self.calculate(&input_values)
217 }
218
219 pub fn calculate(&mut self, inputs: &[f64]) -> anyhow::Result<Price> {
225 if inputs.len() != self.variables.len() {
226 anyhow::bail!("Invalid number of input values");
227 }
228
229 for (variable, input) in self.variables.iter().zip(inputs) {
230 self.context
231 .set_value(variable.clone(), Value::Float(*input))?;
232 }
233
234 let result: Value = self.operator_tree.eval_with_context(&self.context)?;
235
236 match result {
237 Value::Float(price) => Ok(Price::new(price, self.price_precision)),
238 _ => anyhow::bail!("Failed to evaluate formula to a floating point number"),
239 }
240 }
241}
242
243impl PartialEq<Self> for SyntheticInstrument {
244 fn eq(&self, other: &Self) -> bool {
245 self.id == other.id
246 }
247}
248
249impl Eq for SyntheticInstrument {}
250
251impl Hash for SyntheticInstrument {
252 fn hash<H: Hasher>(&self, state: &mut H) {
253 self.id.hash(state);
254 }
255}
256
257#[cfg(test)]
261mod tests {
262 use rstest::rstest;
263
264 use super::*;
265
266 #[rstest]
267 fn test_calculate_from_map() {
268 let mut synth = SyntheticInstrument::default();
269 let mut inputs = HashMap::new();
270 inputs.insert("BTC.BINANCE".to_string(), 100.0);
271 inputs.insert("LTC.BINANCE".to_string(), 200.0);
272 let price = synth.calculate_from_map(&inputs).unwrap();
273
274 assert_eq!(price, Price::from("150.0"));
275 assert_eq!(
276 synth.formula,
277 "(BTC.BINANCE + LTC.BINANCE) / 2.0".to_string()
278 );
279 }
280
281 #[rstest]
282 fn test_calculate() {
283 let mut synth = SyntheticInstrument::default();
284 let inputs = vec![100.0, 200.0];
285 let price = synth.calculate(&inputs).unwrap();
286 assert_eq!(price, Price::from("150.0"));
287 }
288
289 #[rstest]
290 fn test_change_formula() {
291 let mut synth = SyntheticInstrument::default();
292 let new_formula = "(BTC.BINANCE + LTC.BINANCE) / 4".to_string();
293 synth.change_formula(new_formula.clone()).unwrap();
294
295 let mut inputs = HashMap::new();
296 inputs.insert("BTC.BINANCE".to_string(), 100.0);
297 inputs.insert("LTC.BINANCE".to_string(), 200.0);
298 let price = synth.calculate_from_map(&inputs).unwrap();
299
300 assert_eq!(price, Price::from("75.0"));
301 assert_eq!(synth.formula, new_formula);
302 }
303}