oa/ml/rl/environment/trading/
execution.rs1use crate::{Error, Result};
3
4pub(super) const BOOK_LEVELS: usize = 20;
5pub(super) const BOOK_MARKET_WIDTH: usize = 6 + BOOK_LEVELS * 4;
6pub(super) const MARGIN_TIERS: usize = 8;
7pub(super) const RULE_WIDTH: usize = 8 + MARGIN_TIERS * 4;
8
9#[derive(Clone, Copy, Debug, PartialEq)]
11pub struct TradingMarginTier {
12 pub notional_limit: f32,
14 pub initial_margin_rate: f32,
16 pub maintenance_margin_rate: f32,
17 pub maintenance_deduction: f32,
19}
20
21#[derive(Clone, Debug)]
23pub struct TradingBook {
24 pub bids: Vec<[f32; 2]>,
26 pub asks: Vec<[f32; 2]>,
28 pub mark_price: f32,
30}
31impl TradingBook {
32 pub(super) fn validate(&self) -> Result<()> {
33 if !self.mark_price.is_finite() || !(1e-12..=1e12).contains(&self.mark_price) {
34 return Err(Error::invalid_argument("invalid trading book mark"));
35 }
36 for (levels, bid) in [(&self.bids, true), (&self.asks, false)] {
37 if levels.is_empty()
38 || levels.len() > BOOK_LEVELS
39 || levels.iter().any(|v| {
40 !v[0].is_finite()
41 || !v[1].is_finite()
42 || !(1e-12..=1e12).contains(&v[0])
43 || !(1e-12..=1e24).contains(&v[1])
44 }) || levels.windows(2).any(|w| {
45 if bid {
46 w[0][0] <= w[1][0]
47 } else {
48 w[0][0] >= w[1][0]
49 }
50 }) {
51 return Err(Error::invalid_argument(
52 "invalid, unsorted or oversized trading depth",
53 ));
54 }
55 }
56 if self.bids[0][0] >= self.asks[0][0] {
57 return Err(Error::invalid_argument("crossed trading book"));
58 }
59 Ok(())
60 }
61 pub(super) fn append(&self, row: &[f32; 3], out: &mut Vec<f32>) {
62 out.extend_from_slice(row);
63 out.extend([
64 self.mark_price,
65 self.bids.len() as f32,
66 self.asks.len() as f32,
67 ]);
68 for levels in [&self.bids, &self.asks] {
69 for i in 0..BOOK_LEVELS {
70 out.extend(levels.get(i).copied().unwrap_or([0.0; 2]));
71 }
72 }
73 }
74}
75
76#[derive(Clone, Debug, PartialEq)]
79pub struct TradingExecution {
80 pub quantity_step: f32,
81 pub fee_per_unit: f32,
82 pub leverage: f32,
84 pub latency_steps: u32,
86 pub max_slippage_bps: f32,
88 pub liquidation_fee: f32,
90 pub margin_tiers: Vec<TradingMarginTier>,
92}
93impl Default for TradingExecution {
94 fn default() -> Self {
95 Self {
96 quantity_step: 0.0,
97 fee_per_unit: 0.0,
98 leverage: 1.0,
99 latency_steps: 0,
100 max_slippage_bps: 10000.0,
101 liquidation_fee: 0.0,
102 margin_tiers: Vec::new(),
103 }
104 }
105}
106impl TradingExecution {
107 pub fn validate(&self) -> Result<()> {
110 if [
111 self.quantity_step,
112 self.fee_per_unit,
113 self.leverage,
114 self.max_slippage_bps,
115 self.liquidation_fee,
116 ]
117 .iter()
118 .any(|v| !v.is_finite())
119 || self.quantity_step < 0.0
120 || self.fee_per_unit < 0.0
121 || !(1.0..=1000.0).contains(&self.leverage)
122 || self.latency_steps > 1_000_000
123 || !(0.0..=10000.0).contains(&self.max_slippage_bps)
124 || !(0.0..0.1).contains(&self.liquidation_fee)
125 || self.margin_tiers.len() > MARGIN_TIERS
126 || (self.leverage > 1.0 && self.margin_tiers.is_empty())
127 {
128 return Err(Error::invalid_argument("invalid trading execution rules"));
129 }
130 let mut previous = 0.0;
131 let mut previous_initial = 0.0;
132 let mut previous_maintenance = 0.0;
133 let mut previous_deduction = 0.0;
134 for t in &self.margin_tiers {
135 if [
136 t.notional_limit,
137 t.initial_margin_rate,
138 t.maintenance_margin_rate,
139 t.maintenance_deduction,
140 ]
141 .iter()
142 .any(|v| !v.is_finite())
143 || t.notional_limit <= previous
144 || t.notional_limit > 1e24
145 || t.initial_margin_rate <= 0.0
146 || t.initial_margin_rate > 1.0
147 || t.initial_margin_rate < previous_initial
148 || t.maintenance_margin_rate <= 0.0
149 || t.maintenance_margin_rate >= t.initial_margin_rate
150 || t.maintenance_margin_rate < previous_maintenance
151 || t.maintenance_deduction < 0.0
152 || t.maintenance_deduction > previous * t.maintenance_margin_rate
153 || t.maintenance_deduction
154 > previous_deduction
155 + previous * (t.maintenance_margin_rate - previous_maintenance)
156 + 1e-5 * (1.0 + previous * t.maintenance_margin_rate)
157 {
158 return Err(Error::invalid_argument("invalid trading margin tiers"));
159 }
160 previous = t.notional_limit;
161 previous_initial = t.initial_margin_rate;
162 previous_maintenance = t.maintenance_margin_rate;
163 previous_deduction = t.maintenance_deduction;
164 }
165 Ok(())
166 }
167 pub(super) fn append(&self, out: &mut Vec<f32>) {
168 out.extend([
169 self.quantity_step,
170 self.fee_per_unit,
171 self.leverage,
172 self.latency_steps as f32,
173 self.max_slippage_bps / 10000.0,
174 self.liquidation_fee,
175 self.margin_tiers.len() as f32,
176 0.0,
177 ]);
178 for i in 0..MARGIN_TIERS {
179 out.extend(self.margin_tiers.get(i).map_or([0.0; 4], |t| {
180 [
181 t.notional_limit,
182 t.initial_margin_rate,
183 t.maintenance_margin_rate,
184 t.maintenance_deduction,
185 ]
186 }));
187 }
188 }
189}