1use super::{
7 Environment, EnvironmentExecution, EnvironmentSpace, EnvironmentSpec, EnvironmentTransition,
8};
9pub use crate::ml::types::TradingConfig;
10use crate::runtime::{BufferBinding, ComputeDispatch, KernelId, PushConstant, SemanticDispatch};
11use crate::{DType, Error, Matrix, OpAttribute, Result, Runtime, matrix};
12
13pub const TRADING_ACCOUNT_FEATURES: usize = 16;
17pub const TRADING_LEDGER_WIDTH: usize = 26;
20pub const TRADING_ELEMENT_BUDGET: usize = 128_000_000;
24
25mod execution;
26mod state;
27use execution::{BOOK_MARKET_WIDTH, RULE_WIDTH};
28pub use execution::{TradingBook, TradingExecution, TradingMarginTier};
29pub use state::TradingState;
30
31#[derive(Clone, Debug)]
33pub struct TradingSeries {
34 pub timestamps: Vec<i64>,
36 pub market: Vec<[f32; 3]>,
39 pub features: Vec<f32>,
41 pub feature_width: usize,
43 pub execution: TradingExecution,
45 pub books: Vec<TradingBook>,
47}
48
49impl TradingConfig {
50 pub fn validate(self) -> Result<()> {
55 if self.environments == 0
56 || self.environments > 65536
57 || !(1..=1024).contains(&self.window)
58 || self.horizon == 0
59 || self.horizon > 1_000_000
60 || [
61 self.capital,
62 self.exposure,
63 self.taker_fee,
64 self.maker_fee,
65 self.slippage_bps,
66 self.spread_bps,
67 self.max_drawdown,
68 ]
69 .iter()
70 .any(|x| !x.is_finite())
71 || !(0.000001..=1e12).contains(&self.capital)
72 || !(0.000001..=1.0).contains(&self.exposure)
73 || !(0.0..0.1).contains(&self.taker_fee)
74 || !(0.0..0.1).contains(&self.maker_fee)
75 || !(0.0..1000.0).contains(&self.slippage_bps)
76 || !(0.0..1000.0).contains(&self.spread_bps)
77 || self.maker_window_steps > 1_000_000
78 || self.maker_requotes > 1024
79 || (self.maker_window_steps == 0 && (self.maker_requotes != 0 || self.maker_fee != 0.0))
80 || self.max_drawdown <= 0.0
81 || self.max_drawdown >= 1.0
82 {
83 return Err(Error::invalid_argument(
84 "invalid unlevered trading research configuration",
85 ));
86 }
87 Ok(())
88 }
89 fn identity(self) -> u64 {
90 [
91 self.environments,
92 self.window,
93 self.horizon,
94 self.capital.to_bits(),
95 self.exposure.to_bits(),
96 self.taker_fee.to_bits(),
97 self.slippage_bps.to_bits(),
98 self.spread_bps.to_bits(),
99 self.max_drawdown.to_bits(),
100 u32::from(self.perpetual),
101 u32::from(self.liquidate_at_horizon),
102 self.maker_window_steps,
103 self.maker_requotes,
104 self.maker_fee.to_bits(),
105 ]
106 .into_iter()
107 .flat_map(u32::to_le_bytes)
108 .fold(14695981039346656037_u64, |h, b| {
109 (h ^ u64::from(b)).wrapping_mul(1099511628211)
110 })
111 }
112}
113
114#[must_use]
119pub struct TradingEnvironment<'runtime> {
120 runtime: &'runtime Runtime,
121 execution: EnvironmentExecution,
122 config: TradingConfig,
123 spec: EnvironmentSpec,
124 market: Matrix,
125 features: Matrix,
126 bounds: Matrix,
127 rules: Matrix,
128 ledger: Matrix,
129 meta: Matrix,
130 done: Matrix,
131 observation: Matrix,
132 width: u32,
133 market_width: u32,
134 pending_seed: Option<u64>,
135 committed: bool,
136 reset_pending: bool,
137 rollback_observation: Option<Matrix>,
138 force_end: bool,
139 tables_valid: bool,
140 source: crate::crypto::Hash,
141}
142
143impl<'runtime> TradingEnvironment<'runtime> {
144 pub fn set_taker_fee(&mut self, taker_fee: f32) -> Result<()> {
153 let next = TradingConfig {
154 taker_fee,
155 ..self.config
156 };
157 next.validate()?;
158 if !self.tables_valid
159 || self.execution.has_active_recording()
160 || self.execution.has_pending_event()
161 {
162 return Err(Error::failed_precondition(
163 "fee changes require idle trading execution",
164 ));
165 }
166 self.runtime.checkpoint()?.wait()?;
167 if self.committed {
168 self.check_status()?;
169 let metadata = self.meta.read::<u32>()?;
170 let ledger = self.ledger.read_f32()?;
171 if metadata.as_chunks::<4>().0.iter().any(|m| m[1] != 0)
172 || ledger
173 .as_chunks::<TRADING_LEDGER_WIDTH>()
174 .0
175 .iter()
176 .any(|a| a[1] != 0.0 || a[12] != 0.0 || a[15] != 0.0)
177 {
178 return Err(Error::failed_precondition(
179 "fee changes require every trading lane at reset",
180 ));
181 }
182 }
183 self.config = next;
184 Ok(())
185 }
186
187 pub fn new(
194 runtime: &'runtime Runtime,
195 config: TradingConfig,
196 series: &[TradingSeries],
197 ) -> Result<Self> {
198 Self::new_with_row_capacity(runtime, config, series, 0)
199 }
200
201 pub fn new_with_row_capacity(
206 runtime: &'runtime Runtime,
207 config: TradingConfig,
208 series: &[TradingSeries],
209 capacity: usize,
210 ) -> Result<Self> {
211 let tables = trading_tables(config, series)?;
212 let source = state::fingerprint(&tables, series)?;
213 let TradingTables {
214 mut market,
215 mut features,
216 bounds,
217 rules,
218 width,
219 market_width,
220 } = tables;
221 let rows = market.len() / market_width;
222 if capacity != 0 && capacity < rows {
223 return Err(Error::invalid_argument(
224 "trading row capacity is smaller than source rows",
225 ));
226 }
227 let capacity = capacity.max(rows);
228 if capacity
229 .checked_mul(width.max(market_width))
230 .is_none_or(|n| n > TRADING_ELEMENT_BUDGET)
231 {
232 return Err(Error::resource_exhausted(
233 "trading row capacity exceeds the 128M-element budget",
234 ));
235 }
236 market.resize(capacity * market_width, 0.);
237 features.resize(capacity * width, 0.);
238 let lanes = config.environments as usize;
239 let observation_width = (config.window as usize)
240 .checked_mul(width)
241 .and_then(|n| n.checked_add(TRADING_ACCOUNT_FEATURES))
242 .ok_or_else(|| Error::invalid_argument("trading observation overflow"))?;
243 if lanes
244 .checked_mul(observation_width)
245 .is_none_or(|n| n > TRADING_ELEMENT_BUDGET)
246 {
247 return Err(Error::resource_exhausted(
248 "trading observation exceeds the 128M-element budget",
249 ));
250 }
251
252 let spec = EnvironmentSpec::new(
253 EnvironmentSpace::continuous(
254 "observation",
255 [observation_width],
256 DType::F32,
257 f64::NEG_INFINITY,
258 f64::INFINITY,
259 )?,
260 EnvironmentSpace::discrete("action", if config.perpetual { 3 } else { 2 }, DType::I32)?,
261 EnvironmentSpace::continuous("reward", [], DType::F32, f64::NEG_INFINITY, f64::INFINITY)?,
262 EnvironmentSpace::binary("terminated", [])?,
263 EnvironmentSpace::binary("truncated", [])?,
264 )?;
265 Ok(Self {
266 runtime,
267 execution: EnvironmentExecution::new(runtime),
268 config,
269 spec,
270 market: Matrix::new_from_f32_on(
271 runtime,
272 [market.len() / market_width, market_width],
273 &market,
274 )?,
275 features: Matrix::new_from_f32_on(runtime, [features.len() / width, width], &features)?,
276 bounds: Matrix::new_from_slice_on(runtime, [lanes, 2], &bounds)?,
277 rules: Matrix::new_from_f32_on(runtime, [lanes, RULE_WIDTH], &rules)?,
278 ledger: Matrix::new_from_f32_on(
279 runtime,
280 [lanes, TRADING_LEDGER_WIDTH],
281 &vec![0.0; lanes * TRADING_LEDGER_WIDTH],
282 )?,
283 meta: Matrix::new_from_slice_on(runtime, [lanes, 4], &vec![0_u32; lanes * 4])?,
284 done: Matrix::new_from_slice_on(runtime, [lanes], &vec![0_u8; lanes])?,
285 observation: Matrix::new_from_f32_on(
286 runtime,
287 [lanes, observation_width],
288 &vec![0.0; lanes * observation_width],
289 )?,
290 width: width as u32,
291 market_width: market_width as u32,
292 pending_seed: None,
293 committed: false,
294 reset_pending: false,
295 rollback_observation: None,
296 force_end: false,
297 tables_valid: true,
298 source,
299 })
300 }
301
302 pub fn replace_series(&mut self, series: &[TradingSeries]) -> Result<()> {
308 if self.execution.has_active_recording() || self.execution.has_pending_event() {
309 return Err(Error::failed_precondition(
310 "trading table replacement requires idle execution",
311 ));
312 }
313 if self.committed
314 && self
315 .meta
316 .read::<u32>()?
317 .as_chunks::<4>()
318 .0
319 .iter()
320 .any(|m| m[1] != 0 && m[1] < self.config.horizon)
321 {
322 return Err(Error::failed_precondition(
323 "cannot replace source inside a continuing episode",
324 ));
325 }
326 let tables = trading_tables(self.config, series)?;
327 let source = state::fingerprint(&tables, series)?;
328 let TradingTables {
329 mut market,
330 mut features,
331 bounds,
332 rules,
333 width,
334 market_width,
335 } = tables;
336 if width != self.width as usize
337 || market_width != self.market_width as usize
338 || market.len() > self.market.num_elements()
339 {
340 return Err(Error::invalid_argument(
341 "replacement trading table exceeds captured capacity/width",
342 ));
343 }
344 market.resize(self.market.num_elements(), 0.);
345 features.resize(self.features.num_elements(), 0.);
346 self.runtime.checkpoint()?.wait()?;
347 self.committed = false;
348 self.tables_valid = false;
349 self.market.write_values(&market)?;
350 self.features.write_values(&features)?;
351 self.bounds.write_values(&bounds)?;
352 self.rules.write_values(&rules)?;
353 self.source = source;
354 self.tables_valid = true;
355 Ok(())
356 }
357 pub(in crate::ml) fn replay_initialized(&self) -> bool {
358 self.committed && self.tables_valid
359 }
360
361 pub(in crate::ml) fn replay_tables_valid(&self) -> bool {
362 self.tables_valid
363 }
364
365 pub(in crate::ml) fn replay_slots(&self) -> Vec<&Matrix> {
366 vec![&self.ledger, &self.meta, &self.done, &self.observation]
367 }
368
369 pub(in crate::ml) fn replay_identity(&self) -> Vec<u64> {
370 vec![
371 self.market.value_id(),
372 self.features.value_id(),
373 self.bounds.value_id(),
374 self.rules.value_id(),
375 self.ledger.value_id(),
376 self.meta.value_id(),
377 self.done.value_id(),
378 ]
379 }
380 pub(in crate::ml) fn replay_config(&self) -> TradingConfig {
381 self.config
382 }
383 pub(in crate::ml) fn replay_observation(&mut self, value: Matrix) {
384 self.observation = value;
385 self.rollback_observation = None;
386 self.reset_pending = false;
387 self.committed = true;
388 }
389
390 pub fn step_terminal(&mut self, action: &Matrix) -> Result<EnvironmentTransition> {
396 self.force_end = true;
397 let result = self.step(action);
398 self.force_end = false;
399 result
400 }
401
402 pub const fn ledger(&self) -> &Matrix {
407 &self.ledger
408 }
409
410 pub const fn metadata(&self) -> &Matrix {
412 &self.meta
413 }
414
415 pub fn check_status(&self) -> Result<()> {
421 if !self.committed
422 || self.execution.has_active_recording()
423 || self.execution.has_pending_event()
424 {
425 return Err(Error::failed_precondition(
426 "trading status requires completed submitted state",
427 ));
428 }
429 if self
430 .meta
431 .read::<u32>()?
432 .as_chunks::<4>()
433 .0
434 .iter()
435 .any(|r| r[3] != 0)
436 {
437 return Err(Error::failed_precondition(
438 "trading lane rejected action, insolvency, nonfinite arithmetic or exhausted episode counter",
439 ));
440 }
441 Ok(())
442 }
443
444 fn reset_commands(&mut self, only_done: bool) -> Result<()> {
445 self.reset_commands_impl(only_done, None)
446 }
447 pub(in crate::ml) fn reset_replay_commands(
448 &mut self,
449 only_done: bool,
450 cursor: &Matrix,
451 ) -> Result<()> {
452 self.reset_commands_impl(only_done, Some(cursor))
453 }
454 fn reset_commands_impl(&mut self, only_done: bool, cursor: Option<&Matrix>) -> Result<()> {
455 if !self.tables_valid {
456 return Err(Error::failed_precondition(
457 "trading tables require a successful replacement",
458 ));
459 }
460 if only_done && !self.committed && !self.reset_pending {
461 return Err(Error::failed_precondition(
462 "trading requires full reset after construction/cancellation",
463 ));
464 }
465 if self.rollback_observation.is_none() {
466 self.rollback_observation = Some(self.observation.clone());
467 }
468 if cursor.is_none() {
469 self.observation = matrix::copy(&self.observation)?;
470 }
471 let seed = self.pending_seed.unwrap_or(self.config.seed);
472 let mut inputs = vec![
473 &self.market,
474 &self.features,
475 &self.bounds,
476 &self.ledger,
477 &self.meta,
478 &self.done,
479 &self.observation,
480 ];
481 let mut buffers = vec![
482 BufferBinding::read(self.market.storage()),
483 BufferBinding::read(self.features.storage()),
484 BufferBinding::read(self.bounds.storage()),
485 BufferBinding::read_write(self.ledger.storage()),
486 BufferBinding::read_write(self.meta.storage()),
487 BufferBinding::read_write(self.done.storage()),
488 BufferBinding::read_write(self.observation.storage()),
489 ];
490 let mut pushes = vec![
491 PushConstant::U32(self.config.environments),
492 PushConstant::U32(self.config.window),
493 PushConstant::U32(self.width),
494 PushConstant::U32(self.config.horizon),
495 PushConstant::U32(seed as u32),
496 PushConstant::U32((seed >> 32) as u32),
497 PushConstant::U32(u32::from(only_done)),
498 PushConstant::F32(self.config.capital),
499 PushConstant::U32(self.market_width),
500 ];
501 if let Some(cursor) = cursor {
502 inputs.insert(3, cursor);
503 buffers.push(BufferBinding::read(cursor.storage()));
504 pushes.drain(4..6);
505 }
506 let mut attributes = vec![OpAttribute::UnsignedInteger {
507 name: "config_identity".into(),
508 value: self.config.identity(),
509 }];
510 if cursor.is_none() {
511 attributes.push(OpAttribute::UnsignedInteger {
512 name: "seed".into(),
513 value: seed,
514 });
515 }
516 attributes.push(OpAttribute::Boolean {
517 name: "only_completed".into(),
518 value: only_done,
519 });
520
521 self.market.runtime().record_semantic(
522 ComputeDispatch {
523 kernel: if cursor.is_some() {
524 KernelId::MlTradingResetCursorF32
525 } else {
526 KernelId::MlTradingResetF32
527 },
528 buffers: &buffers,
529 push_constants: &pushes,
530 workgroups: KernelId::MlTradingResetF32.linear_workgroups(self.config.environments),
531 indirect: None,
532 },
533 SemanticDispatch {
534 contract: if cursor.is_some() {
535 crate::core::operation::ml::TRADING_RESET_CURSOR
536 } else {
537 crate::core::operation::ml::TRADING_RESET
538 },
539 inputs: &inputs,
540 outputs: &[&self.ledger, &self.meta, &self.done, &self.observation],
541 attributes: &attributes,
542 },
543 )?;
544 if !only_done {
545 self.reset_pending = true;
546 }
547 Ok(())
548 }
549 pub(in crate::ml) fn step_replay_commands(
550 &mut self,
551 action: &Matrix,
552 cursor: &Matrix,
553 ) -> Result<EnvironmentTransition> {
554 self.step_commands(action, Some(cursor))
555 }
556 fn step_commands(
557 &mut self,
558 action: &Matrix,
559 cursor: Option<&Matrix>,
560 ) -> Result<EnvironmentTransition> {
561 self
562 .spec
563 .validate_action(action, self.config.environments)?;
564 if !self.committed && !self.reset_pending {
565 return Err(Error::failed_precondition("trading step requires reset"));
566 }
567 if !self.runtime.owns_matrix(action) {
568 return Err(Error::invalid_argument(
569 "trading action belongs to another Runtime",
570 ));
571 }
572 let before = if cursor.is_some() {
574 self.observation.clone()
575 } else {
576 matrix::copy(&self.observation)?
577 };
578 let lanes = self.config.environments as usize;
579 let next = Matrix::allocate(
580 self.market.runtime(),
581 self.observation.shape().to_vec(),
582 self.observation.num_elements(),
583 DType::F32,
584 )?;
585 let reward = Matrix::allocate(self.market.runtime(), vec![lanes], lanes, DType::F32)?;
586 let terminated = Matrix::new_from_slice_on(self.runtime, [lanes], &vec![0_u8; lanes])?;
587 let truncated = Matrix::new_from_slice_on(self.runtime, [lanes], &vec![0_u8; lanes])?;
588 let mut buffers = vec![
589 BufferBinding::read(self.market.storage()),
590 BufferBinding::read(self.features.storage()),
591 BufferBinding::read(self.bounds.storage()),
592 BufferBinding::read(action.storage()),
593 BufferBinding::read_write(self.ledger.storage()),
594 BufferBinding::read_write(self.meta.storage()),
595 BufferBinding::read_write(self.done.storage()),
596 BufferBinding::write(next.storage()),
597 BufferBinding::write(reward.storage()),
598 BufferBinding::write(terminated.storage()),
599 BufferBinding::write(truncated.storage()),
600 ];
601 let c = self.config;
602 let mut pushes = vec![
603 PushConstant::U32(c.environments),
604 PushConstant::U32(c.window),
605 PushConstant::U32(self.width),
606 PushConstant::U32(c.horizon),
607 PushConstant::U32(u32::from(c.perpetual)),
608 PushConstant::U32(u32::from(c.liquidate_at_horizon)),
609 PushConstant::U32(u32::from(self.force_end)),
610 PushConstant::F32(c.capital),
611 PushConstant::F32(c.exposure),
612 PushConstant::F32(c.taker_fee),
613 PushConstant::F32((c.slippage_bps + c.spread_bps * 0.5) / 10000.0),
614 PushConstant::F32(c.max_drawdown),
615 PushConstant::U32(self.market_width),
616 PushConstant::F32(c.slippage_bps / 10000.0),
617 PushConstant::F32(c.maker_fee),
618 PushConstant::U32(c.maker_window_steps),
619 PushConstant::U32(c.maker_requotes),
620 ];
621 if let Some(cursor) = cursor {
622 buffers.push(BufferBinding::read(cursor.storage()));
623 pushes.remove(6);
624 }
625 buffers.push(BufferBinding::read(self.rules.storage()));
626 let mut inputs = vec![
627 &self.market,
628 &self.features,
629 &self.bounds,
630 action,
631 &self.rules,
632 &self.ledger,
633 &self.meta,
634 &self.done,
635 &next,
636 &reward,
637 &terminated,
638 &truncated,
639 ];
640 if let Some(cursor) = cursor {
641 inputs.insert(4, cursor);
642 }
643 let mut attributes = vec![OpAttribute::UnsignedInteger {
644 name: "config_identity".into(),
645 value: c.identity(),
646 }];
647 if cursor.is_none() {
648 attributes.push(OpAttribute::Boolean {
649 name: "force_end".into(),
650 value: self.force_end,
651 });
652 }
653
654 self.market.runtime().record_semantic(
655 ComputeDispatch {
656 kernel: if cursor.is_some() {
657 KernelId::MlTradingStepCursorF32
658 } else {
659 KernelId::MlTradingStepF32
660 },
661 buffers: &buffers,
662 push_constants: &pushes,
663 workgroups: KernelId::MlTradingStepF32.linear_workgroups(c.environments),
664 indirect: None,
665 },
666 SemanticDispatch {
667 contract: if cursor.is_some() {
668 crate::core::operation::ml::TRADING_STEP_CURSOR
669 } else {
670 crate::core::operation::ml::TRADING_STEP
671 },
672 inputs: &inputs,
673 outputs: &[
674 &self.ledger,
675 &self.meta,
676 &self.done,
677 &next,
678 &reward,
679 &terminated,
680 &truncated,
681 ],
682 attributes: &attributes,
683 },
684 )?;
685 if self.rollback_observation.is_none() {
686 self.rollback_observation = Some(self.observation.clone());
687 }
688 self.observation = next.clone();
689 Ok(EnvironmentTransition::new(
690 before, next, reward, terminated, truncated,
691 ))
692 }
693}
694
695impl Environment for TradingEnvironment<'_> {
696 fn runtime(&self) -> &Runtime {
697 self.runtime
698 }
699
700 fn spec(&self) -> &EnvironmentSpec {
701 &self.spec
702 }
703
704 fn environments(&self) -> u32 {
705 self.config.environments
706 }
707
708 fn observation(&self) -> &Matrix {
709 &self.observation
710 }
711
712 fn execution(&self) -> &EnvironmentExecution {
713 &self.execution
714 }
715
716 fn execution_mut(&mut self) -> &mut EnvironmentExecution {
717 &mut self.execution
718 }
719
720 fn record_reset(&mut self, seed: u64) -> Result<()> {
721 self.pending_seed = Some(seed);
722 self.reset_commands(false)
723 }
724
725 fn record_reset_completed(&mut self) -> Result<()> {
726 self.reset_commands(true)
727 }
728
729 fn commit_recorded_state(&mut self) {
730 if let Some(seed) = self.pending_seed.take() {
731 self.config.seed = seed;
732 }
733 self.rollback_observation = None;
734 self.committed |= self.reset_pending;
735 self.reset_pending = false;
736 }
737
738 fn rollback_recorded_state(&mut self) {
739 if let Some(observation) = self.rollback_observation.take() {
740 self.observation = observation;
741 }
742 self.pending_seed = None;
743 self.reset_pending = false;
744 }
745
746 fn record_step(&mut self, action: &Matrix) -> Result<EnvironmentTransition> {
747 self.step_commands(action, None)
748 }
749}
750
751struct TradingTables {
752 market: Vec<f32>,
753 features: Vec<f32>,
754 bounds: Vec<u32>,
755 rules: Vec<f32>,
756 width: usize,
757 market_width: usize,
758}
759fn trading_tables(config: TradingConfig, series: &[TradingSeries]) -> Result<TradingTables> {
760 config.validate()?;
761 if series.is_empty() || series.len() > config.environments as usize {
762 return Err(Error::invalid_argument(
763 "trading requires at least one lane per contiguous segment",
764 ));
765 }
766 let width = series[0].feature_width;
767 if width == 0 {
770 return Err(Error::invalid_argument("invalid trading feature width"));
771 }
772 let market_width = if series.iter().any(|s| !s.books.is_empty()) {
773 BOOK_MARKET_WIDTH
774 } else {
775 3
776 };
777 if market_width != 3 && series.iter().any(|s| s.books.is_empty()) {
778 return Err(Error::invalid_argument(
779 "mixed legacy/book execution series require explicit books for every series",
780 ));
781 }
782 if config.maker_window_steps > 0 && market_width == 3 {
783 return Err(Error::invalid_argument(
784 "maker execution requires per-row order books",
785 ));
786 }
787 let mut market = Vec::new();
788 let mut features = Vec::new();
789 let mut segments = Vec::new();
790 for s in series {
791 s.execution.validate()?;
792 let n = s.market.len();
793 if !config.perpetual && (s.execution.leverage != 1.0 || !s.execution.margin_tiers.is_empty()) {
794 return Err(Error::invalid_argument(
795 "Spot cannot use leveraged margin rules",
796 ));
797 }
798 if !s.books.is_empty() && s.books.len() != n {
799 return Err(Error::invalid_argument(
800 "trading book row coverage mismatch",
801 ));
802 }
803 for book in &s.books {
804 book.validate()?;
805 }
806 if s.feature_width != width
807 || s.timestamps.len() != n
808 || n < config.window as usize + config.horizon as usize
809 || n.checked_mul(width) != Some(s.features.len())
810 || s.features.iter().any(|x| !x.is_finite())
811 || s.market.iter().any(|x| {
812 x.iter().any(|v| !v.is_finite())
813 || !(1e-12..=1e12).contains(&x[0])
814 || !(1e-12..=1e12).contains(&x[1])
815 || (!config.perpetual && x[2] != 0.0)
816 }) {
817 return Err(Error::invalid_argument(
818 "invalid trading series shape, prices, funding or features",
819 ));
820 }
821 let interval = s.timestamps[1]
822 .checked_sub(s.timestamps[0])
823 .filter(|d| *d > 0)
824 .ok_or_else(|| Error::invalid_argument("invalid trading time interval"))?;
825 if s
826 .timestamps
827 .windows(2)
828 .any(|w| w[1].checked_sub(w[0]) != Some(interval))
829 {
830 return Err(Error::invalid_argument(
831 "trading episode crosses a timestamp gap",
832 ));
833 }
834 let offset = market.len() / market_width;
835 let end = offset
836 .checked_add(n)
837 .ok_or_else(|| Error::invalid_argument("trading row extent overflow"))?;
838 if end
839 .checked_mul(width.max(market_width))
840 .is_none_or(|x| x > TRADING_ELEMENT_BUDGET)
841 {
842 return Err(Error::resource_exhausted(
843 "trading upload exceeds the 128M-element budget",
844 ));
845 }
846 segments.push([
847 u32::try_from(offset + config.window as usize - 1)
848 .map_err(|_| Error::invalid_argument("trading offset overflow"))?,
849 u32::try_from(end - 1).map_err(|_| Error::invalid_argument("trading end overflow"))?,
850 ]);
851 if s.books.is_empty() {
852 market.extend(s.market.iter().flatten().copied());
853 } else {
854 for (row, book) in s.market.iter().zip(&s.books) {
855 book.append(row, &mut market);
856 }
857 }
858 features.extend_from_slice(&s.features);
859 }
860 let bounds = (0..config.environments as usize)
861 .flat_map(|i| segments[i % segments.len()])
862 .collect();
863 let mut rules = Vec::with_capacity(config.environments as usize * RULE_WIDTH);
864 for i in 0..config.environments as usize {
865 series[i % series.len()].execution.append(&mut rules);
866 }
867 Ok(TradingTables {
868 market,
869 features,
870 bounds,
871 rules,
872 width,
873 market_width,
874 })
875}