ccxt_common/order_router.rs
1// Native Rust — hand-written client for the CCXT order-router service.
2//
3// This is the SIXTH port of a class that is hand-written, not transpiled: the
4// TypeScript reference lives in `ts/src/base/OrderRouter.ts`, and Python, PHP,
5// C# and Go carry line-for-line siblings. They are held together by one shared
6// fixture, `ts/src/test/base/fixtures/orderRouter.json`, which every port runs.
7// A change to any of them that this port does not match fails that fixture, in
8// this language, which is the entire point of writing it out again rather than
9// generating it.
10//
11// Two things about Rust make the port read differently from its siblings while
12// meaning the same thing, and both are load-bearing:
13//
14// * The other five pass dictionaries of `any`. Here that is `Value`, which is
15// the same shape (`Value::Dict(Arc<IndexMap<String, Value>>)`) — so the
16// accessors below are genuine equivalents of `numberAt`/`stringAt`/… and
17// not a re-design.
18// * The other five throw. Here the fallible methods return
19// `Result<_, ExchangeError>`. `ExchangeError::kind` carries the same class
20// names the other ports throw, so `is("NetworkError")` answers the same
21// question `isOutcomeUnknownError` asks there.
22
23use std::borrow::Cow;
24use std::collections::BTreeSet;
25use std::sync::Arc;
26
27use crate::error::ExchangeError;
28use crate::value::{HashMap, Value};
29
30/// Result of a fallible router operation. The error's `kind` matches the
31/// exception class the other five ports raise for the same condition.
32pub type RouterResult<T> = std::result::Result<T, ExchangeError>;
33
34fn arguments_required(message: &str) -> ExchangeError {
35 ExchangeError::new("ArgumentsRequired", message)
36}
37
38fn bad_request(message: &str) -> ExchangeError {
39 ExchangeError::new("BadRequest", message)
40}
41
42fn exchange_error(message: &str) -> ExchangeError {
43 ExchangeError::new("ExchangeError", message)
44}
45
46fn insufficient_funds(message: &str) -> ExchangeError {
47 ExchangeError::new("InsufficientFunds", message)
48}
49
50/// NO_CAP is the default: this class does not decide how much of your money you
51/// may trade. `maxNotionalUsd` is an OPT-IN guardrail — set it and it is honoured
52/// exactly, at whatever value you choose; leave it unset and no notional check
53/// runs at all.
54///
55/// It used to be a hard 25 USD ceiling that could be lowered but never raised.
56/// That number came from CLAUDE.md §5.5, which governs THIS REPOSITORY'S live
57/// tests against real exchanges — not the people using the library. A client that
58/// refuses a 30 USD order because its own test suite is cautious is broken as a
59/// product.
60pub const NO_CAP: f64 = 0.0;
61/// Default distance from the expected price at which the limit is placed.
62pub const DEFAULT_SLIPPAGE_BPS: f64 = 25.0;
63/// Default shortfall ratio at which `reconcile_execution_step` halts.
64pub const DEFAULT_RECONCILE_TOLERANCE: f64 = 0.02;
65/// How long `retryFailedSteps` waits before re-placing a step the venue rejected.
66/// A second is the shortest delay that lets a transient cause clear (a rate limit
67/// window, a momentary balance lag) without turning a retry budget into a burst
68/// against a venue that just said no.
69pub const DEFAULT_RETRY_DELAY_MS: f64 = 1000.0;
70/// The float-equality epsilon this class compares with. Not a business
71/// tolerance — that is DEFAULT_RECONCILE_TOLERANCE. This one exists so that
72/// "the fill matches the request" and "the value sits on the precision grid"
73/// survive the last bits of floating-point arithmetic, and it must be the same
74/// number in all six ports or a violation fires in one language and not another.
75pub const TOLERANCE: f64 = 1e-9;
76const DEFAULT_BASE_URL: &str = "https://docs.ccxt.com/router/api";
77
78/// Human-readable text for each safety violation code. Carried in the violation
79/// record itself so a caller logging one does not have to keep its own copy of
80/// this table — and so all six ports emit the same sentence for the same code.
81fn violation_message(code: &str) -> &'static str {
82 match code {
83 "empty_plan" => "the plan contains no steps",
84 "route_unroutable" => "the route carries an unroutableReason and must not be executed",
85 "partial_fill" => "the route does not fill completely at the requested size",
86 "unknown_symbol" => "the symbol is not listed on that venue",
87 "market_mismatch" => "the venue market trades a different pair than the route hop says it does",
88 "invalid_step" => "the step has a non-positive amount or price, or a side that is neither buy nor sell",
89 "amount_below_minimum" => "the amount is below the market minimum",
90 "amount_above_maximum" => "the amount is above the market maximum",
91 "cost_below_minimum" => "the notional is below the market minimum cost",
92 "price_out_of_range" => "the limit price falls outside the market price limits",
93 "notional_unvaluable" => "the step cannot be valued in USD, so the notional cap cannot be enforced",
94 "notional_exceeds_cap" => "the notional exceeds the per-trade USD cap",
95 "amount_precision" => "the amount does not sit on the market amount precision",
96 "price_precision" => "the limit price does not sit on the market price precision",
97 // The TypeScript reads this table with stringAt(.., code, code): an
98 // unknown code falls back to the code itself rather than to empty.
99 other => {
100 // `other` is a &str borrowed from the caller, but this function
101 // returns 'static. Every code the class emits is in the table above,
102 // so the fallback only fires for a code that does not exist yet.
103 let _ = other;
104 "unknown_violation"
105 }
106 }
107}
108const DEFAULT_TIMEOUT_MS: f64 = 30000.0;
109/// The router accepts at most this many balance entries; the rest are dropped
110/// smallest-first and reported.
111const MAX_BALANCE_ENTRIES: usize = 64;
112/// And at most this many characters in the rendered value.
113const MAX_BALANCE_CHARS: usize = 4096;
114
115/// How many executed plan ids the in-process idempotency ledger keeps. 1024 is chosen to
116/// be far more executions than any one process performs in the window where a duplicate is
117/// plausible (a retry loop, an operator re-running a plan, a redelivered message), while
118/// bounding the ledger to a few tens of kilobytes so a router held open for the life of a
119/// daemon cannot grow without limit.
120///
121/// THE TRADEOFF IS REAL AND IS NOT HIDDEN: eviction WEAKENS the guarantee. Once a plan id
122/// has been pushed out by 1024 newer executions, re-executing that plan is no longer
123/// refused in-process — it will be placed again, orders and all. The guard is therefore
124/// "recent duplicates are refused", not "duplicates are impossible". A process that needs
125/// the strong promise across restarts or beyond this window needs the durable ledger the
126/// Known gaps entry calls for; until then, callers whose plans must never re-execute should
127/// key idempotency at the venue themselves (a clientOrderId passed in options.orderParams, on
128/// venues that honour one) rather than rely on this instance's memory.
129pub const MAX_EXECUTED_PLAN_IDS: usize = 1024;
130
131/// The bounded re-execution ledger: a FIFO queue of plan ids plus a set that answers
132/// membership in O(1). Both are private to this type so they can never fall out of step.
133#[derive(Debug)]
134pub struct ExecutedPlanLedger {
135 order: std::collections::VecDeque<String>,
136 seen: std::collections::HashSet<String>,
137}
138
139impl ExecutedPlanLedger {
140 pub fn new() -> Self {
141 ExecutedPlanLedger {
142 order: std::collections::VecDeque::new(),
143 seen: std::collections::HashSet::new(),
144 }
145 }
146
147 /// A hash lookup, not a scan: the ledger is capped but still up to
148 /// MAX_EXECUTED_PLAN_IDS long, and this runs on every live execution.
149 pub fn contains(&self, plan_id: &str) -> bool {
150 self.seen.contains(plan_id)
151 }
152
153 pub fn len(&self) -> usize {
154 self.order.len()
155 }
156
157 pub fn is_empty(&self) -> bool {
158 self.order.is_empty()
159 }
160
161 /// The id at `index` in insertion order, oldest first.
162 pub fn at(&self, index: usize) -> Option<&String> {
163 self.order.get(index)
164 }
165
166 /// Records one plan id, evicting the oldest entry when the cap is reached.
167 pub fn record(&mut self, plan_id: String) {
168 if self.seen.contains(&plan_id) {
169 // Already recorded; re-recording it would move it in the FIFO order and let
170 // a repeatedly re-executed plan keep other ids alive or evict them out of turn.
171 return;
172 }
173 self.seen.insert(plan_id.clone());
174 self.order.push_back(plan_id);
175 while self.order.len() > MAX_EXECUTED_PLAN_IDS {
176 // FIFO: the OLDEST execution is the one whose duplicate is least likely still
177 // in flight. Evicting it drops the refusal for that plan — see the comment on
178 // MAX_EXECUTED_PLAN_IDS; this is a bounded memory promise, not a stronger
179 // idempotency one.
180 if let Some(evicted) = self.order.pop_front() {
181 self.seen.remove(&evicted);
182 }
183 }
184 }
185}
186
187impl Default for ExecutedPlanLedger {
188 fn default() -> Self {
189 Self::new()
190 }
191}
192
193/// The shape of the `onStep` hook: it is handed one event describing a finished
194/// step and returns `"halt"` to stop the route. SYNCHRONOUS by design — it sits
195/// between orders on the money path, so do no network I/O in it.
196///
197/// WHY THIS IS A FIELD AND NOT AN OPTIONS KEY, unlike the other five ports.
198/// In TypeScript, Python, PHP, C# and Go the hook travels inside `options`,
199/// because in those languages a dictionary value can be a function. Rust's
200/// `options` is a `Value`, and `Value` is a closed, JSON-shaped enum that
201/// derives `Debug`, `Clone` and `PartialEq` and answers `to_json` — none of
202/// which a closure can. Adding a `Value::Fn` variant would mean answering
203/// "what does it mean for two closures to be equal, and how does one
204/// serialise" for every existing Value site in the crate, which is a redesign
205/// of the value model to carry an observability callback. So the callback comes
206/// in through the ONE side channel that can hold it — a field on the router,
207/// set by `set_on_step` — and `call_on_step` still takes `options` so the six
208/// implementations read line for line.
209pub type OnStepHook = Arc<dyn Fn(&Value) -> String + Send + Sync>;
210
211/// A client for the CCXT order-router service.
212pub struct OrderRouter {
213 api_key: String,
214 /// Sent as the `User-Agent` header when non-empty, so the router service can
215 /// attribute traffic to the integration that made it.
216 user_agent: String,
217 base_url: String,
218 timeout_ms: f64,
219 max_notional_usd: f64,
220 /// The only clock this class reads. `None` means the real wall clock; a
221 /// test pins time by setting it. A field rather than an overridable method
222 /// because `OrderRouter` is a concrete struct, not a trait.
223 now_ms_override: Option<f64>,
224 /// In-process idempotency ledger: the identity of every plan this instance
225 /// has already executed live. Behind a mutex because `execute` takes `&self`.
226 /// TWO structures for one ledger, in every port: a FIFO deque that fixes the
227 /// eviction order, and a `HashSet` so the membership test is a hash lookup
228 /// rather than a scan whose cost grows with the ledger. They live under ONE
229 /// mutex because they are written and evicted together and must never disagree.
230 executed_plan_ids: std::sync::Mutex<ExecutedPlanLedger>,
231 /// The caller's `onStep` hook, or `None`. See `OnStepHook` for why this is a
232 /// field in this port and an options key in the other five. `execute` takes
233 /// `&self`, so this is only ever read, never written, during a run.
234 on_step: Option<OnStepHook>,
235
236 // The venues this router trades through, held once instead of passed to every call.
237 // Rust diverges from the other five ports HERE, and for the same reason it diverges
238 // on the onStep hook: `Value` is a closed enum and cannot carry a `Box<dyn RouterVenue>`,
239 // so they cannot arrive through the constructor config. The BEHAVIOUR is identical —
240 // fetch_route filters and funds on them, execute falls back to them — only the
241 // installation is a setter.
242 venues: std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
243
244 // The rendered balances string for `venues`, read once and reused. fetch_route is ONE
245 // HTTP request and must stay that way. Placing an order is what makes balances wrong,
246 // so a live execute drops it. A Mutex because fetch_route takes &self.
247 balances_cache: std::sync::Mutex<Option<String>>,
248 // bumped by every invalidation, so a wallet read that was already in flight when the
249 // cache was dropped cannot store its now-obsolete snapshot on the way back
250 balances_generation: std::sync::atomic::AtomicU64,
251
252 // Whether this router manages balances at all. TWO decisions used to ride on `venues`:
253 // where you can trade, and what you hold. The first is a filter - free, and it cannot go
254 // stale. The second costs an authenticated call per venue and made one bad key enough to
255 // kill a quote. So the filter is always on and the wallet reads are a mode you ask for.
256 track_balances: bool,
257}
258
259// ---------------------------------------------------------------------------
260// container accessors
261//
262// Every port has these; they exist so the six implementations read line for
263// line, and so a missing key is never a language-specific crash.
264// ---------------------------------------------------------------------------
265
266/// Plain container read: the field if the container is a dict and the field is
267/// present and not null, `None` otherwise. Deliberately NOT `get_value_k`, which
268/// also routes shared-order-book meta keys and live-client lookups — this class
269/// reads inert JSON structures, and picking up those side effects would make the
270/// accessors mean something the other five ports' accessors do not.
271fn field<'a>(container: &'a Value, key: &str) -> Option<&'a Value> {
272 match container.as_map().and_then(|map| map.get(key)) {
273 Some(Value::Null) | None => None,
274 found => found,
275 }
276}
277
278impl OrderRouter {
279 /// The price a step is sent at, derived from `expectedPrice` when the
280 /// caller gave no `limitPrice`. 0 only when the step has neither field.
281 ///
282 /// `build_execution_plan` always sets `limitPrice`, but a HAND-BUILT plan
283 /// need not: the manual documents it as optional, and the "execute your own
284 /// plans" path is the whole point of `execute` taking a plan rather than a
285 /// route. Reading it as 0 made every such plan fail three different ways —
286 /// a blocking `price_out_of_range` from `check_execution_plan_safety`, a
287 /// `rounded_to_zero` before any strategy branch in `place_step`, and a
288 /// buy-side balance requirement of `amount * 0` — so the documented example
289 /// could not place one order. `expectedPrice` is the honest fallback: it is
290 /// what the caller says the step is worth, and it is already guaranteed
291 /// positive by the `invalid_step` guard. A caller wanting a tighter or
292 /// looser bound sets `limitPrice` explicitly.
293 pub fn step_limit_price(&self, step: &Value) -> f64 {
294 let limit_price = self.number_at(step, "limitPrice", 0.0);
295 if limit_price > 0.0 {
296 return limit_price;
297 }
298 self.number_at(step, "expectedPrice", 0.0)
299 }
300
301 /// The step's quote-side value, derived from `amount` and `expectedPrice`
302 /// when absent.
303 ///
304 /// Same reasoning as `step_limit_price`, and the same formula
305 /// `build_execution_plan` uses. Read as 0, a hand-built plan tripped the
306 /// BLOCKING `cost_below_minimum` on every market declaring a minimum cost.
307 pub fn step_notional_quote(&self, step: &Value) -> f64 {
308 let notional_quote = self.number_at(step, "notionalQuote", 0.0);
309 if notional_quote > 0.0 {
310 return notional_quote;
311 }
312 self.number_at(step, "amount", 0.0) * self.number_at(step, "expectedPrice", 0.0)
313 }
314
315 /// Reads a numeric field, with a default for missing, null and unparseable
316 /// values.
317 pub fn number_at(&self, container: &Value, key: &str, default_value: f64) -> f64 {
318 Self::number_of(field(container, key), default_value)
319 }
320
321 fn number_of(value: Option<&Value>, default_value: f64) -> f64 {
322 match value {
323 None | Some(Value::Null) => default_value,
324 // NaN and the infinities are not numbers this class will act on. An
325 // infinite tolerance silently disables the halt verdict and an
326 // infinite rate silently disables the cap, and "the default" is the
327 // only answer six languages can agree on for either.
328 Some(Value::Int(n)) => {
329 let as_float = *n as f64;
330 if Self::is_finite_number(as_float) { as_float } else { default_value }
331 }
332 Some(Value::Float(n)) => {
333 if Self::is_finite_number(*n) { *n } else { default_value }
334 }
335 Some(Value::Str(text)) => Self::parse_number_text(text, default_value),
336 _ => default_value,
337 }
338 }
339
340 /// Reports whether a double is a real number, i.e. neither NaN nor an
341 /// infinity.
342 pub fn is_finite_number(value: f64) -> bool {
343 // DIVERGENCE, and the only one in this method. The other five ports
344 // write `value !== value`, which their comment calls "the one NaN test
345 // that needs no library" — in Rust that is clippy::eq_op, denied by
346 // default, and CI compiles with it fatal. `is_nan()` is the identical
347 // predicate; only the spelling differs.
348 if value.is_nan() {
349 return false;
350 }
351 if value > 1.7976931348623157e308 || value < -1.7976931348623157e308 {
352 return false;
353 }
354 true
355 }
356
357 /// Reads the leading numeric prefix of a string exactly as JavaScript's
358 /// `parseFloat` does, returning the default when there is not one or when
359 /// the result is not finite.
360 pub fn parse_number(&self, text: &str, default_value: f64) -> f64 {
361 Self::parse_number_text(text, default_value)
362 }
363
364 fn parse_number_text(text: &str, default_value: f64) -> f64 {
365 // Hand-rolled rather than delegated to the language's own parser,
366 // because every language's own parser disagrees with the others
367 // somewhere: Python reads '1_000' as 1000 and '1,234.5' not at all, PHP
368 // and Go read '0x10' as 0 only by accident of their regex, C# trims
369 // Unicode whitespace JavaScript does not, and Rust's own `f64::from_str`
370 // accepts "inf"/"NaN" and rejects any trailing text at all. The grammar
371 // below is JavaScript's StrDecimalLiteral prefix over the ASCII
372 // whitespace set, and it is the SAME twenty lines in all six ports.
373 //
374 // Indexed over BYTES, not chars: every character the grammar accepts is
375 // ASCII, and a multi-byte character can only ever end the scan.
376 let bytes = text.as_bytes();
377 let mut cursor = 0usize;
378 while cursor < bytes.len() && Self::is_router_space(bytes[cursor]) {
379 cursor += 1;
380 }
381 let start = cursor;
382 if cursor < bytes.len() && (bytes[cursor] == b'+' || bytes[cursor] == b'-') {
383 cursor += 1;
384 }
385 let mut digits = 0usize;
386 while cursor < bytes.len() && bytes[cursor].is_ascii_digit() {
387 cursor += 1;
388 digits += 1;
389 }
390 if cursor < bytes.len() && bytes[cursor] == b'.' {
391 cursor += 1;
392 while cursor < bytes.len() && bytes[cursor].is_ascii_digit() {
393 cursor += 1;
394 digits += 1;
395 }
396 }
397 if digits == 0 {
398 // 'Infinity', 'inf', 'NaN', '' and '٠١' all land here, in all six.
399 return default_value;
400 }
401 let mut end = cursor;
402 if cursor < bytes.len() && (bytes[cursor] == b'e' || bytes[cursor] == b'E') {
403 let mut exponent = cursor + 1;
404 if exponent < bytes.len() && (bytes[exponent] == b'+' || bytes[exponent] == b'-') {
405 exponent += 1;
406 }
407 let mut exponent_digits = 0usize;
408 while exponent < bytes.len() && bytes[exponent].is_ascii_digit() {
409 exponent += 1;
410 exponent_digits += 1;
411 }
412 if exponent_digits > 0 {
413 // A trailing 'e' with no digits is not part of the number: JS
414 // reads '1e' as 1, and so does every port here.
415 end = exponent;
416 }
417 }
418 let slice = &text[start..end];
419 match slice.parse::<f64>() {
420 // '1e400' overflows to an infinity, which is not a number the cap or
421 // the tolerance may be built out of.
422 Ok(parsed) if Self::is_finite_number(parsed) => parsed,
423 _ => default_value,
424 }
425 }
426
427 /// Reports whether a byte is one of the six ASCII spaces the number grammar
428 /// skips.
429 fn is_router_space(character: u8) -> bool {
430 // Deliberately NOT the language's own is_whitespace: Python, PHP, C#,
431 // Go and Rust each draw the Unicode line in a different place, and a
432 // non-breaking space that parses in one language and not the others is
433 // drift.
434 character == b' '
435 || character == b'\t'
436 || character == b'\n'
437 || character == b'\r'
438 || character == 0x0c
439 || character == 0x0b
440 }
441
442 /// Reads a string field, with a default for missing and null values.
443 pub fn string_at(&self, container: &Value, key: &str, default_value: &str) -> String {
444 match field(container, key) {
445 Some(Value::Str(text)) => text.to_string(),
446 _ => default_value.to_string(),
447 }
448 }
449
450 /// Reads a boolean field, with a default for missing and null values.
451 /// Whether the key holds the boolean `true` and nothing else. A config that
452 /// stringifies its booleans must not silently stop trading, so `"true"` is NOT true here.
453 pub fn is_exactly_true(&self, container: &Value, key: &str) -> bool {
454 matches!(field(container, key), Some(Value::Bool(true)))
455 }
456
457 pub fn bool_at(&self, container: &Value, key: &str, default_value: bool) -> bool {
458 match field(container, key) {
459 Some(Value::Bool(flag)) => *flag,
460 _ => default_value,
461 }
462 }
463
464 /// Reads an array field, returning an empty vector when absent. Never None,
465 /// for the same reason `listAt` never returns undefined.
466 pub fn list_at(&self, container: &Value, key: &str) -> Vec<Value> {
467 match field(container, key) {
468 Some(Value::Arr(items)) => items.as_ref().clone(),
469 _ => Vec::new(),
470 }
471 }
472
473 /// Reads a nested dictionary, returning an empty one when absent.
474 pub fn dict_at(&self, container: &Value, key: &str) -> Value {
475 match field(container, key) {
476 Some(Value::Dict(map)) => Value::Dict(Arc::clone(map)),
477 _ => Value::Map(HashMap::new()),
478 }
479 }
480
481 /// Formats a double as decimal text with no exponent, so that six languages
482 /// produce the same string.
483 pub fn format_number(&self, value: f64) -> RouterResult<String> {
484 // JavaScript prints 1e-7 where Python prints 1e-07 and Go prints 1e-07;
485 // a fixed 12-decimal rendering with the trailing zeros trimmed is the
486 // one spelling all six languages agree on for the magnitudes a balance
487 // or an amount can take.
488 if !Self::is_finite_number(value) {
489 return Ok("0".to_string());
490 }
491 if value.abs() >= 1e18 {
492 // JavaScript's toFixed switches to exponent notation at 1e21 while
493 // the other languages never do. Rather than let one language send a
494 // different string than the others, refuse — loudly, and at a
495 // magnitude no real amount reaches.
496 return Err(bad_request(
497 "OrderRouter: a number this large cannot be rendered identically in all six languages",
498 ));
499 }
500 let mut text = Self::to_fixed_12(value);
501 if text.contains('.') {
502 while text.ends_with('0') {
503 text.pop();
504 }
505 if text.ends_with('.') {
506 text.pop();
507 }
508 }
509 if text.is_empty() || text == "-" || text == "-0" {
510 return Ok("0".to_string());
511 }
512 Ok(text)
513 }
514
515 /// Renders a finite f64 with exactly twelve decimals, from the exact binary
516 /// value and under JavaScript's toFixed tie rule.
517 ///
518 /// The reference is TypeScript, and TypeScript's toFixed is ECMA-262's: the
519 /// sign is stripped BEFORE the digits are chosen, so a tie rounds AWAY FROM
520 /// ZERO on the magnitude and (-0.0001220703125).toFixed(12) is
521 /// -0.000122070313, not -...312. Rust's `{:.12}` rounds half to EVEN and
522 /// would answer ...312, so the balances query string this feeds would differ
523 /// per language on every value landing exactly on a half tick — 2^-13
524 /// included.
525 ///
526 /// `{:.53}` is EXACT for every double whose expansion reaches the twelfth
527 /// decimal: a double is m * 2^-k and its expansion terminates at digit k, so
528 /// k <= 53 (|value| >= 2^-53) renders with no rounding at all, and anything
529 /// smaller is below 1e-16 — its digits 13 and 14 are both 0, so no carry
530 /// from digit 53 can reach the digit this rounds on.
531 fn to_fixed_12(value: f64) -> String {
532 let negative = value < 0.0;
533 // abs() rather than a negation, so a negative zero renders WITHOUT a
534 // sign: the digit walk below assumes every byte it reads is a digit.
535 let magnitude = value.abs();
536 let rendered = format!("{magnitude:.53}");
537 let dot = match rendered.find('.') {
538 Some(index) => index,
539 None => return rendered,
540 };
541 let mut integer_length = dot;
542 let digits: Vec<u8> = rendered
543 .bytes()
544 .filter(|byte| *byte != b'.')
545 .collect();
546 let keep = integer_length + 12;
547 // round half UP on the magnitude, reading the thirteenth decimal exactly
548 let round_up = digits[keep] >= b'5';
549 let mut kept: Vec<u8> = digits[..keep].to_vec();
550 if round_up {
551 let mut carry = 1u8;
552 let mut index = kept.len();
553 while index > 0 && carry == 1 {
554 index -= 1;
555 let digit = kept[index] - b'0' + carry;
556 carry = u8::from(digit >= 10);
557 kept[index] = (digit % 10) + b'0';
558 }
559 if carry == 1 {
560 kept.insert(0, b'1');
561 integer_length += 1;
562 }
563 }
564 let text = String::from_utf8_lossy(&kept).to_string();
565 let sign = if negative { "-" } else { "" };
566 format!("{}{}.{}", sign, &text[..integer_length], &text[integer_length..])
567 }
568}
569
570// ---------------------------------------------------------------------------
571// construction
572// ---------------------------------------------------------------------------
573
574impl OrderRouter {
575 /// Creates a client for the CCXT order-router service.
576 ///
577 /// `config` keys: `apiKey` (optional; the service rate-limits by IP), `baseUrl`, `timeoutMs`,
578 /// `maxNotionalUsd` (an OPT-IN per-trade USD cap, honoured exactly at
579 /// whatever value is given; 0 — the default — means NO CAP, and a negative
580 /// value is refused), `userAgent` (optional `User-Agent` header sent with every
581 /// router request so the service can attribute traffic, e.g.
582 /// `ccxt-mcp/1.2.3 (ccxt 4.5.6)`; empty — the default — keeps reqwest's default).
583 pub fn new(config: &Value) -> RouterResult<Self> {
584 // Constructed through a temporary so the accessors — which are methods,
585 // exactly as in the other five ports — are available while reading the
586 // config that builds the real one.
587 let reader = OrderRouter {
588 api_key: String::new(),
589 user_agent: String::new(),
590 base_url: String::new(),
591 timeout_ms: DEFAULT_TIMEOUT_MS,
592 max_notional_usd: NO_CAP,
593 now_ms_override: None,
594 executed_plan_ids: std::sync::Mutex::new(ExecutedPlanLedger::new()),
595 on_step: None,
596 venues: std::collections::BTreeMap::new(),
597 balances_cache: std::sync::Mutex::new(None),
598 balances_generation: std::sync::atomic::AtomicU64::new(0),
599 track_balances: false,
600 };
601 // The service dropped API keys in favour of per-IP rate limiting, so an empty key is
602 // the normal case and must not error. A key supplied anyway is CARRIED rather than
603 // ignored, so the same client works against both servers.
604 let api_key = reader.string_at(config, "apiKey", "");
605 let user_agent = reader.string_at(config, "userAgent", "");
606 let mut base_url = reader.string_at(config, "baseUrl", DEFAULT_BASE_URL);
607 while base_url.ends_with('/') {
608 base_url.pop();
609 }
610 let timeout_ms = reader.number_at(config, "timeoutMs", DEFAULT_TIMEOUT_MS);
611 let max_notional_usd = reader.number_at(config, "maxNotionalUsd", NO_CAP);
612 if max_notional_usd < 0.0 {
613 // A negative cap is a typo, not a policy, and silently ignoring it
614 // would leave the caller believing a guardrail is in place.
615 return Err(bad_request(
616 "OrderRouter maxNotionalUsd must not be negative; omit it, or pass 0, for no cap",
617 ));
618 }
619 // 0 means NO CAP. Any positive value is honoured exactly — it is not
620 // clamped, because the caller is the one who knows the size of their own
621 // trade.
622 Ok(OrderRouter {
623 api_key,
624 user_agent,
625 base_url,
626 timeout_ms,
627 max_notional_usd,
628 now_ms_override: None,
629 executed_plan_ids: std::sync::Mutex::new(ExecutedPlanLedger::new()),
630 on_step: None,
631 venues: std::collections::BTreeMap::new(),
632 balances_cache: std::sync::Mutex::new(None),
633 balances_generation: std::sync::atomic::AtomicU64::new(0),
634 track_balances: false,
635 })
636 }
637
638 /// Installs the `onStep` hook: called after each step completes and
639 /// reconciles, never mid-order, with one event describing that step. Return
640 /// `"halt"` to stop the route cleanly (`haltReason` becomes
641 /// `halted_by_on_step`); any other value continues. It can only STOP a
642 /// route, never resume one already halted. Do NO network I/O here — it sits
643 /// between orders on the money path. A hook that PANICS is recorded as
644 /// `on_step_hook_failed` and the run continues, because losing the report
645 /// would destroy the only account of orders that are already live.
646 pub fn set_on_step(&mut self, hook: OnStepHook) {
647 self.on_step = Some(hook);
648 }
649
650 /// Installs the venues this router trades through. See the `venues` field for why this
651 /// is a setter in Rust and a constructor key everywhere else.
652 pub fn set_venues(&mut self, venues: std::collections::BTreeMap<String, Box<dyn RouterVenue>>) {
653 self.venues = venues;
654 }
655
656 /// Turns balance tracking on or off. Off (the default), fetch_route never touches a venue
657 /// and stays a single HTTP request; on, it routes on what you can actually fund.
658 pub fn set_track_balances(&mut self, track: bool) {
659 self.track_balances = track;
660 self.invalidate_balances();
661 }
662
663 /// Removes the stored venues, so fetch_route stops filtering and funding on them.
664 pub fn clear_venues(&mut self) {
665 self.venues = std::collections::BTreeMap::new();
666 }
667
668 /// The venues this router holds, empty when none were installed.
669 pub fn venues(&self) -> &std::collections::BTreeMap<String, Box<dyn RouterVenue>> {
670 &self.venues
671 }
672
673 /// Removes the `onStep` hook.
674 pub fn clear_on_step(&mut self) {
675 self.on_step = None;
676 }
677
678 /// Reports whether this instance has executed the given plan id recently enough for
679 /// the bounded ledger to still remember it.
680 pub fn has_executed_plan(&self, plan_id: &str) -> bool {
681 self.executed_plan_ids.lock().unwrap().contains(plan_id)
682 }
683
684 /// Records one plan id in the bounded ledger, evicting the oldest entry when full.
685 pub fn record_executed_plan(&self, plan_id: &str) {
686 self.executed_plan_ids.lock().unwrap().record(plan_id.to_string());
687 }
688
689 /// How many plan ids the ledger currently holds, and the id at one position in
690 /// insertion order. Both exist so the self-test can assert the bound and the
691 /// eviction order without reaching through the mutex itself.
692 pub fn executed_plan_count(&self) -> usize {
693 self.executed_plan_ids.lock().unwrap().len()
694 }
695
696 pub fn executed_plan_at(&self, index: usize) -> String {
697 let ledger = self.executed_plan_ids.lock().unwrap();
698 match ledger.at(index) {
699 Some(entry) => entry.clone(),
700 None => String::new(),
701 }
702 }
703
704 /// Pins the clock, for tests. Production never calls this.
705 pub fn set_now_ms(&mut self, now_ms: f64) {
706 self.now_ms_override = Some(now_ms);
707 }
708
709 /// The only clock this class reads.
710 fn now_ms(&self) -> f64 {
711 match self.now_ms_override {
712 Some(pinned) => pinned,
713 None => std::time::SystemTime::now()
714 .duration_since(std::time::UNIX_EPOCH)
715 .map(|d| d.as_millis() as f64)
716 .unwrap_or(0.0),
717 }
718 }
719
720 /// The per-trade USD notional cap this client will enforce, or `NO_CAP` when
721 /// the caller never asked for one.
722 pub fn max_notional_usd(&self) -> f64 {
723 self.max_notional_usd
724 }
725
726 /// The api key this client carries, empty when it has none. The service is
727 /// public and needs no key; one supplied anyway is sent as `x-api-key`, so a
728 /// deployment fronting the router with its own authentication still works.
729 pub fn api_key(&self) -> &str {
730 &self.api_key
731 }
732
733 /// The User-Agent this client sends, empty when it keeps the http client's default.
734 pub fn user_agent(&self) -> &str {
735 &self.user_agent
736 }
737
738 /// The router base url, with any trailing slashes removed.
739 pub fn base_url(&self) -> &str {
740 &self.base_url
741 }
742
743 /// The configured request timeout, in milliseconds.
744 pub fn timeout_ms(&self) -> f64 {
745 self.timeout_ms
746 }
747}
748
749// ---------------------------------------------------------------------------
750// PURE: build_execution_plan
751// ---------------------------------------------------------------------------
752
753impl OrderRouter {
754 /// Refuses a route whose hops do not connect, or that does not run from the
755 /// asset the caller offered to the asset the caller wanted.
756 ///
757 /// `build_execution_plan` used to copy `from`, `to`, `pair` and `side`
758 /// straight out of the server's JSON, and the safety checks only tested
759 /// internal consistency against whatever market that named — so a
760 /// compromised, or simply buggy, router response could steer real orders
761 /// into any real market and every check would pass it, under the 25 USD cap.
762 pub fn assert_route_chain_is_coherent(&self, route: &Value, hops: &[Value]) -> RouterResult<()> {
763 if hops.is_empty() {
764 return Ok(());
765 }
766 let mut carried = String::new();
767 for (index, hop) in hops.iter().enumerate() {
768 let side = self.string_at(hop, "side", "").to_lowercase();
769 let base_code = self.string_at(hop, "base", "").to_uppercase();
770 let quote = self.string_at(hop, "quote", "").to_uppercase();
771 if base_code.is_empty() || quote.is_empty() || (side != "buy" && side != "sell") {
772 return Err(exchange_error(&format!(
773 "OrderRouter: hop {index} does not name a market and a side"
774 )));
775 }
776 // A buy spends the quote to acquire the base; a sell is the reverse.
777 let spends = if side == "buy" { quote.clone() } else { base_code.clone() };
778 let produces = if side == "buy" { base_code } else { quote };
779 if index > 0 && spends != carried {
780 // Hop N+1 must spend exactly what hop N produced, or the plan
781 // strands the proceeds of one order and funds the next from a
782 // wallet nobody checked.
783 return Err(exchange_error(&format!(
784 "OrderRouter: hop {index} spends {spends} but the previous hop produced {carried}"
785 )));
786 }
787 if index == 0 {
788 let requested_from = self.string_at(route, "clientRequestedFrom", "");
789 if !requested_from.is_empty() && spends != requested_from {
790 return Err(exchange_error(&format!(
791 "OrderRouter: the route spends {spends}, not the requested {requested_from}"
792 )));
793 }
794 }
795 carried = produces;
796 }
797 let requested_to = self.string_at(route, "clientRequestedTo", "");
798 if !requested_to.is_empty() && carried != requested_to {
799 return Err(exchange_error(&format!(
800 "OrderRouter: the route produces {carried}, not the requested {requested_to}"
801 )));
802 }
803 Ok(())
804 }
805
806 /// Turns a RouteResult into an ordered list of concrete orders. PURE — no
807 /// I/O, and the same input produces the same output in all six languages.
808 ///
809 /// `options` keys: `slippageBps` (default 25) and `reconcileToleranceRatio`
810 /// (default 0.02).
811 pub fn build_execution_plan(&self, route: &Value, options: &Value) -> RouterResult<Value> {
812 let slippage_bps = self.number_at(options, "slippageBps", DEFAULT_SLIPPAGE_BPS);
813 let tolerance = self.number_at(options, "reconcileToleranceRatio", DEFAULT_RECONCILE_TOLERANCE);
814 let hops = self.list_at(route, "hops");
815 self.assert_route_chain_is_coherent(route, &hops)?;
816 let mut steps: Vec<Value> = Vec::new();
817 let mut step_index = 0i64;
818 for (hop_index, hop) in hops.iter().enumerate() {
819 let symbol = self.string_at(hop, "pair", "");
820 let side = self.string_at(hop, "side", "");
821 let base_code = self.string_at(hop, "base", "");
822 let quote = self.string_at(hop, "quote", "");
823 let legs = self.list_at(hop, "legs");
824 for (leg_index, leg) in legs.iter().enumerate() {
825 // Leg amounts are always in BASE units, on both sides of the
826 // market — see the router's RoutingQuote.filledAmount contract.
827 let amount = self.number_at(leg, "amount", 0.0);
828 let expected_price = self.number_at(leg, "averagePrice", 0.0);
829 let effective_price = self.number_at(leg, "effectivePrice", expected_price);
830 // The limit sits on the side that costs you: above for a buy,
831 // below for a sell.
832 let limit_price = if side == "buy" {
833 expected_price * (1.0 + slippage_bps / 10000.0)
834 } else {
835 expected_price * (1.0 - slippage_bps / 10000.0)
836 };
837 let mut step = HashMap::new();
838 step.insert("stepIndex".into(), Value::Float(step_index as f64));
839 step.insert("hopIndex".into(), Value::Float(hop_index as f64));
840 step.insert("legIndex".into(), Value::Float(leg_index as f64));
841 step.insert("exchangeId".into(), Value::Str(self.string_at(leg, "exchangeId", "").into()));
842 step.insert("symbol".into(), Value::Str(symbol.clone().into()));
843 step.insert("side".into(), Value::Str(side.clone().into()));
844 step.insert("base".into(), Value::Str(base_code.clone().into()));
845 step.insert("quote".into(), Value::Str(quote.clone().into()));
846 step.insert("amount".into(), Value::Float(amount));
847 step.insert("expectedPrice".into(), Value::Float(expected_price));
848 step.insert("effectivePrice".into(), Value::Float(effective_price));
849 step.insert("limitPrice".into(), Value::Float(limit_price));
850 step.insert("notionalQuote".into(), Value::Float(amount * expected_price));
851 // The taker fee the ROUTER predicted for this leg, always denominated in
852 // the quote currency (the service's own RouteLeg.feeCost contract). Carried
853 // so step_expected_out can measure the expectation the same way execute
854 // measures the realised amount — see the note there. 0 on a hand-built plan,
855 // which is exactly the old behaviour.
856 step.insert(
857 "expectedFeeCost".into(),
858 Value::Float(self.number_at(leg, "feeCost", 0.0)),
859 );
860 // This leg was cut short by the WALLET, not by the book: more was on offer,
861 // the balances just could not pay for it. Size-capped and depth-capped look
862 // identical in the numbers and need different follow-up.
863 step.insert(
864 "balanceLimited".into(),
865 Value::Bool(self.bool_at(leg, "balanceLimited", false)),
866 );
867 steps.push(Value::Map(step));
868 step_index += 1;
869 }
870 }
871 let mut plan = HashMap::new();
872 plan.insert("requestId".into(), Value::Str(self.string_at(route, "requestId", "").into()));
873 plan.insert("calculatedAt".into(), Value::Float(self.number_at(route, "calculatedAt", 0.0)));
874 plan.insert("from".into(), Value::Str(self.string_at(route, "from", "").into()));
875 plan.insert("to".into(), Value::Str(self.string_at(route, "to", "").into()));
876 plan.insert("routingStrategy".into(), Value::Str(self.string_at(route, "strategy", "").into()));
877 plan.insert("exactSide".into(), Value::Str(self.string_at(route, "exactSide", "").into()));
878 plan.insert("amountIn".into(), Value::Float(self.number_at(route, "amountIn", 0.0)));
879 plan.insert("amountOut".into(), Value::Float(self.number_at(route, "amountOut", 0.0)));
880 plan.insert("fullyFillable".into(), Value::Bool(self.bool_at(route, "fullyFillable", false)));
881 plan.insert("fillRatio".into(), Value::Float(self.number_at(route, "fillRatio", 0.0)));
882 plan.insert("unroutableReason".into(), Value::Str(self.string_at(route, "unroutableReason", "").into()));
883 // WHICH hop could not be solved. -1 when the route is routable or the server did not
884 // say; 0 is a real answer and must not read as "unknown".
885 plan.insert(
886 "unroutableHopIndex".into(),
887 Value::Float(self.number_at(route, "unroutableHopIndex", -1.0)),
888 );
889 // What the CALLER asked for, stamped by fetch_route — not the server's echo.
890 plan.insert(
891 "requireFullFill".into(),
892 Value::Bool(self.bool_at(route, "clientRequestedRequireFullFill", false)),
893 );
894 plan.insert("hopCount".into(), Value::Float(hops.len() as f64));
895 plan.insert("stepCount".into(), Value::Float(steps.len() as f64));
896 plan.insert("slippageBps".into(), Value::Float(slippage_bps));
897 plan.insert("reconcileToleranceRatio".into(), Value::Float(tolerance));
898 plan.insert("steps".into(), Value::List(steps));
899 Ok(Value::Map(plan))
900 }
901}
902
903// ---------------------------------------------------------------------------
904// the venue abstraction
905// ---------------------------------------------------------------------------
906
907/// What `execute` needs from an exchange, and nothing more.
908///
909/// The other five ports hand `execute` their language's exchange object
910/// directly. Rust cannot: `ExchangeBase`'s methods return `impl Future`, which
911/// is not object-safe, so a `HashMap<String, Box<dyn ExchangeBase>>` — the
912/// shape every other port uses for `venues` — cannot exist. This trait is that
913/// shape, narrowed to the operations the money path actually performs, and it
914/// is what makes the venues map possible here at all.
915///
916/// It also buys something the other ports get for free from dynamic typing: a
917/// test can implement this in twenty lines, so the execute-path invariants are
918/// testable without a live exchange.
919#[async_trait::async_trait]
920pub trait RouterVenue: Send + Sync {
921 /// The venue's ccxt id, e.g. `binance`. Matched against a step's
922 /// `exchangeId`.
923 fn id(&self) -> String;
924
925 /// Snaps an amount to the market's precision, as text — the same contract
926 /// as ccxt's `amountToPrecision`.
927 fn amount_to_precision(&self, symbol: &str, amount: f64) -> String;
928
929 /// Snaps a price to the market's precision, as text.
930 fn price_to_precision(&self, symbol: &str, price: f64) -> String;
931
932 /// Whether this venue accepts an immediate-or-cancel time-in-force on a
933 /// limit order. A venue that does not gets a market order only when the
934 /// caller has explicitly opted in — see `execute`.
935 fn supports_ioc(&self) -> bool;
936
937 /// Places an order. `params` carries the time-in-force and any caller
938 /// extras.
939 async fn create_order(
940 &self,
941 symbol: &str,
942 order_type: &str,
943 side: &str,
944 amount: f64,
945 price: f64,
946 params: &Value,
947 ) -> RouterResult<Value>;
948
949 /// Reads an order back. Used to re-read a venue that answered without a
950 /// `filled`, rather than assuming one.
951 async fn fetch_order(&self, id: &str, symbol: &str) -> RouterResult<Value>;
952
953 /// Cancels an order. Used by the protected-limit path when the poll expires.
954 async fn cancel_order(&self, id: &str, symbol: &str) -> RouterResult<Value>;
955
956 /// Reads the account's holdings, in ccxt's balance shape — `free` and
957 /// `total` maps of currency code to amount. Only `fetch_route_with_balances`
958 /// calls this; a venue used solely with `execute` can return an empty map.
959 async fn fetch_balance(&self) -> RouterResult<Value> {
960 Ok(Value::Map(HashMap::new()))
961 }
962}
963
964// ---------------------------------------------------------------------------
965// PURE: check_execution_plan_safety
966// ---------------------------------------------------------------------------
967
968impl OrderRouter {
969 /// Builds one safety violation record.
970 fn violation(
971 &self,
972 step_index: f64,
973 exchange_id: &str,
974 symbol: &str,
975 code: &str,
976 blocking: bool,
977 actual: f64,
978 limit: f64,
979 ) -> Value {
980 let mut entry = HashMap::new();
981 entry.insert("stepIndex".into(), Value::Float(step_index));
982 entry.insert("exchangeId".into(), Value::Str(exchange_id.to_string().into()));
983 entry.insert("symbol".into(), Value::Str(symbol.to_string().into()));
984 entry.insert("code".into(), Value::Str(code.to_string().into()));
985 entry.insert("blocking".into(), Value::Bool(blocking));
986 entry.insert("actual".into(), Value::Float(actual));
987 entry.insert("limit".into(), Value::Float(limit));
988 entry.insert("message".into(), Value::Str(violation_message(code).to_string().into()));
989 Value::Map(entry)
990 }
991
992 /// Resolves the USD price of a currency, treating USD itself as 1 and
993 /// assuming nothing about anything else.
994 fn usd_rate_for(&self, code: &str, usd_rates: &Value) -> f64 {
995 if code.is_empty() {
996 return 0.0;
997 }
998 if code == "USD" {
999 return 1.0;
1000 }
1001 // USDT and USDC are NOT assumed to be one dollar. A stablecoin peg is an
1002 // empirical fact, not a definition, and the caller supplying rates is
1003 // the one who knows today's.
1004 let rate = self.number_at(usd_rates, code, 0.0);
1005 if rate > 0.0 {
1006 return rate;
1007 }
1008 0.0
1009 }
1010
1011 /// The USD value of a step's notional, quote side first and base side as
1012 /// the fallback — `amount * usd(base)` values the same trade.
1013 fn notional_usd(&self, step: &Value, notional_quote: f64, usd_rates: &Value) -> f64 {
1014 let quote = self.string_at(step, "quote", "");
1015 let quote_rate = self.usd_rate_for("e, usd_rates);
1016 if quote_rate > 0.0 {
1017 return notional_quote * quote_rate;
1018 }
1019 let base_code = self.string_at(step, "base", "");
1020 let base_rate = self.usd_rate_for(&base_code, usd_rates);
1021 if base_rate > 0.0 {
1022 return self.number_at(step, "amount", 0.0) * base_rate;
1023 }
1024 0.0
1025 }
1026
1027 /// Reports whether a value fails to sit on a market's precision grid.
1028 fn precision_violated(&self, value: f64, precision: f64, mode: &str) -> bool {
1029 if precision <= 0.0 {
1030 // Unknown or unconstrained precision is not a finding.
1031 return false;
1032 }
1033 let rounded = if mode == "decimal_places" {
1034 let factor = 10f64.powf(precision);
1035 (value * factor).round() / factor
1036 } else {
1037 // The rounding mode is irrelevant here: a value exactly halfway
1038 // between two ticks is off-grid whichever neighbour it snaps to, so
1039 // the six languages' differing round() semantics cannot change this
1040 // predicate's answer.
1041 (value / precision).round() * precision
1042 };
1043 let allowed = value.abs() * TOLERANCE + 1e-15;
1044 (rounded - value).abs() > allowed
1045 }
1046
1047 /// Checks a plan against per-venue market rules and the hard per-trade USD
1048 /// notional cap. PURE — no I/O. A step that cannot be valued in USD BLOCKS;
1049 /// it is never skipped, because a cap that silently disappears when a rate
1050 /// is missing is not a cap.
1051 ///
1052 /// `markets` is `markets[exchangeId][symbol]`.
1053 pub fn check_execution_plan_safety(
1054 &self,
1055 plan: &Value,
1056 markets: &Value,
1057 options: &Value,
1058 ) -> Vec<Value> {
1059 let mut violations: Vec<Value> = Vec::new();
1060 // Honoured exactly as given, per call or per client. No clamping: a
1061 // caller trading thousands and a caller trading cents are both using
1062 // this correctly.
1063 let max_notional_usd = self.number_at(options, "maxNotionalUsd", self.max_notional_usd);
1064 let cap_in_force = max_notional_usd > 0.0;
1065 let usd_rates = self.dict_at(options, "usdRates");
1066 let precision_mode = self.string_at(options, "precisionMode", "tick_size");
1067 let steps = self.list_at(plan, "steps");
1068 if steps.is_empty() {
1069 // An empty plan passing an empty violation list would read as "safe".
1070 violations.push(self.violation(-1.0, "", "", "empty_plan", true, 0.0, 0.0));
1071 return violations;
1072 }
1073 let unroutable_reason = self.string_at(plan, "unroutableReason", "");
1074 if !unroutable_reason.is_empty() {
1075 violations.push(self.violation(-1.0, "", "", "route_unroutable", true, 0.0, 0.0));
1076 }
1077 if !self.bool_at(plan, "fullyFillable", false) {
1078 violations.push(self.violation(
1079 // BLOCKING when the caller asked for requireFullFill. That parameter is
1080 // the one route flag that fails OPEN: a partial route in the same breath as
1081 // the flag means the flag did not survive the trip.
1082 -1.0,
1083 "",
1084 "",
1085 "partial_fill",
1086 self.bool_at(plan, "requireFullFill", false),
1087 self.number_at(plan, "fillRatio", 0.0),
1088 1.0,
1089 ));
1090 }
1091 for (i, step) in steps.iter().enumerate() {
1092 let step_index = self.number_at(step, "stepIndex", i as f64);
1093 let exchange_id = self.string_at(step, "exchangeId", "");
1094 let symbol = self.string_at(step, "symbol", "");
1095 let amount = self.number_at(step, "amount", 0.0);
1096 let expected_price = self.number_at(step, "expectedPrice", 0.0);
1097 let limit_price = self.step_limit_price(step);
1098 let notional_quote = self.step_notional_quote(step);
1099 let side = self.string_at(step, "side", "");
1100 if amount <= 0.0 || expected_price <= 0.0 || (side != "buy" && side != "sell") {
1101 violations.push(self.violation(
1102 step_index, &exchange_id, &symbol, "invalid_step", true, amount, 0.0,
1103 ));
1104 continue;
1105 }
1106 let venue_markets = self.dict_at(markets, &exchange_id);
1107 let market = self.dict_at(&venue_markets, &symbol);
1108 if market.as_map().map(|m| m.is_empty()).unwrap_or(true) {
1109 violations.push(self.violation(
1110 step_index, &exchange_id, &symbol, "unknown_symbol", true, 0.0, 0.0,
1111 ));
1112 continue;
1113 }
1114 // The same symbol string on a different venue is not necessarily the
1115 // same pair, and the USD valuation below trusts the step's quote
1116 // currency — so disagreement is fatal, not cosmetic.
1117 let market_base = self.string_at(&market, "base", "");
1118 let market_quote = self.string_at(&market, "quote", "");
1119 let step_base = self.string_at(step, "base", "");
1120 let step_quote = self.string_at(step, "quote", "");
1121 let base_disagrees =
1122 !market_base.is_empty() && !step_base.is_empty() && market_base != step_base;
1123 let quote_disagrees =
1124 !market_quote.is_empty() && !step_quote.is_empty() && market_quote != step_quote;
1125 if base_disagrees || quote_disagrees {
1126 violations.push(self.violation(
1127 step_index, &exchange_id, &symbol, "market_mismatch", true, 0.0, 0.0,
1128 ));
1129 continue;
1130 }
1131 let limits = self.dict_at(&market, "limits");
1132 let amount_limits = self.dict_at(&limits, "amount");
1133 let price_limits = self.dict_at(&limits, "price");
1134 let cost_limits = self.dict_at(&limits, "cost");
1135 let min_amount = self.number_at(&amount_limits, "min", 0.0);
1136 let max_amount = self.number_at(&amount_limits, "max", 0.0);
1137 let min_price = self.number_at(&price_limits, "min", 0.0);
1138 let max_price = self.number_at(&price_limits, "max", 0.0);
1139 let min_cost = self.number_at(&cost_limits, "min", 0.0);
1140 if min_amount > 0.0 && amount < min_amount {
1141 violations.push(self.violation(
1142 step_index, &exchange_id, &symbol, "amount_below_minimum", true, amount, min_amount,
1143 ));
1144 }
1145 if max_amount > 0.0 && amount > max_amount {
1146 violations.push(self.violation(
1147 step_index, &exchange_id, &symbol, "amount_above_maximum", true, amount, max_amount,
1148 ));
1149 }
1150 if min_cost > 0.0 && notional_quote < min_cost {
1151 violations.push(self.violation(
1152 step_index, &exchange_id, &symbol, "cost_below_minimum", true, notional_quote, min_cost,
1153 ));
1154 }
1155 if (min_price > 0.0 && limit_price < min_price)
1156 || (max_price > 0.0 && limit_price > max_price)
1157 {
1158 let bound = if limit_price < min_price { min_price } else { max_price };
1159 violations.push(self.violation(
1160 step_index, &exchange_id, &symbol, "price_out_of_range", true, limit_price, bound,
1161 ));
1162 }
1163 let precision = self.dict_at(&market, "precision");
1164 let amount_precision = self.number_at(&precision, "amount", 0.0);
1165 let price_precision = self.number_at(&precision, "price", 0.0);
1166 // Precision findings are advisory: execute() snaps through the
1167 // venue's own amountToPrecision/priceToPrecision before sending.
1168 if self.precision_violated(amount, amount_precision, &precision_mode) {
1169 violations.push(self.violation(
1170 step_index, &exchange_id, &symbol, "amount_precision", false, amount, amount_precision,
1171 ));
1172 }
1173 if self.precision_violated(limit_price, price_precision, &precision_mode) {
1174 violations.push(self.violation(
1175 step_index, &exchange_id, &symbol, "price_precision", false, limit_price, price_precision,
1176 ));
1177 }
1178 // The notional cap. The worst case is the higher of the expected and
1179 // the limit price, which is the buy side; a sell's limit sits below,
1180 // so its expected price is the one that governs.
1181 let mut worst_price = expected_price;
1182 if limit_price > worst_price {
1183 worst_price = limit_price;
1184 }
1185 if cap_in_force {
1186 // Only when a cap is actually set. With no cap there is nothing
1187 // to enforce, so a missing USD rate is not an error and the
1188 // caller is not made to supply usdRates for a check they did not
1189 // ask for.
1190 let worst_notional = amount * worst_price;
1191 let usd_value = self.notional_usd(step, worst_notional, &usd_rates);
1192 if usd_value <= 0.0 {
1193 // BLOCKING, and deliberately so. Skipping the cap for a step
1194 // whose USD value is unknown defeats the cap the caller DID
1195 // ask for.
1196 violations.push(self.violation(
1197 step_index, &exchange_id, &symbol, "notional_unvaluable", true,
1198 worst_notional, max_notional_usd,
1199 ));
1200 } else if usd_value > max_notional_usd * (1.0 + TOLERANCE) {
1201 violations.push(self.violation(
1202 step_index, &exchange_id, &symbol, "notional_exceeds_cap", true, usd_value,
1203 max_notional_usd,
1204 ));
1205 }
1206 }
1207 }
1208 violations
1209 }
1210}
1211
1212// ---------------------------------------------------------------------------
1213// PURE: reconcile_execution_step
1214// ---------------------------------------------------------------------------
1215
1216impl OrderRouter {
1217 /// How much of its output asset a step is expected to produce, gross of
1218 /// fees: base units for a buy, quote units for a sell.
1219 pub fn step_expected_out(&self, step: &Value) -> f64 {
1220 let amount = self.number_at(step, "amount", 0.0);
1221 if self.string_at(step, "side", "") == "buy" {
1222 // A buy produces BASE, and the router's predicted fee is quote-denominated,
1223 // so it does not reduce what this step hands to the next one. A venue that
1224 // charges its buy fee in the base asset really does deliver less, and the
1225 // resize that follows from it is correct.
1226 return amount;
1227 }
1228 // A SELL produces QUOTE, which is the currency the predicted fee is already in.
1229 //
1230 // This subtraction is what stops the fee being counted TWICE. execute reports
1231 // realisedOut net of a fee charged in the asset the step produced, because that
1232 // is what the wallet actually receives. The router, in turn, already sized the
1233 // next hop from its own NET figure: in the shared fixture, hop 0 sells 500 DOGE
1234 // at 0.089 for 44.5 gross, reports amountOut 44.47482324238088 after a
1235 // 0.025176757619121304 USDT fee, and hop 1's amountIn is that net number to the
1236 // last digit. Measuring the expectation gross against a realised amount that is
1237 // net therefore reported a shortfall on a PERFECT fill and shrank the next hop by
1238 // the fee a second time, stranding it in the bridge asset.
1239 //
1240 // Gross stays gross where gross is right: notionalQuote is what the order is
1241 // worth to the venue and is untouched, as is the notional cap built on it.
1242 let gross = amount * self.number_at(step, "expectedPrice", 0.0);
1243 let expected_fee = self.number_at(step, "expectedFeeCost", 0.0);
1244 if expected_fee <= 0.0 || expected_fee >= gross {
1245 // a fee at or above the whole proceeds is not a fee this class will
1246 // subtract: it would report an expectation of zero or less and turn every
1247 // fill into a halt
1248 return gross;
1249 }
1250 gross - expected_fee
1251 }
1252
1253 /// Reports whether a field holds a usable number, as opposed to holding
1254 /// zero or nothing at all.
1255 ///
1256 /// "The venue said zero" and "the venue said nothing" are different facts
1257 /// and used to produce the same number. Reuses `number_of` rather than
1258 /// re-deriving the coercion: "the value is usable" and "the value is
1259 /// present" must never disagree, and two copies of that rule is how they
1260 /// would.
1261 pub fn has_number_at(&self, container: &Value, key: &str) -> bool {
1262 let probe = Self::number_of(field(container, key), f64::NAN);
1263 Self::is_finite_number(probe)
1264 }
1265
1266 /// Compares what a step actually produced against what the route predicted,
1267 /// resizes every downstream hop, and returns the proceed-or-halt verdict.
1268 /// PURE — no I/O.
1269 ///
1270 /// The halt decision lives here rather than in the execution loop because it
1271 /// is a money decision, and six separate loops is six chances to omit it.
1272 pub fn reconcile_execution_step(
1273 &self,
1274 plan: &Value,
1275 step_index: i64,
1276 realised_out: f64,
1277 ) -> RouterResult<Value> {
1278 let steps = self.list_at(plan, "steps");
1279 if step_index < 0 || step_index as usize >= steps.len() {
1280 return Err(bad_request("reconcileExecutionStep: stepIndex is out of range"));
1281 }
1282 let step = &steps[step_index as usize];
1283 let hop_index = self.number_at(step, "hopIndex", 0.0);
1284 let tolerance =
1285 self.number_at(plan, "reconcileToleranceRatio", DEFAULT_RECONCILE_TOLERANCE);
1286 let expected_out = self.step_expected_out(step);
1287 let mut resized: Vec<Value> = Vec::new();
1288 if expected_out <= 0.0 {
1289 let mut verdict = HashMap::new();
1290 verdict.insert("stepIndex".into(), Value::Float(step_index as f64));
1291 verdict.insert("hopIndex".into(), Value::Float(hop_index));
1292 verdict.insert("expectedOut".into(), Value::Float(0.0));
1293 verdict.insert("realisedOut".into(), Value::Float(realised_out));
1294 verdict.insert("shortfall".into(), Value::Float(0.0));
1295 verdict.insert("shortfallRatio".into(), Value::Float(0.0));
1296 verdict.insert("scale".into(), Value::Float(0.0));
1297 verdict.insert("verdict".into(), Value::Str("halt".into()));
1298 verdict.insert("reason".into(), Value::Str("zero_expected_output".into()));
1299 verdict.insert("resizedSteps".into(), Value::List(resized));
1300 return Ok(Value::Map(verdict));
1301 }
1302 let mut shortfall = expected_out - realised_out;
1303 if shortfall < 0.0 {
1304 shortfall = 0.0;
1305 }
1306 let shortfall_ratio = shortfall / expected_out;
1307 // The downstream hops lost `shortfall` out of this hop's whole output,
1308 // not out of this leg's, so the scale is measured against the hop.
1309 let mut hop_expected_out = 0.0f64;
1310 // Shortfall already reported by this hop's OTHER legs. Each leg used to
1311 // compute a scale from the hop total and multiply the downstream amounts
1312 // by it, so a second leg scaled an already-scaled number: 80% and 60%
1313 // fills produced 0.9 x 0.8 = 0.72 of the next hop instead of the true
1314 // 0.70, sizing it for more than the wallet actually received and
1315 // inviting a spurious insufficient-funds halt on exactly the bridged
1316 // routes this class exists for. Reproduced at 144 against a true 140
1317 // before this changed.
1318 let mut prior_shortfall = 0.0f64;
1319 for other in steps.iter() {
1320 if self.number_at(other, "hopIndex", 0.0) == hop_index {
1321 hop_expected_out += self.step_expected_out(other);
1322 if self.number_at(other, "stepIndex", -1.0) != step_index as f64
1323 && self.has_number_at(other, "realisedOut")
1324 {
1325 let mut leg_shortfall =
1326 self.step_expected_out(other) - self.number_at(other, "realisedOut", 0.0);
1327 if leg_shortfall < 0.0 {
1328 leg_shortfall = 0.0;
1329 }
1330 prior_shortfall += leg_shortfall;
1331 }
1332 }
1333 }
1334 // scale_before is what the downstream amounts have ALREADY been
1335 // multiplied by, so the factor applied here is the increment that takes
1336 // them from that to the hop's true cumulative scale. With one leg per
1337 // hop prior_shortfall is 0, scale_before is 1, and this is
1338 // arithmetically identical to what it replaced.
1339 let mut scale_before = 1.0f64;
1340 let mut scale_after = 1.0f64;
1341 if hop_expected_out > 0.0 {
1342 scale_before = (hop_expected_out - prior_shortfall) / hop_expected_out;
1343 scale_after = (hop_expected_out - prior_shortfall - shortfall) / hop_expected_out;
1344 }
1345 if scale_before <= 0.0 {
1346 // The hop already produced nothing; there is nothing left to scale
1347 // down.
1348 scale_before = 1.0;
1349 scale_after = 0.0;
1350 }
1351 let mut scale = scale_after / scale_before;
1352 if scale > 1.0 {
1353 // Never scale UP. An overfill is good news, but growing a downstream
1354 // order past the size that passed the safety check would place an
1355 // order nobody ever approved.
1356 scale = 1.0;
1357 }
1358 if scale < 0.0 {
1359 scale = 0.0;
1360 }
1361 for (i, other) in steps.iter().enumerate() {
1362 if self.number_at(other, "hopIndex", 0.0) <= hop_index {
1363 continue;
1364 }
1365 let previous_amount = self.number_at(other, "amount", 0.0);
1366 let amount = previous_amount * scale;
1367 let mut entry = HashMap::new();
1368 entry.insert(
1369 "stepIndex".into(),
1370 Value::Float(self.number_at(other, "stepIndex", i as f64)),
1371 );
1372 entry.insert("previousAmount".into(), Value::Float(previous_amount));
1373 entry.insert("amount".into(), Value::Float(amount));
1374 entry.insert(
1375 "notionalQuote".into(),
1376 Value::Float(amount * self.number_at(other, "expectedPrice", 0.0)),
1377 );
1378 resized.push(Value::Map(entry));
1379 }
1380 let mut verdict_text = "proceed";
1381 let mut reason = "within_tolerance";
1382 if realised_out <= 0.0 {
1383 verdict_text = "halt";
1384 reason = "nothing_filled";
1385 } else if shortfall_ratio > tolerance * (1.0 + TOLERANCE) {
1386 verdict_text = "halt";
1387 reason = "shortfall_exceeds_tolerance";
1388 }
1389 let mut verdict = HashMap::new();
1390 verdict.insert("stepIndex".into(), Value::Float(step_index as f64));
1391 verdict.insert("hopIndex".into(), Value::Float(hop_index));
1392 verdict.insert("expectedOut".into(), Value::Float(expected_out));
1393 verdict.insert("realisedOut".into(), Value::Float(realised_out));
1394 verdict.insert("shortfall".into(), Value::Float(shortfall));
1395 verdict.insert("shortfallRatio".into(), Value::Float(shortfall_ratio));
1396 verdict.insert("scale".into(), Value::Float(scale));
1397 verdict.insert("verdict".into(), Value::Str(verdict_text.into()));
1398 verdict.insert("reason".into(), Value::Str(reason.into()));
1399 verdict.insert("resizedSteps".into(), Value::List(resized));
1400 Ok(Value::Map(verdict))
1401 }
1402
1403 /// Writes a reconciliation's downstream resize back into the working steps.
1404 ///
1405 /// Records what this leg actually produced BEFORE resizing anything.
1406 /// `reconcile_execution_step` is pure and cannot remember across calls, so
1407 /// the hop's cumulative shortfall has to live on the steps themselves —
1408 /// this is what stops the next leg of the same hop compounding its scale
1409 /// onto an already-scaled amount.
1410 pub fn apply_resize(&self, steps: &mut [Value], reconciliation: &Value) {
1411 let reconciled_step = self.number_at(reconciliation, "stepIndex", -1.0);
1412 let realised_out = self.number_at(reconciliation, "realisedOut", 0.0);
1413 for step in steps.iter_mut() {
1414 if self.number_at(step, "stepIndex", -1.0) == reconciled_step {
1415 Self::put(step, "realisedOut", Value::Float(realised_out));
1416 break;
1417 }
1418 }
1419 let resized = self.list_at(reconciliation, "resizedSteps");
1420 for entry in &resized {
1421 let target = self.number_at(entry, "stepIndex", -1.0);
1422 let amount = self.number_at(entry, "amount", 0.0);
1423 let notional = self.number_at(entry, "notionalQuote", 0.0);
1424 for step in steps.iter_mut() {
1425 if self.number_at(step, "stepIndex", -1.0) == target {
1426 Self::put(step, "amount", Value::Float(amount));
1427 Self::put(step, "notionalQuote", Value::Float(notional));
1428 break;
1429 }
1430 }
1431 }
1432 }
1433
1434 /// Sets a key on a `Value::Dict` in place, through `Arc::make_mut` so the
1435 /// copy-on-write only deep-copies when the map is actually shared.
1436 ///
1437 /// Public because callers building a route by hand need it too — stamping
1438 /// `clientRequestedFrom`/`clientRequestedTo` onto a route obtained by some
1439 /// route other than `fetch_route`, for one. The other five ports get this
1440 /// for free from assignment into a dictionary.
1441 pub fn set_key(container: &mut Value, key: &str, value: Value) {
1442 Self::put(container, key, value)
1443 }
1444
1445 fn put(container: &mut Value, key: &str, value: Value) {
1446 if let Value::Dict(map) = container {
1447 Arc::make_mut(map).insert(key.to_string(), value);
1448 }
1449 }
1450}
1451
1452// ---------------------------------------------------------------------------
1453// PURE: build_unwind_plan
1454// ---------------------------------------------------------------------------
1455
1456impl OrderRouter {
1457 /// Accumulates a signed amount into the (exchangeId, asset) position list,
1458 /// appending in first-seen order.
1459 ///
1460 /// `produced` is true when this step PRODUCED the asset, which is the only
1461 /// kind of step an unwind can reverse.
1462 fn add_position(
1463 &self,
1464 positions: &mut Vec<Value>,
1465 exchange_id: &str,
1466 asset: &str,
1467 amount: f64,
1468 source: &Value,
1469 produced: bool,
1470 ) {
1471 for position in positions.iter_mut() {
1472 let same_venue = self.string_at(position, "exchangeId", "") == exchange_id;
1473 let same_asset = self.string_at(position, "asset", "") == asset;
1474 if same_venue && same_asset {
1475 let running = self.number_at(position, "amount", 0.0) + amount;
1476 Self::put(position, "amount", Value::Float(running));
1477 let existing = self.dict_at(position, "source");
1478 let empty = existing.as_map().map(|m| m.is_empty()).unwrap_or(true);
1479 if produced && empty {
1480 Self::put(position, "source", source.clone());
1481 }
1482 return;
1483 }
1484 }
1485 // The source must be the step that PRODUCED the asset, never one that
1486 // consumed it: reversing a step that spent your USDT would sell the
1487 // wrong side of the wrong market. Walking the results backwards, the
1488 // first producing step seen is the last one that ran, which is exactly
1489 // the order an unwind undoes first.
1490 let initial_source =
1491 if produced { source.clone() } else { Value::Map(HashMap::new()) };
1492 let mut entry = HashMap::new();
1493 entry.insert("exchangeId".into(), Value::Str(exchange_id.to_string().into()));
1494 entry.insert("asset".into(), Value::Str(asset.to_string().into()));
1495 entry.insert("amount".into(), Value::Float(amount));
1496 entry.insert("source".into(), initial_source);
1497 positions.push(Value::Map(entry));
1498 }
1499
1500 /// Given a halted execution report, computes the reverse orders that sell
1501 /// each stranded residual back toward the original from-asset, on the venue
1502 /// that actually holds it. PURE — no I/O.
1503 ///
1504 /// NEVER automatic: the result carries `requiresConfirmation` and nothing in
1505 /// this class executes it.
1506 pub fn build_unwind_plan(&self, report: &Value) -> Value {
1507 let from_asset = self.string_at(report, "from", "");
1508 let to_asset = self.string_at(report, "to", "");
1509 let slippage_bps = self.number_at(report, "slippageBps", DEFAULT_SLIPPAGE_BPS);
1510 let results = self.list_at(report, "steps");
1511 // Net position per (exchangeId, asset). Held in a VECTOR rather than a
1512 // map because the output order must be identical in six languages and
1513 // map iteration order is not.
1514 let mut positions: Vec<Value> = Vec::new();
1515 for result in results.iter().rev() {
1516 let exchange_id = self.string_at(result, "exchangeId", "");
1517 let out_asset = self.string_at(result, "outAsset", "");
1518 let out_amount = self.number_at(result, "outAmount", 0.0);
1519 if !out_asset.is_empty() && out_amount > 0.0 {
1520 self.add_position(&mut positions, &exchange_id, &out_asset, out_amount, result, true);
1521 }
1522 let in_asset = self.string_at(result, "inAsset", "");
1523 let in_amount = self.number_at(result, "inAmount", 0.0);
1524 if !in_asset.is_empty() && in_amount > 0.0 {
1525 // What a later hop consumed on this venue is not a residual.
1526 // Netting is per venue: assets sitting on a venue the route
1527 // never spent them on stay stranded, because this class never
1528 // moves funds between venues.
1529 self.add_position(&mut positions, &exchange_id, &in_asset, -in_amount, result, false);
1530 }
1531 }
1532 let mut steps: Vec<Value> = Vec::new();
1533 let mut unresolved: Vec<Value> = Vec::new();
1534 let mut residual_count = 0i64;
1535 for position in &positions {
1536 let asset = self.string_at(position, "asset", "");
1537 let amount = self.number_at(position, "amount", 0.0);
1538 let exchange_id = self.string_at(position, "exchangeId", "");
1539 if amount <= 0.0 {
1540 continue;
1541 }
1542 if asset == from_asset {
1543 // Already home.
1544 continue;
1545 }
1546 residual_count += 1;
1547 let source = self.dict_at(position, "source");
1548 let symbol = self.string_at(&source, "symbol", "");
1549 let source_side = self.string_at(&source, "side", "");
1550 let mut price = self.number_at(&source, "averagePrice", 0.0);
1551 if price <= 0.0 {
1552 price = self.number_at(&source, "expectedPrice", 0.0);
1553 }
1554 if symbol.is_empty() || (source_side != "buy" && source_side != "sell") {
1555 unresolved.push(Self::unresolved_entry(&exchange_id, &asset, amount, "no_source_market"));
1556 continue;
1557 }
1558 if price <= 0.0 {
1559 unresolved.push(Self::unresolved_entry(&exchange_id, &asset, amount, "no_price"));
1560 continue;
1561 }
1562 // Reverse the order that created the residual: a buy left you
1563 // holding base, so sell it back; a sell left you holding quote, so
1564 // buy the base back with it.
1565 //
1566 // The counter asset is whatever the reversed order gives back, which
1567 // is exactly what the original order spent.
1568 let counter_asset = self.string_at(&source, "inAsset", "");
1569 let side;
1570 let unwind_amount;
1571 let market_base;
1572 let market_quote;
1573 if source_side == "buy" {
1574 side = "sell";
1575 market_base = self.string_at(&source, "outAsset", "");
1576 market_quote = self.string_at(&source, "inAsset", "");
1577 } else {
1578 side = "buy";
1579 market_base = self.string_at(&source, "inAsset", "");
1580 market_quote = self.string_at(&source, "outAsset", "");
1581 }
1582 // The limit price comes FIRST, because the buy below is sized on it.
1583 let limit_price = if side == "buy" {
1584 price * (1.0 + slippage_bps / 10000.0)
1585 } else {
1586 price * (1.0 - slippage_bps / 10000.0)
1587 };
1588 if side == "buy" {
1589 // Size the buy on the price it is actually PLACED at, not on the
1590 // expected price. A residual of 44.5 USDT sized at 0.089 is 500
1591 // DOGE, but the order goes out at 0.0892225 and would need 44.61
1592 // USDT to fill - 0.11 more than the venue holds. The venue rejects
1593 // it for insufficient funds, or fills it partially and leaves the
1594 // rest of the stranded money stranded. Dividing by limit_price
1595 // spends at most the residual.
1596 unwind_amount = amount / limit_price;
1597 } else {
1598 unwind_amount = amount;
1599 }
1600 let mut step = HashMap::new();
1601 step.insert("stepIndex".into(), Value::Float(steps.len() as f64));
1602 step.insert("exchangeId".into(), Value::Str(exchange_id.clone().into()));
1603 step.insert("symbol".into(), Value::Str(symbol.into()));
1604 step.insert("side".into(), Value::Str(side.to_string().into()));
1605 // base and quote are carried so that an unwind plan can be fed
1606 // straight back into check_execution_plan_safety: unwinding is
1607 // trading, and it is subject to the same 25 USD cap.
1608 step.insert("base".into(), Value::Str(market_base.into()));
1609 step.insert("quote".into(), Value::Str(market_quote.into()));
1610 step.insert("asset".into(), Value::Str(asset.clone().into()));
1611 step.insert("counterAsset".into(), Value::Str(counter_asset.clone().into()));
1612 step.insert("amount".into(), Value::Float(unwind_amount));
1613 step.insert("expectedPrice".into(), Value::Float(price));
1614 step.insert("limitPrice".into(), Value::Float(limit_price));
1615 // Notional at the price the order is actually placed at: this plan is
1616 // fed back into check_execution_plan_safety, and a cap that was
1617 // checked against the expected price under-counts what the buy above
1618 // really spends.
1619 step.insert(
1620 "notionalQuote".into(),
1621 Value::Float(unwind_amount * limit_price),
1622 );
1623 step.insert("reachesFrom".into(), Value::Bool(counter_asset == from_asset));
1624 step.insert("isDestination".into(), Value::Bool(asset == to_asset));
1625 steps.push(Value::Map(step));
1626 }
1627 let mut plan = HashMap::new();
1628 plan.insert("from".into(), Value::Str(from_asset.into()));
1629 plan.insert("to".into(), Value::Str(to_asset.into()));
1630 plan.insert("halted".into(), Value::Bool(self.bool_at(report, "halted", false)));
1631 plan.insert("haltReason".into(), Value::Str(self.string_at(report, "haltReason", "").into()));
1632 plan.insert("residualCount".into(), Value::Float(residual_count as f64));
1633 plan.insert("requiresConfirmation".into(), Value::Bool(true));
1634 plan.insert("automatic".into(), Value::Bool(false));
1635 plan.insert("steps".into(), Value::List(steps));
1636 plan.insert("unresolved".into(), Value::List(unresolved));
1637 Value::Map(plan)
1638 }
1639
1640 fn unresolved_entry(exchange_id: &str, asset: &str, amount: f64, reason: &str) -> Value {
1641 let mut entry = HashMap::new();
1642 entry.insert("exchangeId".into(), Value::Str(exchange_id.to_string().into()));
1643 entry.insert("asset".into(), Value::Str(asset.to_string().into()));
1644 entry.insert("amount".into(), Value::Float(amount));
1645 entry.insert("reason".into(), Value::Str(reason.to_string().into()));
1646 Value::Map(entry)
1647 }
1648}
1649
1650// ---------------------------------------------------------------------------
1651// I/O: the router HTTP client
1652// ---------------------------------------------------------------------------
1653
1654/// The query keys forwarded to GET /route, in a fixed order so that two ports
1655/// build a byte-identical URL.
1656const ROUTE_QUERY_KEYS: [&str; 14] = [
1657 "amountIn", "amountOut", "strategy", "maxVenues", "bridges", "exchanges", "balances",
1658 "balanceMode", "includeQuotes", "includeFees", "certified", "requireFullFill",
1659 "hopPenaltyBps", "minLegNotional",
1660];
1661
1662impl OrderRouter {
1663 /// Percent-encodes exactly what JavaScript's `encodeURIComponent` leaves
1664 /// alone, so six ports produce the same URL byte for byte.
1665 ///
1666 /// Deliberately not `urlencoding::encode`: that is `application/x-www-form-
1667 /// urlencoded`, which escapes `!`, `'`, `(`, `)`, `*` and renders a space as
1668 /// `+`. `encodeURIComponent` does neither. A route whose bridge list or
1669 /// balances string contains any of those would sign a different URL here
1670 /// than in the other five.
1671 fn encode_uri_component(text: &str) -> String {
1672 let mut out = String::with_capacity(text.len());
1673 for byte in text.as_bytes() {
1674 let c = *byte;
1675 let unreserved = c.is_ascii_alphanumeric()
1676 || matches!(c, b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')');
1677 if unreserved {
1678 out.push(c as char);
1679 } else {
1680 out.push_str(&format!("%{:02X}", c));
1681 }
1682 }
1683 out
1684 }
1685
1686 /// Renders one query parameter's value the way the other five ports do.
1687 fn query_text(&self, value: &Value) -> RouterResult<String> {
1688 Ok(match value {
1689 Value::Bool(flag) => (if *flag { "true" } else { "false" }).to_string(),
1690 Value::Int(n) => self.format_number(*n as f64)?,
1691 Value::Float(n) => self.format_number(*n)?,
1692 Value::Arr(items) => items
1693 .iter()
1694 .map(|item| match item {
1695 Value::Str(s) => s.to_string(),
1696 other => format!("{other:?}"),
1697 })
1698 .collect::<Vec<String>>()
1699 .join(","),
1700 Value::Str(s) => s.to_string(),
1701 // REFUSED rather than debug-formatted. This used to end in `format!("{other:?}")`,
1702 // which renders a map as Rust's own debug form and ships it: the server then
1703 // rejects a value naming neither what was sent nor what was wanted. `balances` is
1704 // the one param with a meaningful map form and it is rendered before it gets here.
1705 other => {
1706 return Err(bad_request(&format!(
1707 "OrderRouter: a route parameter must be a string, number, boolean or list; got {other:?}"
1708 )))
1709 }
1710 })
1711 }
1712
1713 /// Refuses neither-or-both amounts before a byte reaches the wire.
1714 ///
1715 /// Shared by `fetch_route` and `watch_route` because the service runs ONE parser
1716 /// for both and they must not disagree about what is valid.
1717 pub fn assert_route_amounts(params: &Value, method: &str) -> RouterResult<()> {
1718 let has_amount_in = field(params, "amountIn").is_some();
1719 let has_amount_out = field(params, "amountOut").is_some();
1720 if has_amount_in == has_amount_out {
1721 return Err(bad_request(&format!(
1722 "{method} requires exactly one of amountIn or amountOut"
1723 )));
1724 }
1725 Ok(())
1726 }
1727
1728 /// Builds the wss url for `GET /stream/route`, refusing what the endpoint refuses.
1729 pub fn stream_url(&self, from_asset: &str, to_asset: &str, params: &Value) -> RouterResult<String> {
1730 if from_asset.is_empty() || to_asset.is_empty() {
1731 return Err(arguments_required("watchRoute requires fromAsset and toAsset"));
1732 }
1733 Self::assert_route_amounts(params, "watchRoute")?;
1734 // REFUSED HERE, not by the server closing the socket on us. A stream is held open
1735 // for minutes and carries no channel to update the holdings it was opened with, so
1736 // every frame after the first would price a portfolio the caller may already have
1737 // traded away.
1738 if field(params, "balances").is_some() {
1739 return Err(bad_request(
1740 "OrderRouter: /stream/route does not accept balances — a socket outlives the holdings it was opened with. Use fetch_route",
1741 ));
1742 }
1743 if field(params, "balanceMode").is_some() {
1744 return Err(bad_request(
1745 "OrderRouter: /stream/route does not accept balanceMode, because it does not accept balances. Use fetch_route",
1746 ));
1747 }
1748 // the same venue filter fetch_route applies. A router built with venues can only
1749 // execute on those, so a stream that quoted the rest would hand back routes its own
1750 // executor must refuse. The caller's own exchanges parameter still wins.
1751 let scoped_params: Value;
1752 let params = if !self.venues.is_empty() && field(params, "exchanges").is_none() {
1753 let mut scoped = params.as_map().cloned().unwrap_or_default();
1754 let stored_ids: Vec<String> = self.venues.keys().cloned().collect();
1755 scoped.insert("exchanges".to_string(), Value::from(stored_ids.join(",")));
1756 scoped_params = Value::map(scoped);
1757 &scoped_params
1758 } else {
1759 params
1760 };
1761 // includeQuotes is deliberately NOT defaulted: the service defaults it to false on
1762 // this endpoint and true on the REST one, and the query builder omits what the
1763 // caller did not set.
1764 let mut query = format!(
1765 "from={}&to={}",
1766 Self::encode_uri_component(&from_asset.to_uppercase()),
1767 Self::encode_uri_component(&to_asset.to_uppercase())
1768 );
1769 for key in ROUTE_QUERY_KEYS.iter() {
1770 let value = match field(params, key) {
1771 Some(found) => found,
1772 None => continue,
1773 };
1774 let text = self.query_text(value)?;
1775 query.push('&');
1776 query.push_str(key);
1777 query.push('=');
1778 query.push_str(&Self::encode_uri_component(&text));
1779 }
1780 let base = if let Some(rest) = self.base_url.strip_prefix("https://") {
1781 format!("wss://{rest}")
1782 } else if let Some(rest) = self.base_url.strip_prefix("http://") {
1783 format!("ws://{rest}")
1784 } else {
1785 self.base_url.clone()
1786 };
1787 Ok(format!("{base}/stream/route?{query}"))
1788 }
1789
1790 /// Maps a websocket close code onto the error the same refusal raises over REST.
1791 /// `None` for an ordinary close.
1792 pub fn stream_close_error(&self, code: u16, last_frame: &Value) -> Option<ExchangeError> {
1793 if code == 1008 {
1794 // the service sends ONE json frame carrying the same `error` string the REST
1795 // endpoint would have answered a 400 with — including a bridged exact-out,
1796 // which REST refuses as a 501. Same refusal, same error.
1797 let message = self.string_at(last_frame, "error", "the router rejected the stream request");
1798 return Some(bad_request(&format!("OrderRouter: {message}")));
1799 }
1800 if code == 1013 {
1801 // try again later: the cache was cold when the socket was accepted. A stream
1802 // carries no status codes once open, so this is the only way the service can say
1803 // what a REST 503 says — and it is the same retry, not a fault.
1804 let message = self.string_at(last_frame, "error", "the router cache is cold");
1805 let cold = self.cold_cache_suffix(last_frame);
1806 return Some(ExchangeError::new(
1807 "ExchangeNotAvailable",
1808 format!("OrderRouter: {message}{cold}"),
1809 ));
1810 }
1811 if code == 1000 || code == 1005 || code == 0 {
1812 // a clean close, or one with no code, which is what a caller-requested stop
1813 // looks like from here
1814 return None;
1815 }
1816 Some(ExchangeError::new(
1817 "ExchangeNotAvailable",
1818 format!("OrderRouter: the route stream closed with code {code}"),
1819 ))
1820 }
1821
1822 /// The same route as `fetch_route`, pushed over a websocket whenever any market it
1823 /// depends on moves.
1824 ///
1825 /// BLOCKS until the stream ends: `on_route` is how you read it. Return `"stop"` from the
1826 /// hook to close the socket cleanly; the call then returns the last route it saw. Every
1827 /// frame is stamped with the same client-side keys `fetch_route` stamps, so it can go
1828 /// straight into `build_execution_plan`.
1829 ///
1830 /// `balances` and `balanceMode` are refused — see `stream_url` for why — and
1831 /// `includeQuotes` is left to the endpoint's own default, which is false here.
1832 ///
1833 /// Unlike `execute`'s step hook, this one is a plain parameter rather than something
1834 /// stored on the client: nothing here has to survive in a `Value`, so the closed-enum
1835 /// workaround `set_on_step` needs does not apply.
1836 pub async fn watch_route(
1837 &self,
1838 from_asset: &str,
1839 to_asset: &str,
1840 params: &Value,
1841 on_route: &mut dyn FnMut(&Value) -> String,
1842 ) -> RouterResult<Value> {
1843 use futures::StreamExt;
1844 use tokio_tungstenite::tungstenite::client::IntoClientRequest;
1845 use tokio_tungstenite::tungstenite::Message;
1846
1847 // built BEFORE the socket, so a refusal this client can make itself costs no
1848 // connection
1849 let url = self.stream_url(from_asset, to_asset, params)?;
1850 let mut request = url.as_str().into_client_request().map_err(|e| {
1851 ExchangeError::new("ExchangeNotAvailable", format!("OrderRouter: {e}"))
1852 })?;
1853 {
1854 let headers = request.headers_mut();
1855 // omitted entirely when absent: an empty x-api-key reads as a malformed
1856 // credential to a server that still authenticates, not as an anonymous caller
1857 if !self.api_key.is_empty() {
1858 let key = self.api_key.parse().map_err(|_| {
1859 bad_request("OrderRouter: the apiKey cannot be sent as a header")
1860 })?;
1861 headers.insert("x-api-key", key);
1862 }
1863 let request_id = self.string_at(params, "requestId", "");
1864 if !request_id.is_empty() && request_id.len() <= 200 {
1865 if let Ok(value) = request_id.parse() {
1866 headers.insert("x-request-id", value);
1867 }
1868 }
1869 // a userAgent that is not a valid header value is skipped, like x-request-id
1870 if !self.user_agent.is_empty() {
1871 if let Ok(value) = self.user_agent.parse() {
1872 headers.insert("user-agent", value);
1873 }
1874 }
1875 }
1876 let (socket, _response) = match tokio_tungstenite::connect_async(request).await {
1877 Ok(pair) => pair,
1878 Err(e) => return Err(self.stream_handshake_error(&e.to_string())),
1879 };
1880 let (_write, mut read) = socket.split();
1881 let upper_from = from_asset.to_uppercase();
1882 let upper_to = to_asset.to_uppercase();
1883 let required_full_fill = self.bool_at(params, "requireFullFill", false);
1884 let mut last_frame = Value::Map(HashMap::new());
1885 let mut last_route = Value::Map(HashMap::new());
1886 while let Some(next) = read.next().await {
1887 let message = match next {
1888 Ok(found) => found,
1889 Err(_) => break,
1890 };
1891 match message {
1892 Message::Close(frame) => {
1893 let code = frame.map(|f| u16::from(f.code)).unwrap_or(0);
1894 return match self.stream_close_error(code, &last_frame) {
1895 Some(failure) => Err(failure),
1896 None => Ok(last_route),
1897 };
1898 }
1899 Message::Text(text) => {
1900 let parsed: serde_json::Value = serde_json::from_str(&text)
1901 .map_err(|_| exchange_error("OrderRouter stream sent a non-JSON frame"))?;
1902 let mut frame = Value::from_json(&parsed);
1903 // Held whether or not it looks like a route: a REFUSAL arrives as one
1904 // ordinary frame and only the close code that follows says it was one.
1905 last_frame = frame.clone();
1906 if !self.string_at(&frame, "error", "").is_empty() {
1907 // not a route — wait for the close code to say which refusal it is
1908 continue;
1909 }
1910 // the same client-side stamps fetch_route applies, for the same reason:
1911 // every frame is a route build_execution_plan may be handed
1912 Self::put(&mut frame, "clientRequestedFrom", Value::Str(upper_from.clone().into()));
1913 Self::put(&mut frame, "clientRequestedTo", Value::Str(upper_to.clone().into()));
1914 Self::put(
1915 &mut frame,
1916 "clientRequestedRequireFullFill",
1917 Value::Bool(required_full_fill),
1918 );
1919 last_route = frame.clone();
1920 if on_route(&frame) == "stop" {
1921 return Ok(last_route);
1922 }
1923 }
1924 _ => {
1925 // ping/pong/binary: tungstenite answers pings itself, and this endpoint
1926 // sends nothing binary
1927 }
1928 }
1929 }
1930 // the stream ended without a close frame
1931 match self.stream_close_error(0, &last_frame) {
1932 Some(failure) => Err(failure),
1933 None => Ok(last_route),
1934 }
1935 }
1936
1937 /// Maps a failed websocket upgrade onto the same error the REST path raises for that
1938 /// status. 401, 429 and 503 happen BEFORE the upgrade, so they never arrive as close
1939 /// codes, and the transport reports them only as text.
1940 pub fn stream_handshake_error(&self, message: &str) -> ExchangeError {
1941 if message.contains("401") {
1942 return ExchangeError::new("AuthenticationError", "OrderRouter: unauthorized".to_string());
1943 }
1944 if message.contains("403") {
1945 // same ipv4-only refusal as the REST path, and the same reason not to call it an
1946 // authentication failure: this service has no credential to get wrong
1947 return ExchangeError::new("PermissionDenied", "OrderRouter: the router resolved this client to a non-IPv4 address and refused it; reach it over IPv4".to_string());
1948 }
1949 if message.contains("429") {
1950 return ExchangeError::new("RateLimitExceeded", "OrderRouter: rate limit exceeded".to_string());
1951 }
1952 ExchangeError::new("ExchangeNotAvailable", format!("OrderRouter: {message}"))
1953 }
1954
1955 /// Builds the fully-formed `/route` url, including the query string.
1956 ///
1957 /// Split out from `fetch_route` so the URL construction — the part that has
1958 /// to be byte-identical across six languages — is testable without a
1959 /// network.
1960 pub fn build_route_url(
1961 &self,
1962 from_asset: &str,
1963 to_asset: &str,
1964 params: &Value,
1965 ) -> RouterResult<String> {
1966 if from_asset.is_empty() || to_asset.is_empty() {
1967 return Err(arguments_required("fetchRoute requires fromAsset and toAsset"));
1968 }
1969 Self::assert_route_amounts(params, "fetchRoute")?;
1970 let mut query = format!(
1971 "from={}&to={}",
1972 Self::encode_uri_component(&from_asset.to_uppercase()),
1973 Self::encode_uri_component(&to_asset.to_uppercase())
1974 );
1975 for key in ROUTE_QUERY_KEYS.iter() {
1976 let value = match field(params, key) {
1977 Some(found) => found,
1978 None => continue,
1979 };
1980 let text = self.query_text(value)?;
1981 query.push('&');
1982 query.push_str(key);
1983 query.push('=');
1984 query.push_str(&Self::encode_uri_component(&text));
1985 }
1986 Ok(format!("{}/route?{}", self.base_url, query))
1987 }
1988
1989 /// Builds the `POST /route` JSON body — the same fields as the query
1990 /// string, by the same names.
1991 ///
1992 /// HOLDINGS NEVER TRAVEL IN A URL. The service scrubs balances out of its
1993 /// own logs, but a URL does not stay inside that process: the standard
1994 /// deployment puts a reverse proxy in front, and nginx, an ALB and a CDN all
1995 /// log the full request line by default. So do browser history and
1996 /// client-side tracing, and a `Referer` carries it off-origin. None of that
1997 /// is reachable from the router, and no amount of in-process redaction fixes
1998 /// it — the fix is for the wallet not to be in the URL.
1999 pub fn build_route_body(
2000 &self,
2001 from_asset: &str,
2002 to_asset: &str,
2003 params: &Value,
2004 ) -> RouterResult<Value> {
2005 if from_asset.is_empty() || to_asset.is_empty() {
2006 return Err(arguments_required("fetchRoute requires fromAsset and toAsset"));
2007 }
2008 Self::assert_route_amounts(params, "fetchRoute")?;
2009 let mut body = Value::Dict(Arc::new(HashMap::new()));
2010 Self::put(&mut body, "from", Value::Str(from_asset.to_uppercase().into()));
2011 Self::put(&mut body, "to", Value::Str(to_asset.to_uppercase().into()));
2012 for key in ROUTE_QUERY_KEYS.iter() {
2013 let value = match field(params, key) {
2014 Some(found) => found,
2015 None => continue,
2016 };
2017 // numbers and booleans travel as themselves — the body is JSON and
2018 // the service's own schema types amountIn as a number. Everything
2019 // else uses the same text form the query string uses, so one handler
2020 // reads both verbs.
2021 // balances FIRST, before the number/boolean shortcut: a numeric balances is not
2022 // a wallet, and letting it through as a JSON number sent it to the server to be
2023 // refused there.
2024 let encoded = if *key == "balances" {
2025 Value::Str(self.render_balances(value)?.into())
2026 } else {
2027 match value {
2028 Value::Bool(flag) => Value::Bool(*flag),
2029 Value::Int(n) => Value::Int(*n),
2030 Value::Float(n) => Value::Float(*n),
2031 other => Value::Str(self.query_text(other)?.into()),
2032 }
2033 };
2034 Self::put(&mut body, key, encoded);
2035 }
2036 Ok(body)
2037 }
2038
2039 /// Asks the router how to convert one asset into another, over the venues
2040 /// and bridges it has live books for.
2041 ///
2042 /// An unroutable pair comes back as a RouteResult carrying an
2043 /// `unroutableReason`, NOT as an error: refusing to quote is a deliberate
2044 /// outcome, not a failure.
2045 pub async fn fetch_route(
2046 &self,
2047 from_asset: &str,
2048 to_asset: &str,
2049 params: &Value,
2050 ) -> RouterResult<Value> {
2051 // THE STORED VENUES ANSWER TWO QUESTIONS HERE, and a caller-supplied value wins both.
2052 // `exchanges` is cheap and always right: a route naming a venue you hold no keys for
2053 // is not a route you can take. `balances` reads every venue's wallet, so it happens
2054 // only when venues were installed and the caller supplied none of their own.
2055 let owned_params;
2056 let params = if self.venues.is_empty() {
2057 params
2058 } else {
2059 let mut map = match params.as_map() {
2060 Some(existing) => existing.clone(),
2061 None => HashMap::new(),
2062 };
2063 if field(params, "exchanges").is_none() {
2064 let ids: Vec<String> = self.venues.keys().cloned().collect();
2065 map.insert("exchanges".into(), Value::Str(ids.join(",").into()));
2066 }
2067 if self.track_balances && field(params, "balances").is_none() {
2068 map.insert("balances".into(), Value::Str(self.load_balances(false).await?.into()));
2069 }
2070 owned_params = Value::Map(map);
2071 &owned_params
2072 };
2073 // A request carrying no holdings still goes as a GET: cacheable,
2074 // linkable, and what every existing caller already uses. One that
2075 // carries them is POSTed — see build_route_body for why.
2076 let sends_balances = field(params, "balances").is_some();
2077 // an audit id the caller chose, so their log and the router's decision log can be
2078 // joined. The service mints one when this is absent, and echoes whichever it used.
2079 let request_id = self.string_at(params, "requestId", "");
2080 let mut route = if sends_balances {
2081 let body = self.build_route_body(from_asset, to_asset, params)?;
2082 self.request(&format!("{}/route", self.base_url), "POST", &body, &request_id).await?
2083 } else {
2084 let url = self.build_route_url(from_asset, to_asset, params)?;
2085 self.request(&url, "GET", &Value::Null, &request_id).await?
2086 };
2087 if sends_balances {
2088 // CHECKED HERE, not only in fetch_route_with_balances. `balances` is a
2089 // documented parameter of this method, and a caller who passes it directly was
2090 // getting no verification at all — the same silent failure, one call lower down.
2091 self.assert_balances_applied(&route, params)?;
2092 }
2093 // What THIS CLIENT asked for, stamped client-side so check_execution_plan_safety can
2094 // tell a flag that was honoured from one that was lost in transit. requireFullFill is
2095 // the one route parameter that fails OPEN.
2096 Self::put(
2097 &mut route,
2098 "clientRequestedRequireFullFill",
2099 Value::Bool(self.bool_at(params, "requireFullFill", false)),
2100 );
2101 // Stamp what THIS CLIENT asked for, client-side, so build_execution_plan
2102 // can check the answer against the question. Everything else in the
2103 // response — from, to, pair, side — is the server's word for it, and the
2104 // plan used to trust all of it: a compromised or simply buggy router
2105 // could name any real market and the safety checks, which only test
2106 // internal consistency against that market, would pass it under the
2107 // 25 USD cap.
2108 Self::put(&mut route, "clientRequestedFrom", Value::Str(from_asset.to_uppercase().into()));
2109 Self::put(&mut route, "clientRequestedTo", Value::Str(to_asset.to_uppercase().into()));
2110 Ok(route)
2111 }
2112
2113 /// Errors unless the router confirmed it read the holdings that were sent.
2114 pub fn assert_balances_applied(&self, route: &Value, params: &Value) -> RouterResult<()> {
2115 if !self.bool_at(params, "requireBalancesApplied", true) {
2116 // the caller opted out, with their eyes open
2117 return Ok(());
2118 }
2119 // /route declares its query without a JSON schema, so a router that predates the
2120 // balances feature IGNORES them and answers byte-identically to one that never
2121 // received any.
2122 if !self.string_at(route, "balancesApplied", "").is_empty() {
2123 return Ok(());
2124 }
2125 // An EMPTY echo is ambiguous on its own: "" is also the honest answer to `balances=`
2126 // meaning "I hold nothing". balanceEntryCount disambiguates by PRESENCE, not by
2127 // value — a current server sends 0, a server that never heard of the feature sends
2128 // nothing at all. This is the case the old check skipped outright.
2129 if self.number_at(route, "balanceEntryCount", -1.0) >= 0.0 {
2130 return Ok(());
2131 }
2132 Err(exchange_error(
2133 "OrderRouter did not echo balancesApplied: the balances were ignored, so this route is not funded-aware",
2134 ))
2135 }
2136
2137 /// Renders a retry interval as a message suffix, empty when the service sent
2138 /// none.
2139 fn retry_suffix(retry_after: &str) -> String {
2140 if retry_after.is_empty() {
2141 return String::new();
2142 }
2143 format!(", retry after {retry_after}s")
2144 }
2145
2146 /// Renders the book counts a `cache_cold` refusal carries, so a caller can
2147 /// log why it was refused.
2148 fn cold_cache_suffix(&self, body: &Value) -> String {
2149 let total = self.number_at(body, "bookCount", 0.0);
2150 if total <= 0.0 {
2151 return String::new();
2152 }
2153 let fresh = self.number_at(body, "freshCount", 0.0);
2154 let needed = self.number_at(body, "minFreshBooksForReady", 0.0);
2155 match (
2156 self.format_number(fresh),
2157 self.format_number(total),
2158 self.format_number(needed),
2159 ) {
2160 (Ok(fresh_text), Ok(total_text), Ok(needed_text)) => {
2161 format!(" ({fresh_text} of {total_text} books fresh, {needed_text} needed)")
2162 }
2163 // a count this class cannot render is a count it will not guess at:
2164 // the suffix is dropped whole rather than reporting a number that
2165 // differs from what the other five ports would print
2166 _ => String::new(),
2167 }
2168 }
2169
2170 /// Performs the authenticated call and maps router status codes onto ccxt
2171 /// error kinds.
2172 pub async fn request(
2173 &self,
2174 url: &str,
2175 method: &str,
2176 request_body: &Value,
2177 request_id: &str,
2178 ) -> RouterResult<Value> {
2179 let client = reqwest::Client::builder()
2180 .timeout(std::time::Duration::from_millis(self.timeout_ms.max(0.0) as u64))
2181 .build()
2182 .map_err(|e| ExchangeError::new("ExchangeNotAvailable", format!("OrderRouter could not build an http client: {e}")))?;
2183 let mut builder = if method == "POST" {
2184 client
2185 .post(url)
2186 .header("Content-Type", "application/json")
2187 .body(request_body.to_json().to_string())
2188 } else {
2189 client.get(url)
2190 };
2191 builder = builder.header("Accept", "application/json");
2192 if !self.api_key.is_empty() {
2193 builder = builder.header("x-api-key", &self.api_key);
2194 }
2195 if !request_id.is_empty() && request_id.len() <= 200 {
2196 // the service caps this at 200 characters and mints its own when absent, so a
2197 // longer one is dropped rather than sent and rejected
2198 builder = builder.header("x-request-id", request_id);
2199 }
2200 if !self.user_agent.is_empty() {
2201 // only when configured: an empty value keeps reqwest's own default rather than
2202 // sending a blank one. (Browsers forbid setting User-Agent, so the TS port silently
2203 // drops it there; no such restriction applies here.)
2204 builder = builder.header("User-Agent", &self.user_agent);
2205 }
2206 let response = builder.send().await;
2207 let response = match response {
2208 Ok(found) => found,
2209 Err(e) => {
2210 if e.is_timeout() {
2211 return Err(ExchangeError::new(
2212 "RequestTimeout",
2213 format!("OrderRouter request timed out after {}ms", self.timeout_ms),
2214 ));
2215 }
2216 return Err(ExchangeError::new(
2217 "ExchangeNotAvailable",
2218 format!("OrderRouter request failed: {e}"),
2219 ));
2220 }
2221 };
2222 let status = response.status().as_u16();
2223 // READ BEFORE THE BODY. On a 429 or a 503 this is the only number that
2224 // says how long to wait, and a caller told "unavailable" with no
2225 // interval retries blind.
2226 //
2227 // The two headers are NOT interchangeable and are kept apart on purpose.
2228 // retry-after answers "how long until this particular refusal clears";
2229 // x-ratelimit-reset answers "how long until the rate-limit window rolls
2230 // over", which is the same question ONLY on a 429. Using the window as a
2231 // fallback for a cold cache would tell a caller to wait a full minute for
2232 // a cache that repopulates in seconds.
2233 let header_text = |name: &str| -> String {
2234 response
2235 .headers()
2236 .get(name)
2237 .and_then(|value| value.to_str().ok())
2238 .unwrap_or("")
2239 .to_string()
2240 };
2241 let retry_after = header_text("retry-after");
2242 let rate_limit_reset = header_text("x-ratelimit-reset");
2243 let text = response.text().await.map_err(|e| {
2244 ExchangeError::new("ExchangeNotAvailable", format!("OrderRouter request failed: {e}"))
2245 })?;
2246 let parsed: serde_json::Value = serde_json::from_str(&text)
2247 .map_err(|_| exchange_error("OrderRouter returned a non-JSON body"))?;
2248 let body = Value::from_json(&parsed);
2249 if (200..300).contains(&status) {
2250 return Ok(body);
2251 }
2252 // 404 and 501 carry a complete RouteResult explaining the refusal —
2253 // `no_market` and `exact_out_multi_hop_unsupported` are routing
2254 // outcomes, and turning them into errors would make the caller parse an
2255 // error string to recover a structure it already has.
2256 if (status == 404 || status == 501) && !self.string_at(&body, "unroutableReason", "").is_empty() {
2257 return Ok(body);
2258 }
2259 let message = self.string_at(&body, "error", &format!("http status {status}"));
2260 if status == 503 {
2261 // /ready answers 503 WITH ITS ANSWER: a Readiness body saying
2262 // not_ready and why. That is the result of the probe, not a failure
2263 // of it — erroring would hide the very counts the caller asked for.
2264 // Distinguished by shape, exactly as 404 and 501 are above.
2265 if !self.string_at(&body, "status", "").is_empty() {
2266 return Ok(body);
2267 }
2268 // Every other 503 is cache_cold: the router is alive but has too few
2269 // fresh books to rank on, typically for a few seconds after a restart
2270 // while the connectors repopulate. It is a RETRY, and the generic
2271 // ExchangeError this used to raise made it indistinguishable from a
2272 // permanent server fault.
2273 let cold = self.cold_cache_suffix(&body);
2274 let retry = Self::retry_suffix(&retry_after);
2275 return Err(ExchangeError::new(
2276 "ExchangeNotAvailable",
2277 format!("OrderRouter: {message}{cold}{retry}"),
2278 ));
2279 }
2280 if status == 429 {
2281 // the window rollover IS the retry interval here, so it stands in when
2282 // the service sent no retry-after
2283 let limit_interval = if retry_after.is_empty() { &rate_limit_reset } else { &retry_after };
2284 let retry = Self::retry_suffix(limit_interval);
2285 return Err(ExchangeError::new(
2286 "RateLimitExceeded",
2287 format!("OrderRouter: {message}{retry}"),
2288 ));
2289 }
2290 if status == 403 {
2291 // NOT an authentication failure. The service has no API key; its only 403 is the
2292 // ipv4-only refusal, raised before rate limiting when the resolved client address
2293 // is not a dotted quad. Calling it an auth error sends the caller looking for a
2294 // credential that exists for nobody, while the real remedy goes unsaid.
2295 return Err(ExchangeError::new(
2296 "PermissionDenied",
2297 format!("OrderRouter: {message} — the router resolved this client to a non-IPv4 address and refused it; reach it over IPv4"),
2298 ));
2299 }
2300 let kind = match status {
2301 400 => "BadRequest",
2302 401 => "AuthenticationError",
2303 408 | 504 => "RequestTimeout",
2304 _ => "ExchangeError",
2305 };
2306 Err(ExchangeError::new(kind, format!("OrderRouter: {message}")))
2307 }
2308
2309 /// Liveness only — the service answers 200 from the first millisecond of
2310 /// boot, before a single venue has connected. Use `fetch_readiness` to decide
2311 /// whether the router can actually price anything.
2312 pub async fn fetch_health(&self) -> RouterResult<Value> {
2313 self.request(&format!("{}/health", self.base_url), "GET", &Value::Null, "").await
2314 }
2315
2316 /// Whether the router has enough fresh books to rank on, measured with the
2317 /// same staleness cutoff `/route` uses.
2318 ///
2319 /// NOT_READY IS A NORMAL ANSWER: the service replies 503 with the same body
2320 /// it returns on 200, and this method returns it rather than erroring,
2321 /// because a caller asking "are you ready" needs the counts that say why not.
2322 pub async fn fetch_readiness(&self) -> RouterResult<Value> {
2323 self.request(&format!("{}/ready", self.base_url), "GET", &Value::Null, "").await
2324 }
2325
2326 /// Build provenance of the running process. This is what a deploy pipeline
2327 /// asserts against — `/health` answers 200 from the OLD process just as
2328 /// happily when a deploy silently no-ops, and `commit` is the only field that
2329 /// tells the two apart.
2330 pub async fn fetch_version(&self) -> RouterResult<Value> {
2331 self.request(&format!("{}/version", self.base_url), "GET", &Value::Null, "").await
2332 }
2333
2334 /// The unified symbols the router currently holds a cached book for. A pair
2335 /// absent from this list cannot be routed no matter how it is spelled.
2336 pub async fn fetch_symbols(&self) -> RouterResult<Vec<Value>> {
2337 let response = self.request(&format!("{}/symbols", self.base_url), "GET", &Value::Null, "").await?;
2338 Ok(self.list_at(&response, "symbols"))
2339 }
2340
2341 /// Per-venue connection health. A venue can hold an open socket while its
2342 /// subscription is silently dead, so read the per-venue update age and not
2343 /// only the connected flag.
2344 pub async fn fetch_exchanges_status(&self) -> RouterResult<Vec<Value>> {
2345 let response = self
2346 .request(&format!("{}/exchanges/status", self.base_url), "GET", &Value::Null, "")
2347 .await?;
2348 Ok(self.list_at(&response, "exchanges"))
2349 }
2350
2351 /// The router's own cached L2 book for one venue and symbol — the exact depth
2352 /// a route was ranked on, which is what makes a surprising route auditable.
2353 pub async fn fetch_cached_order_book(&self, exchange_id: &str, symbol: &str) -> RouterResult<Value> {
2354 if exchange_id.is_empty() || symbol.is_empty() {
2355 return Err(arguments_required("fetchCachedOrderBook requires an exchangeId and a symbol"));
2356 }
2357 // the symbol carries a slash and travels as ONE path segment, so it is
2358 // encoded rather than interpolated: BTC/USDT unencoded would read as two
2359 // segments and reach a route that does not exist
2360 let url = format!(
2361 "{}/orderbook/{}/{}",
2362 self.base_url,
2363 Self::encode_uri_component(exchange_id),
2364 Self::encode_uri_component(symbol)
2365 );
2366 self.request(&url, "GET", &Value::Null, "").await
2367 }
2368}
2369
2370// ---------------------------------------------------------------------------
2371// IMPURE: execute
2372// ---------------------------------------------------------------------------
2373
2374/// The strategies `execute` accepts. Anything else is refused before a venue is
2375/// touched, rather than silently falling through to a default.
2376// HOW the orders go out, and nothing else. Whether they go out at all is `dryRun`.
2377const KNOWN_STRATEGIES: [&str; 5] = [
2378 "sequential", "parallel_within_hop", "limit_protected", "best_effort", "atomic_ish",
2379];
2380
2381impl OrderRouter {
2382 /// The stable identity of an execution, used for the re-execution guard.
2383 ///
2384 /// A caller-supplied `idempotencyKey` WINS over the plan's own `requestId`:
2385 /// passing one is a deliberate statement about what this execution is, and it
2386 /// is the only identity a hand-assembled plan can have — `execute` takes any
2387 /// dictionary of the plan shape, not only the output of `build_execution_plan`,
2388 /// and a plan a user built themselves never went through a routing request and
2389 /// so never had a `requestId`. Nothing is invented when both are absent: a
2390 /// generated identity would be either random, which defeats the guard that
2391 /// depends on it, or a fingerprint of the plan's contents, which makes two
2392 /// plans that happen to agree indistinguishable.
2393 pub fn plan_identity(&self, plan: &Value, options: &Value) -> String {
2394 let idempotency_key = self.string_at(options, "idempotencyKey", "");
2395 if !idempotency_key.is_empty() {
2396 return idempotency_key;
2397 }
2398 self.string_at(plan, "requestId", "")
2399 }
2400
2401 /// Counts the distinct hops a step list spans, which is the only authority
2402 /// on whether a plan is multi-hop.
2403 fn hop_count_of(&self, steps: &[Value]) -> usize {
2404 // A vector rather than a set, so the count is the same in six languages
2405 // and does not depend on hash iteration order.
2406 let mut seen: Vec<f64> = Vec::new();
2407 for step in steps {
2408 let hop_index = self.number_at(step, "hopIndex", 0.0);
2409 if !seen.iter().any(|s| *s == hop_index) {
2410 seen.push(hop_index);
2411 }
2412 }
2413 seen.len()
2414 }
2415
2416 /// A deep-enough copy of the plan's steps that resizing them cannot reach
2417 /// back into the caller's plan.
2418 fn clone_steps(&self, plan: &Value) -> Vec<Value> {
2419 let mut copied = Vec::new();
2420 let steps = self.list_at(plan, "steps");
2421 for (i, step) in steps.iter().enumerate() {
2422 // NORMALISE, do not shallow-copy. This used to clone the incoming map field
2423 // for field, which is fine for a plan build_execution_plan produced and wrong
2424 // for every other plan the Manual says execute accepts: a hand-assembled one,
2425 // one that travelled through JSON, or the rebuilt tail of a halted route.
2426 //
2427 // A step carrying no stepIndex then stayed absent, apply_resize reads it as
2428 // -1.0, and reconcile_execution_step only ever names targets >= 0 — so the
2429 // downstream resize matched nothing and silently applied NOTHING. Later hops
2430 // went to the venue at their original unshrunk size, sized for money the
2431 // bridge asset never received, and realisedOut was never written back, so a
2432 // multi-leg hop compounded its scale instead of accumulating the shortfall.
2433 //
2434 // The other five ports have always rebuilt the step here; this is Rust
2435 // catching up to them, field for field.
2436 let mut fresh = HashMap::new();
2437 fresh.insert("stepIndex".into(), Value::Float(self.number_at(step, "stepIndex", i as f64)));
2438 fresh.insert("hopIndex".into(), Value::Float(self.number_at(step, "hopIndex", 0.0)));
2439 fresh.insert("legIndex".into(), Value::Float(self.number_at(step, "legIndex", 0.0)));
2440 fresh.insert("exchangeId".into(), Value::Str(self.string_at(step, "exchangeId", "").into()));
2441 fresh.insert("symbol".into(), Value::Str(self.string_at(step, "symbol", "").into()));
2442 fresh.insert("side".into(), Value::Str(self.string_at(step, "side", "").into()));
2443 fresh.insert("base".into(), Value::Str(self.string_at(step, "base", "").into()));
2444 fresh.insert("quote".into(), Value::Str(self.string_at(step, "quote", "").into()));
2445 fresh.insert("amount".into(), Value::Float(self.number_at(step, "amount", 0.0)));
2446 fresh.insert("expectedPrice".into(), Value::Float(self.number_at(step, "expectedPrice", 0.0)));
2447 fresh.insert("effectivePrice".into(), Value::Float(self.number_at(step, "effectivePrice", 0.0)));
2448 fresh.insert("limitPrice".into(), Value::Float(self.step_limit_price(step)));
2449 fresh.insert("notionalQuote".into(), Value::Float(self.step_notional_quote(step)));
2450 // carried through the clone because execute reconciles against THESE steps,
2451 // not the plan's: without it the fee netting would be measured against a
2452 // gross expectation on every live run
2453 fresh.insert("expectedFeeCost".into(), Value::Float(self.number_at(step, "expectedFeeCost", 0.0)));
2454 copied.push(Value::Map(fresh));
2455 }
2456 copied
2457 }
2458
2459 /// The report skeleton, with one planned result per step.
2460 fn empty_report(
2461 &self,
2462 plan: &Value,
2463 strategy: &str,
2464 dry_run: bool,
2465 steps: &[Value],
2466 ) -> Value {
2467 let mut results = Vec::new();
2468 for step in steps {
2469 let mut result = HashMap::new();
2470 result.insert("stepIndex".into(), Value::Float(self.number_at(step, "stepIndex", -1.0)));
2471 result.insert("hopIndex".into(), Value::Float(self.number_at(step, "hopIndex", 0.0)));
2472 result.insert("legIndex".into(), Value::Float(self.number_at(step, "legIndex", 0.0)));
2473 result.insert("exchangeId".into(), Value::Str(self.string_at(step, "exchangeId", "").into()));
2474 result.insert("symbol".into(), Value::Str(self.string_at(step, "symbol", "").into()));
2475 result.insert("side".into(), Value::Str(self.string_at(step, "side", "").into()));
2476 result.insert("status".into(), Value::Str("planned".into()));
2477 result.insert("requestedAmount".into(), Value::Float(self.number_at(step, "amount", 0.0)));
2478 result.insert("filledAmount".into(), Value::Float(0.0));
2479 result.insert("averagePrice".into(), Value::Float(0.0));
2480 result.insert("cost".into(), Value::Float(0.0));
2481 result.insert("inAsset".into(), Value::Str(Cow::Borrowed("")));
2482 result.insert("inAmount".into(), Value::Float(0.0));
2483 result.insert("outAsset".into(), Value::Str(Cow::Borrowed("")));
2484 result.insert("outAmount".into(), Value::Float(0.0));
2485 result.insert("orderId".into(), Value::Str(Cow::Borrowed("")));
2486 result.insert("clientOrderId".into(), Value::Str(Cow::Borrowed("")));
2487 result.insert("errorCode".into(), Value::Str(Cow::Borrowed("")));
2488 // which retry produced this result; 0 unless retryFailedSteps re-placed it
2489 result.insert("attempt".into(), Value::Float(0.0));
2490 // False until an order is actually dispatched — a failure before
2491 // dispatch cannot have left anything resting on a venue.
2492 result.insert("placementAttempted".into(), Value::Bool(false));
2493 results.push(Value::Map(result));
2494 }
2495 let mut report = HashMap::new();
2496 // A placeholder: execute resolves the real identity from the plan AND the
2497 // options and overwrites it before anything reads this field.
2498 report.insert("planId".into(), Value::Str(Cow::Borrowed("")));
2499 report.insert("strategy".into(), Value::Str(strategy.to_string().into()));
2500 report.insert("dryRun".into(), Value::Bool(dry_run));
2501 report.insert("live".into(), Value::Bool(!dry_run));
2502 report.insert("from".into(), Value::Str(self.string_at(plan, "from", "").into()));
2503 report.insert("to".into(), Value::Str(self.string_at(plan, "to", "").into()));
2504 report.insert("slippageBps".into(), Value::Float(self.number_at(plan, "slippageBps", DEFAULT_SLIPPAGE_BPS)));
2505 report.insert(
2506 "reconcileToleranceRatio".into(),
2507 Value::Float(self.number_at(plan, "reconcileToleranceRatio", DEFAULT_RECONCILE_TOLERANCE)),
2508 );
2509 report.insert("stepCount".into(), Value::Float(steps.len() as f64));
2510 report.insert("wouldPlaceOrders".into(), Value::Float(0.0));
2511 report.insert("ordersPlaced".into(), Value::Float(0.0));
2512 report.insert("halted".into(), Value::Bool(false));
2513 report.insert("haltReason".into(), Value::Str(Cow::Borrowed("")));
2514 report.insert("haltStepIndex".into(), Value::Float(-1.0));
2515 report.insert("filledIn".into(), Value::Float(0.0));
2516 report.insert("filledOut".into(), Value::Float(0.0));
2517 report.insert("steps".into(), Value::List(results));
2518 report.insert("openOrders".into(), Value::List(Vec::new()));
2519 report.insert("errors".into(), Value::List(Vec::new()));
2520 report.insert("reconciliations".into(), Value::List(Vec::new()));
2521 Value::Map(report)
2522 }
2523
2524 /// Appends one entry to a list-valued field of a container.
2525 fn append_to(container: &mut Value, key: &str, entry: Value) {
2526 let mut items = match container.as_map().and_then(|m| m.get(key)) {
2527 Some(Value::Arr(existing)) => existing.as_ref().clone(),
2528 _ => Vec::new(),
2529 };
2530 items.push(entry);
2531 Self::put(container, key, Value::List(items));
2532 }
2533
2534 /// Records an error against the report.
2535 fn record_error(&self, report: &mut Value, step_index: f64, exchange_id: &str, symbol: &str, code: &str) {
2536 let mut entry = HashMap::new();
2537 entry.insert("stepIndex".into(), Value::Float(step_index));
2538 entry.insert("exchangeId".into(), Value::Str(exchange_id.to_string().into()));
2539 entry.insert("symbol".into(), Value::Str(symbol.to_string().into()));
2540 entry.insert("code".into(), Value::Str(code.to_string().into()));
2541 Self::append_to(report, "errors", Value::Map(entry));
2542 }
2543
2544 /// Records an order that may still be resting on a venue.
2545 fn record_open_order(&self, report: &mut Value, exchange_id: &str, symbol: &str, order_id: &str, reason: &str) {
2546 let mut entry = HashMap::new();
2547 entry.insert("exchangeId".into(), Value::Str(exchange_id.to_string().into()));
2548 entry.insert("symbol".into(), Value::Str(symbol.to_string().into()));
2549 entry.insert("orderId".into(), Value::Str(order_id.to_string().into()));
2550 entry.insert("reason".into(), Value::Str(reason.to_string().into()));
2551 Self::append_to(report, "openOrders", Value::Map(entry));
2552 }
2553
2554 /// Records a placement whose outcome is genuinely unknown — the request may
2555 /// or may not have reached the venue, so an order may or may not exist.
2556 fn record_unconfirmed_placement(&self, report: &mut Value, exchange_id: &str, symbol: &str, reason: &str) {
2557 // No order id, because there is none to record: that is the whole
2558 // problem. It goes on openOrders regardless, because the one thing a
2559 // caller must not conclude is that nothing was placed.
2560 self.record_open_order(report, exchange_id, symbol, "", reason);
2561 }
2562
2563 /// Reports whether a thrown error leaves a placement's outcome genuinely
2564 /// unknown.
2565 fn is_outcome_unknown_error(&self, error: &ExchangeError) -> bool {
2566 // Seven names, matched exactly — the same list the other five ports use.
2567 //
2568 // NOT `error.is("NetworkError")`: that walks the hierarchy, and in
2569 // ccxt's tree DDoSProtection, RateLimitExceeded and InvalidNonce are
2570 // all children of NetworkError. Those are the venue ANSWERING — a
2571 // rate-limit rejection is a definite "no order was placed" — so the
2572 // walk reported every throttled request as a possibly-live order,
2573 // halting a route the other five ports complete and sending an
2574 // operator hunting for an order that never existed.
2575 //
2576 // OperationFailed, BadResponse and NullResponse are the other
2577 // direction of the same mistake: the call came back with NO usable
2578 // answer, so an order may well be live. binance maps -1006 — "An
2579 // unexpected response was received from the message bus. Execution
2580 // status unknown." — to OperationFailed on one endpoint and
2581 // BadResponse on another, and both were read as a definite rejection
2582 // and RETRIED under retryFailedSteps.
2583 matches!(
2584 error.kind.as_str(),
2585 "RequestTimeout"
2586 | "ExchangeNotAvailable"
2587 | "NetworkError"
2588 | "OnMaintenance"
2589 | "OperationFailed"
2590 | "BadResponse"
2591 | "NullResponse"
2592 )
2593 }
2594
2595 /// Marks every step from an index onwards as skipped after a halt.
2596 fn mark_remaining_skipped(&self, report: &mut Value, start: usize) {
2597 let mut results = self.list_at(report, "steps");
2598 for result in results.iter_mut().skip(start) {
2599 if self.string_at(result, "status", "") == "planned" {
2600 Self::put(result, "status", Value::Str("skipped".into()));
2601 }
2602 }
2603 Self::put(report, "steps", Value::List(results));
2604 }
2605
2606 /// Totals the report's fills once the loops are done.
2607 fn summarise_report(&self, report: &mut Value, steps: &[Value]) {
2608 let results = self.list_at(report, "steps");
2609 // filledIn is denominated in the route's FROM asset and filledOut in its
2610 // TO asset, which is only true if each is summed over one hop: the first
2611 // and the last. Summing inAmount and outAmount across every step, as
2612 // this port did, adds USDT to BTC to ETH and reports the total as one
2613 // number — meaningless on any route longer than a single hop, and
2614 // meaningless in a way that reads like a figure.
2615 let mut last_hop = 0.0;
2616 for step in steps {
2617 let hop_index = self.number_at(step, "hopIndex", 0.0);
2618 if hop_index > last_hop {
2619 last_hop = hop_index;
2620 }
2621 }
2622 let mut filled_in = 0.0;
2623 let mut filled_out = 0.0;
2624 for result in &results {
2625 let hop_index = self.number_at(result, "hopIndex", 0.0);
2626 if hop_index == 0.0 {
2627 filled_in += self.number_at(result, "inAmount", 0.0);
2628 }
2629 if hop_index == last_hop {
2630 filled_out += self.number_at(result, "outAmount", 0.0);
2631 }
2632 }
2633 // ordersPlaced is NOT recomputed here. It is incremented as each order is
2634 // placed, so it counts an outcome_unknown step too — a status-derived
2635 // recount silently dropped exactly those, which are the placements an
2636 // operator most needs to know about.
2637 Self::put(report, "filledIn", Value::Float(filled_in));
2638 Self::put(report, "filledOut", Value::Float(filled_out));
2639 Self::put(report, "stepCount", Value::Float(steps.len() as f64));
2640 }
2641}
2642
2643impl OrderRouter {
2644 /// Sums the fees an order charged in one asset, ignoring any other currency.
2645 fn order_fee_in_asset(&self, order: &Value, asset: &str) -> f64 {
2646 if asset.is_empty() {
2647 return 0.0;
2648 }
2649 let mut total = 0.0;
2650 // ccxt reports the same cut in up to three places, so this is a strict
2651 // THREE-TIER PRECEDENCE and never a sum across tiers: the `fees` list wins
2652 // outright; if it named no entry in this asset, the single `fee` is read;
2653 // only if that named nothing either are the per-trade fees totalled.
2654 // `saw_in_list` is what makes each tier exclusive of the ones below it —
2655 // safeOrder fills `fee` and `fees` from the same charge, and the per-trade
2656 // fees are usually that same charge again, so adding tiers together would
2657 // double- or triple-count. Within ONE tier every matching entry IS summed.
2658 let fees = self.list_at(order, "fees");
2659 let mut saw_in_list = false;
2660 for entry in &fees {
2661 if self.string_at(entry, "currency", "").to_uppercase() == asset.to_uppercase() {
2662 total += self.number_at(entry, "cost", 0.0);
2663 saw_in_list = true;
2664 }
2665 }
2666 if !saw_in_list {
2667 let single = self.dict_at(order, "fee");
2668 if self.string_at(&single, "currency", "").to_uppercase() == asset.to_uppercase() {
2669 total += self.number_at(&single, "cost", 0.0);
2670 saw_in_list = true;
2671 }
2672 }
2673 if !saw_in_list {
2674 // Last resort: a venue that reports its cut only per trade. The Go
2675 // port has no `fees` list on its typed Order at all, so this
2676 // fallback is what lets all six ports read the same fee off the same
2677 // order — and reading NOTHING here is the dangerous direction, not
2678 // the safe one: an unread fee leaves out_amount GROSS, which sizes
2679 // the next hop on money the venue already took.
2680 let trades = self.list_at(order, "trades");
2681 for trade in &trades {
2682 let trade_fee = self.dict_at(trade, "fee");
2683 if self.string_at(&trade_fee, "currency", "").to_uppercase() == asset.to_uppercase() {
2684 total += self.number_at(&trade_fee, "cost", 0.0);
2685 }
2686 }
2687 }
2688 if !Self::is_finite_number(total) || total < 0.0 {
2689 return 0.0;
2690 }
2691 total
2692 }
2693
2694 /// One re-read of an order the venue answered incompletely, falling back to
2695 /// what we already had rather than losing the placement record.
2696 async fn refetch_order(
2697 &self,
2698 venue: &dyn RouterVenue,
2699 order_id: &str,
2700 symbol: &str,
2701 fallback: Value,
2702 ) -> Value {
2703 match venue.fetch_order(order_id, symbol).await {
2704 Ok(reread) => reread,
2705 // The caller marks the fill unknown; a failure here must not lose
2706 // the placement record.
2707 Err(_) => fallback,
2708 }
2709 }
2710
2711 /// Re-checks the notional cap immediately before a placement, and does
2712 /// nothing at all when the caller never asked for one.
2713 fn assert_under_cap(
2714 &self,
2715 step: &Value,
2716 amount: f64,
2717 price: f64,
2718 usd_rates: &Value,
2719 options: &Value,
2720 ) -> RouterResult<()> {
2721 let cap = self.number_at(options, "maxNotionalUsd", self.max_notional_usd);
2722 if cap <= 0.0 {
2723 // No cap set, so there is nothing to enforce here.
2724 return Ok(());
2725 }
2726 // A PROBE, not the step: `amount` here is the venue-SNAPPED size actually being
2727 // sent, and the step still carries the unsnapped plan amount. notional_usd's
2728 // base-side fallback values the order off `amount`, so passing the step valued the
2729 // wrong quantity — the other five ports have always built this probe.
2730 let mut probe = HashMap::new();
2731 probe.insert("base".to_string(), Value::Str(self.string_at(step, "base", "").into()));
2732 probe.insert("quote".to_string(), Value::Str(self.string_at(step, "quote", "").into()));
2733 probe.insert("amount".to_string(), Value::Float(amount));
2734 let usd_value = self.notional_usd(&Value::Map(probe), amount * price, usd_rates);
2735 if usd_value <= 0.0 {
2736 return Err(exchange_error(
2737 "OrderRouter: refusing to place an order that cannot be valued in USD",
2738 ));
2739 }
2740 if usd_value > cap * (1.0 + TOLERANCE) {
2741 return Err(exchange_error(
2742 "OrderRouter: refusing to place an order above the per-trade USD notional cap",
2743 ));
2744 }
2745 Ok(())
2746 }
2747
2748 /// Places one order for one step and never returns an error, so that a
2749 /// sibling leg's failure cannot abandon an in-flight order.
2750 async fn place_step(
2751 &self,
2752 step: &Value,
2753 venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
2754 options: &Value,
2755 usd_rates: &Value,
2756 strategy: &str,
2757 report: &mut Value,
2758 ) -> Value {
2759 let step_index = self.number_at(step, "stepIndex", -1.0);
2760 let exchange_id = self.string_at(step, "exchangeId", "");
2761 let symbol = self.string_at(step, "symbol", "");
2762 let side = self.string_at(step, "side", "");
2763 let mut result = HashMap::new();
2764 result.insert("stepIndex".into(), Value::Float(step_index));
2765 // Carried from the step, not derived. Without them every result read as
2766 // hopIndex 0, which is what let summarise_report sum a two-hop route's
2767 // spends together — and it is also how a caller tells which hop a result
2768 // belongs to at all.
2769 result.insert("hopIndex".into(), Value::Float(self.number_at(step, "hopIndex", 0.0)));
2770 result.insert("legIndex".into(), Value::Float(self.number_at(step, "legIndex", 0.0)));
2771 result.insert("exchangeId".into(), Value::Str(exchange_id.clone().into()));
2772 result.insert("symbol".into(), Value::Str(symbol.clone().into()));
2773 result.insert("side".into(), Value::Str(side.clone().into()));
2774 result.insert("status".into(), Value::Str("failed".into()));
2775 result.insert("requestedAmount".into(), Value::Float(self.number_at(step, "amount", 0.0)));
2776 result.insert("filledAmount".into(), Value::Float(0.0));
2777 result.insert("averagePrice".into(), Value::Float(0.0));
2778 result.insert("cost".into(), Value::Float(0.0));
2779 result.insert("inAsset".into(), Value::Str(Cow::Borrowed("")));
2780 result.insert("inAmount".into(), Value::Float(0.0));
2781 result.insert("outAsset".into(), Value::Str(Cow::Borrowed("")));
2782 result.insert("outAmount".into(), Value::Float(0.0));
2783 result.insert("orderId".into(), Value::Str(Cow::Borrowed("")));
2784 result.insert("clientOrderId".into(), Value::Str(Cow::Borrowed("")));
2785 result.insert("errorCode".into(), Value::Str(Cow::Borrowed("")));
2786 result.insert("placementAttempted".into(), Value::Bool(false));
2787 let mut result = Value::Map(result);
2788
2789 let venue = match venues.get(&exchange_id) {
2790 Some(found) => found,
2791 None => {
2792 Self::put(&mut result, "errorCode", Value::Str("venue_missing".into()));
2793 self.record_error(report, step_index, &exchange_id, &symbol, "venue_missing");
2794 return result;
2795 }
2796 };
2797 let amount = self.parse_number(&venue.amount_to_precision(&symbol, self.number_at(step, "amount", 0.0)), 0.0);
2798 let price = self.parse_number(&venue.price_to_precision(&symbol, self.step_limit_price(step)), 0.0);
2799 if !(amount > 0.0) || !(price > 0.0) {
2800 Self::put(&mut result, "errorCode", Value::Str("rounded_to_zero".into()));
2801 self.record_error(report, step_index, &exchange_id, &symbol, "rounded_to_zero");
2802 return result;
2803 }
2804 // CLAUDE.md: compute the notional before EVERY createOrder. The
2805 // plan-level check already ran, but the plan can have been resized by a
2806 // reconciliation since, and the snapped price is not the one that was
2807 // checked.
2808 if let Err(e) = self.assert_under_cap(step, amount, price, usd_rates, options) {
2809 // the exception's own class name, exactly as the other five ports record it.
2810 // A hardcoded "over_cap" was wrong twice over: it did not match the five, and
2811 // it labelled the "cannot be valued in USD" refusal — which is not a cap
2812 // breach at all — as though the notional had exceeded the cap.
2813 Self::put(&mut result, "errorCode", Value::Str(e.kind.clone().into()));
2814 self.record_error(report, step_index, &exchange_id, &symbol, &e.kind);
2815 return result;
2816 }
2817 let order_params = self.dict_at(options, "orderParams");
2818 // No clientOrderId is set here. Whatever the caller put in options.orderParams
2819 // travels as-is, and each exchange's create_order keeps sending whatever
2820 // identifier it generates on its own; the id the venue reports back is
2821 // recorded on the result once the order returns. (An id derived from the
2822 // plan identity used to be forced onto every step, but venues disagree on
2823 // its length and charset, so it was rejected exactly where it mattered.)
2824 // The attempt is still recorded: retryFailedSteps re-places a step the venue
2825 // definitively rejected, and the report should say which try produced the result.
2826 let attempt = self.number_at(step, "attempt", 0.0);
2827 Self::put(&mut result, "attempt", Value::Float(attempt));
2828
2829 // Dispatch. `placementAttempted` is set immediately before the call and
2830 // not a line earlier: everything above this point is a refusal that
2831 // cannot have reached a venue.
2832 let order = if strategy == "limit_protected" {
2833 self.place_protected_limit(
2834 venue.as_ref(), step, &symbol, &side, amount, price, &order_params, options,
2835 report, &mut result,
2836 )
2837 .await
2838 } else {
2839 self.place_immediate_order(
2840 venue.as_ref(), &symbol, &side, amount, price, &order_params, options, &mut result,
2841 )
2842 .await
2843 };
2844 let order = match order {
2845 Ok(placed) => {
2846 Self::put(&mut result, "clientOrderId", Value::Str(self.string_at(&placed, "clientOrderId", "").into()));
2847 placed
2848 }
2849 Err(e) => {
2850 Self::put(&mut result, "errorCode", Value::Str(e.kind.clone().into()));
2851 self.record_error(report, step_index, &exchange_id, &symbol, &e.kind);
2852 // createOrder may already have succeeded: every path between it and the final
2853 // read — a poll that times out, a network drop, a cap re-check — leaves a real
2854 // order on a real venue. Reporting the id is the difference between an operator
2855 // who can go cancel it and one who never learns it exists. (This branch was
2856 // missing from the Rust port: a limit_protected order whose poll threw was
2857 // reported as a plain failure with no id anywhere in the report.)
2858 let known_id = self.string_at(&result, "orderId", "");
2859 if !known_id.is_empty() {
2860 // "failed" would read as "nothing happened" while openOrders says the
2861 // opposite, and one report must not carry both readings. Having an id means
2862 // create_order RETURNED — the venue accepted something — so whatever threw
2863 // afterwards left a real order behind whose fill is simply unknown to us.
2864 Self::put(&mut result, "status", Value::Str("outcome_unknown".into()));
2865 self.record_open_order(report, &exchange_id, &symbol, &known_id, "outcome_unknown");
2866 return result;
2867 }
2868 if self.bool_at(&result, "placementAttempted", false) && self.is_outcome_unknown_error(&e) {
2869 // The request may or may not have reached the venue. Halting
2870 // on an unknown quantity is recoverable; concluding that
2871 // nothing was placed is not.
2872 Self::put(&mut result, "status", Value::Str("outcome_unknown".into()));
2873 self.record_unconfirmed_placement(report, &exchange_id, &symbol, "placement_unconfirmed");
2874 }
2875 return result;
2876 }
2877 };
2878 self.settle_order_into_result(&order, step, &mut result, venue.as_ref(), &symbol, &exchange_id, amount, price, report, strategy).await;
2879 result
2880 }
2881}
2882
2883impl OrderRouter {
2884 /// Places an immediate-or-cancel limit order, or — only with explicit
2885 /// opt-in — a market order on a venue that cannot do IOC.
2886 async fn place_immediate_order(
2887 &self,
2888 venue: &dyn RouterVenue,
2889 symbol: &str,
2890 side: &str,
2891 amount: f64,
2892 price: f64,
2893 order_params: &Value,
2894 options: &Value,
2895 result: &mut Value,
2896 ) -> RouterResult<Value> {
2897 if venue.supports_ioc() {
2898 let mut params = order_params.clone();
2899 Self::put(&mut params, "timeInForce", Value::Str("IOC".into()));
2900 // Set immediately before the call that can leave a real order on a
2901 // real venue, and never reset. Anything that fails before this point
2902 // — a missing venue, a size that rounds to zero, the notional cap, a
2903 // venue that cannot do IOC — dispatched nothing, and recording an
2904 // unconfirmed placement for it would be a false alarm.
2905 Self::put(result, "placementAttempted", Value::Bool(true));
2906 let order = venue.create_order(symbol, "limit", side, amount, price, ¶ms).await?;
2907 Self::put(result, "orderId", Value::Str(self.string_at(&order, "id", "").into()));
2908 return Ok(order);
2909 }
2910 if !self.bool_at(options, "allowMarketOrders", false) {
2911 // A market order is an unbounded price, and switching to one on a
2912 // caller's behalf is exactly the decision they did not delegate.
2913 return Err(ExchangeError::new(
2914 "NotSupported",
2915 "OrderRouter: venue cannot do IOC and allowMarketOrders was not set",
2916 ));
2917 }
2918 // A market order and a notional cap cannot both be honoured. assertUnderCap valued this order
2919 // at the plan's LIMIT price, and the call below sends no price at all: the venue fills wherever
2920 // the book is, which is the one thing the cap exists to bound. Passing the check and then
2921 // removing the price it was computed from is a cap that silently disappears, which by this
2922 // file's own rule is not a cap. So the two options are refused together.
2923 if self.number_at(options, "maxNotionalUsd", self.max_notional_usd) > 0.0 {
2924 return Err(ExchangeError::new("NotSupported", "OrderRouter: allowMarketOrders cannot be honoured under a maxNotionalUsd cap, because a market order has no price to check"));
2925 }
2926 Self::put(result, "placementAttempted", Value::Bool(true));
2927 // Price 0 stands for "no price", which is what a market order carries.
2928 let order = venue.create_order(symbol, "market", side, amount, 0.0, order_params).await?;
2929 Self::put(result, "orderId", Value::Str(self.string_at(&order, "id", "").into()));
2930 Ok(order)
2931 }
2932
2933 /// Rests a limit order, then cancels it on timeout and ALWAYS re-reads it,
2934 /// because a cancel and a fill can cross.
2935 #[allow(clippy::too_many_arguments)]
2936 async fn place_protected_limit(
2937 &self,
2938 venue: &dyn RouterVenue,
2939 step: &Value,
2940 symbol: &str,
2941 side: &str,
2942 amount: f64,
2943 price: f64,
2944 order_params: &Value,
2945 options: &Value,
2946 report: &mut Value,
2947 result: &mut Value,
2948 ) -> RouterResult<Value> {
2949 let timeout_ms = self.number_at(options, "orderTimeoutMs", 20000.0);
2950 let poll_interval_ms = self.number_at(options, "pollIntervalMs", 1000.0);
2951 Self::put(result, "placementAttempted", Value::Bool(true));
2952 let mut order = venue.create_order(symbol, "limit", side, amount, price, order_params).await?;
2953 let order_id = self.string_at(&order, "id", "");
2954 // Before the first poll, the first sleep and the first thing that can go
2955 // wrong: from here on the caller can always name what is resting.
2956 Self::put(result, "orderId", Value::Str(order_id.clone().into()));
2957 let mut waited = 0.0;
2958 while waited < timeout_ms {
2959 let status = self.string_at(&order, "status", "");
2960 if status == "closed" || status == "canceled" {
2961 return Ok(order);
2962 }
2963 tokio::time::sleep(std::time::Duration::from_millis(poll_interval_ms.max(0.0) as u64)).await;
2964 waited += poll_interval_ms;
2965 order = venue.fetch_order(&order_id, symbol).await?;
2966 }
2967 let final_status = self.string_at(&order, "status", "");
2968 if final_status == "closed" || final_status == "canceled" {
2969 // The venue ended it on the last poll — an expiry, a self-trade
2970 // prevention, a post-only rejection of the remainder. Cancelling an
2971 // order the venue already closed throws, and the partial fill this
2972 // order carries is real: dropping it would hide a live position from
2973 // the report AND from the unwind plan built out of it.
2974 return Ok(order);
2975 }
2976 if venue.cancel_order(&order_id, symbol).await.is_err() {
2977 // The order may still be live. Reporting a fill we did not observe
2978 // would be a lie, and continuing to the next hop on top of an
2979 // unknown position is worse.
2980 self.record_open_order(report, &self.string_at(step, "exchangeId", ""), symbol, &order_id, "cancel_failed");
2981 return Err(exchange_error(
2982 "OrderRouter: cancelOrder failed and an order is left OPEN, refusing to proceed",
2983 ));
2984 }
2985 // ALWAYS re-read after a cancel: the cancel and the fill can cross, and
2986 // the observed order is the only authority on what actually happened.
2987 venue.fetch_order(&order_id, symbol).await
2988 }
2989
2990 /// Reads a placed order into the step result: the fill, the direction, the
2991 /// fee netting and the status.
2992 #[allow(clippy::too_many_arguments)]
2993 async fn settle_order_into_result(
2994 &self,
2995 order: &Value,
2996 step: &Value,
2997 result: &mut Value,
2998 venue: &dyn RouterVenue,
2999 symbol: &str,
3000 exchange_id: &str,
3001 amount: f64,
3002 price: f64,
3003 report: &mut Value,
3004 strategy: &str,
3005 ) {
3006 let mut order = order.clone();
3007 // "The venue said zero" and "the venue said nothing" are different facts
3008 // and used to produce the same number. A venue that omits `filled`
3009 // yielded 0, reconciliation read that as nothing_filled and halted the
3010 // route — while a real position sat on a real venue. So presence is
3011 // tested, not the value.
3012 let order_id = self.string_at(result, "orderId", "");
3013 if !self.has_number_at(&order, "filled") && !order_id.is_empty() {
3014 // One re-read, exactly as place_protected_limit already does after
3015 // its poll. The immediate path never did, so it could only ever
3016 // fabricate.
3017 order = self.refetch_order(venue, &order_id, symbol, order.clone()).await;
3018 }
3019 // An order the venue explicitly calls open is RESTING, and on this path
3020 // it must not be: place_immediate_order asked for immediate-or-cancel, so
3021 // a venue that silently dropped the timeInForce param has left a plain
3022 // limit order sitting on the book. Recording it and walking on was not
3023 // enough — the next hop then trades on top of a position that keeps
3024 // growing behind it, is sized from a fill that is already out of date, and
3025 // the leftover order is still live after the route has ended and nobody is
3026 // watching it. So it is cancelled and re-read here, exactly as
3027 // place_protected_limit does on its timeout path.
3028 let mut resting_cancel_failed = false;
3029 if strategy != "limit_protected" && self.string_at(&order, "status", "") == "open" && !order_id.is_empty() {
3030 if venue.cancel_order(&order_id, symbol).await.is_err() {
3031 // The order may still be live and its fill can still move, so
3032 // whatever this step reports below is a snapshot that is already
3033 // stale. The status is downgraded after the amounts are filled in,
3034 // not here: a cost the venue DID report is a fact, and
3035 // build_unwind_plan subtracts it.
3036 resting_cancel_failed = true;
3037 } else {
3038 // ALWAYS re-read after a cancel: the cancel and the fill can
3039 // cross, and the observed order is the only authority on what
3040 // actually happened.
3041 order = self.refetch_order(venue, &order_id, symbol, order.clone()).await;
3042 }
3043 }
3044 let filled_known = self.has_number_at(&order, "filled");
3045 let filled = self.number_at(&order, "filled", 0.0);
3046 let average_known = self.has_number_at(&order, "average") || self.has_number_at(&order, "price");
3047 let mut average = self.number_at(&order, "average", 0.0);
3048 if average <= 0.0 {
3049 average = self.number_at(&order, "price", 0.0);
3050 }
3051 if average <= 0.0 {
3052 average = price;
3053 }
3054 let cost_known = self.has_number_at(&order, "cost");
3055 let mut cost = self.number_at(&order, "cost", 0.0);
3056 if cost <= 0.0 {
3057 cost = filled * average;
3058 }
3059 let side = self.string_at(step, "side", "");
3060 Self::put(result, "filledAmount", Value::Float(filled));
3061 Self::put(result, "averagePrice", Value::Float(average));
3062 Self::put(result, "cost", Value::Float(cost));
3063 // Companion flags, per the file's own "was it known" rule. A false here
3064 // means the number beside it is this class's best guess, not the venue's
3065 // answer. This port omitted all three, so a caller reading a Rust report
3066 // could not tell a venue's figure from a fallback.
3067 Self::put(result, "filledKnown", Value::Bool(filled_known));
3068 Self::put(result, "averageKnown", Value::Bool(average_known));
3069 Self::put(result, "costKnown", Value::Bool(cost_known));
3070 if side == "buy" {
3071 Self::put(result, "inAsset", Value::Str(self.string_at(step, "quote", "").into()));
3072 Self::put(result, "inAmount", Value::Float(cost));
3073 Self::put(result, "outAsset", Value::Str(self.string_at(step, "base", "").into()));
3074 Self::put(result, "outAmount", Value::Float(filled));
3075 } else {
3076 Self::put(result, "inAsset", Value::Str(self.string_at(step, "base", "").into()));
3077 Self::put(result, "inAmount", Value::Float(filled));
3078 Self::put(result, "outAsset", Value::Str(self.string_at(step, "quote", "").into()));
3079 Self::put(result, "outAmount", Value::Float(cost));
3080 }
3081 // Net the taker fee out of what is actually CARRIED FORWARD, when the
3082 // venue charged it in the asset this step produced. filled and cost are
3083 // gross of fees — the manual says so — so a venue taking its cut in the
3084 // acquired asset credits less than `filled`, and sizing the next hop (or
3085 // an unwind) on the gross figure orders more than the wallet holds. Fees
3086 // in any OTHER currency are left alone: they do not reduce what this hop
3087 // hands to the next one.
3088 let out_asset = self.string_at(result, "outAsset", "");
3089 let fee_cost = self.order_fee_in_asset(&order, &out_asset);
3090 Self::put(result, "feeCost", Value::Float(fee_cost));
3091 Self::put(result, "feeCurrency", Value::Str(out_asset.into()));
3092 if fee_cost > 0.0 {
3093 let gross = self.number_at(result, "outAmount", 0.0);
3094 let mut net = gross - fee_cost;
3095 if net < 0.0 {
3096 net = 0.0;
3097 }
3098 Self::put(result, "grossOutAmount", Value::Float(gross));
3099 Self::put(result, "outAmount", Value::Float(net));
3100 }
3101 if !filled_known {
3102 // Refuse to reconcile on a fabricated fill: halting on an unknown
3103 // quantity is recoverable, sizing the next hop from an invented
3104 // number is not.
3105 Self::put(result, "status", Value::Str("outcome_unknown".into()));
3106 self.record_open_order(report, exchange_id, symbol, &self.string_at(result, "orderId", ""), "fill_unconfirmed");
3107 // An order WAS placed, and this is exactly the path where knowing
3108 // that matters most. Counted here, as in the other five ports.
3109 Self::put(report, "ordersPlaced", Value::Float(self.number_at(report, "ordersPlaced", 0.0) + 1.0));
3110 return;
3111 }
3112 // No halt on an unknown PRICE. This port had an extra `price_unconfirmed`
3113 // branch that no other has: a fill whose average or cost the venue did
3114 // not report falls back to the order's `price`, then to the limit price,
3115 // and is flagged above rather than stopping the route. The reference
3116 // halts on an unknown FILL — an invented quantity is what makes the next
3117 // hop unsafe — and reports an estimated price as an estimate.
3118 if filled <= 0.0 {
3119 Self::put(result, "status", Value::Str("unfilled".into()));
3120 } else if filled >= amount * (1.0 - TOLERANCE) {
3121 Self::put(result, "status", Value::Str("filled".into()));
3122 } else {
3123 Self::put(result, "status", Value::Str("partial".into()));
3124 }
3125 if resting_cancel_failed {
3126 // A resting order this class could not cancel is the worst outcome
3127 // there is: it can still fill, in full, after the route has returned.
3128 // Sizing the next hop on the fill recorded above would trade against a
3129 // position that is still moving, so the step is marked unknown and
3130 // execute_sequential stops here.
3131 Self::put(result, "status", Value::Str("outcome_unknown".into()));
3132 self.record_open_order(report, exchange_id, symbol, &self.string_at(result, "orderId", ""), "cancel_failed");
3133 } else if self.string_at(&order, "status", "") == "open" {
3134 // Cancelled — or on the limit_protected path, cancelled by
3135 // place_protected_limit — and the venue STILL calls it open. The order
3136 // is live whatever this class asked for, so the same rule applies:
3137 // report it, and refuse to size anything downstream from a fill that
3138 // can still grow.
3139 Self::put(result, "status", Value::Str("outcome_unknown".into()));
3140 self.record_open_order(report, exchange_id, symbol, &self.string_at(result, "orderId", ""), "still_open");
3141 }
3142 Self::put(report, "ordersPlaced", Value::Float(self.number_at(report, "ordersPlaced", 0.0) + 1.0));
3143 }
3144}
3145
3146
3147impl OrderRouter {
3148 /// Places one step, re-placing it up to `options["retryFailedSteps"]` times
3149 /// when — and ONLY when — the venue definitively rejected it.
3150 async fn place_step_with_retry(
3151 &self,
3152 step: &Value,
3153 venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
3154 options: &Value,
3155 usd_rates: &Value,
3156 strategy: &str,
3157 report: &mut Value,
3158 ) -> Value {
3159 let max_retries = self.number_at(options, "retryFailedSteps", 0.0);
3160 let retry_delay_ms = self.number_at(options, "retryDelayMs", DEFAULT_RETRY_DELAY_MS);
3161 let mut attempt = 0.0f64;
3162 loop {
3163 let mut attempted = step.clone();
3164 Self::put(&mut attempted, "attempt", Value::Float(attempt));
3165 let result = self.place_step(&attempted, venues, options, usd_rates, strategy, report).await;
3166 let status = self.string_at(&result, "status", "");
3167 // "failed" is the ONLY retryable outcome, and the distinction is the whole safety
3168 // argument. A failed step was refused by the venue: nothing was placed, so placing
3169 // it again cannot double-fill. An "outcome_unknown" step may ALREADY be a live
3170 // position that simply could not be read back, and re-placing that is precisely the
3171 // double-fill this class exists to prevent. It is never retried, at any setting.
3172 if status != "failed" || attempt >= max_retries {
3173 return result;
3174 }
3175 attempt += 1.0;
3176 if retry_delay_ms > 0.0 {
3177 tokio::time::sleep(std::time::Duration::from_millis(retry_delay_ms.max(0.0) as u64)).await;
3178 }
3179 }
3180 }
3181
3182 /// Hands the caller's `onStep` hook one finished step and returns its
3183 /// verdict, treating any failure of the hook as "no opinion".
3184 ///
3185 /// `options` is taken, and deliberately unused, so that this method reads
3186 /// the same as the other five ports at every call site. In THIS port the
3187 /// hook itself lives on the router (see `OnStepHook`), because `Value`
3188 /// cannot carry a closure.
3189 fn call_on_step(
3190 &self,
3191 options: &Value,
3192 report: &mut Value,
3193 result: &Value,
3194 reconciliation: &Value,
3195 step_index: usize,
3196 steps_total: usize,
3197 ) -> String {
3198 let _ = options;
3199 let hook = match &self.on_step {
3200 Some(found) => Arc::clone(found),
3201 None => return String::new(),
3202 };
3203 let mut event = HashMap::new();
3204 event.insert("planId".to_string(), Value::Str(self.string_at(report, "planId", "").into()));
3205 event.insert("stepIndex".to_string(), Value::Float(step_index as f64));
3206 event.insert("hopIndex".to_string(), Value::Float(self.number_at(result, "hopIndex", 0.0)));
3207 event.insert("legIndex".to_string(), Value::Float(self.number_at(result, "legIndex", 0.0)));
3208 event.insert("exchangeId".to_string(), Value::Str(self.string_at(result, "exchangeId", "").into()));
3209 event.insert("symbol".to_string(), Value::Str(self.string_at(result, "symbol", "").into()));
3210 event.insert("side".to_string(), Value::Str(self.string_at(result, "side", "").into()));
3211 event.insert("status".to_string(), Value::Str(self.string_at(result, "status", "").into()));
3212 event.insert("requestedAmount".to_string(), Value::Float(self.number_at(result, "requestedAmount", 0.0)));
3213 event.insert("filledAmount".to_string(), Value::Float(self.number_at(result, "filledAmount", 0.0)));
3214 event.insert("outAsset".to_string(), Value::Str(self.string_at(result, "outAsset", "").into()));
3215 event.insert("outAmount".to_string(), Value::Float(self.number_at(result, "outAmount", 0.0)));
3216 event.insert("orderId".to_string(), Value::Str(self.string_at(result, "orderId", "").into()));
3217 event.insert("clientOrderId".to_string(), Value::Str(self.string_at(result, "clientOrderId", "").into()));
3218 event.insert("errorCode".to_string(), Value::Str(self.string_at(result, "errorCode", "").into()));
3219 event.insert("attempt".to_string(), Value::Float(self.number_at(result, "attempt", 0.0)));
3220 event.insert("reconciliation".to_string(), reconciliation.clone());
3221 event.insert("ordersPlaced".to_string(), Value::Float(self.number_at(report, "ordersPlaced", 0.0)));
3222 event.insert("halted".to_string(), Value::Bool(self.bool_at(report, "halted", false)));
3223 event.insert("haltReason".to_string(), Value::Str(self.string_at(report, "haltReason", "").into()));
3224 event.insert("stepsTotal".to_string(), Value::Float(steps_total as f64));
3225 event.insert("stepsRemaining".to_string(), Value::Float((steps_total - (step_index + 1)) as f64));
3226 let event = Value::Map(event);
3227 // A hook that PANICS must NOT take the run with it — the Rust form of the try/catch
3228 // the other ports use, and of Go's defer/recover. Everything placed so far is recorded
3229 // in this report, and losing it to a panic raised by observability code would destroy
3230 // the only account of orders that are already live. `catch_unwind` is the right tool
3231 // here and only here: the hook is caller code we make no assumptions about, it is
3232 // handed an owned event and shares no mutable state with the router (hence
3233 // `AssertUnwindSafe`), and the run continues afterwards as if it had no opinion.
3234 // It does NOT contain an abort — a panic=abort profile takes the process down, which
3235 // no language-level construct in any of the six ports can prevent.
3236 let verdict = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| hook(&event)));
3237 match verdict {
3238 Ok(spoken) => {
3239 if spoken == "halt" {
3240 return "halt".to_string();
3241 }
3242 String::new()
3243 }
3244 Err(_) => {
3245 // Rust panics carry no error TYPE to name, unlike the class name the other
3246 // five ports report, so the code is a fixed "panic".
3247 self.record_error(
3248 report,
3249 step_index as f64,
3250 &self.string_at(result, "exchangeId", ""),
3251 &self.string_at(result, "symbol", ""),
3252 "on_step_hook_failed:panic",
3253 );
3254 String::new()
3255 }
3256 }
3257 }
3258}
3259
3260impl OrderRouter {
3261 /// Places one order at a time in plan order, reconciling after each and
3262 /// obeying the halt verdict.
3263 async fn execute_sequential(
3264 &self,
3265 report: &mut Value,
3266 steps: &mut Vec<Value>,
3267 venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
3268 options: &Value,
3269 usd_rates: &Value,
3270 strategy: &str,
3271 ) {
3272 for i in 0..steps.len() {
3273 let step = steps[i].clone();
3274 let result = self.place_step_with_retry(&step, venues, options, usd_rates, strategy, report).await;
3275 let mut results = self.list_at(report, "steps");
3276 results[i] = result.clone();
3277 Self::put(report, "steps", Value::List(results));
3278 let status = self.string_at(&result, "status", "");
3279 if status == "failed" || status == "outcome_unknown" {
3280 Self::put(report, "halted", Value::Bool(true));
3281 // An unknown outcome must NOT fall through to reconciliation:
3282 // reconciling reads outAmount, which is 0 because nothing was
3283 // observed, and reports the halt as "nothing_filled" — asserting
3284 // the one thing we do not know.
3285 let reason = if status == "failed" { "order_failed" } else { "outcome_unknown" };
3286 Self::put(report, "haltReason", Value::Str(reason.into()));
3287 Self::put(report, "haltStepIndex", Value::Float(i as f64));
3288 // the hook is told about a halt it did not cause, and cannot undo it
3289 self.call_on_step(options, report, &result, &Value::Map(HashMap::new()), i, steps.len());
3290 self.mark_remaining_skipped(report, i + 1);
3291 return;
3292 }
3293 let mut reconcile_plan = HashMap::new();
3294 reconcile_plan.insert("steps".to_string(), Value::List(steps.clone()));
3295 reconcile_plan.insert(
3296 "reconcileToleranceRatio".to_string(),
3297 Value::Float(self.number_at(report, "reconcileToleranceRatio", DEFAULT_RECONCILE_TOLERANCE)),
3298 );
3299 let reconciliation = match self.reconcile_execution_step(
3300 &Value::Map(reconcile_plan), i as i64, self.number_at(&result, "outAmount", 0.0),
3301 ) {
3302 Ok(verdict) => verdict,
3303 Err(_) => return,
3304 };
3305 Self::append_to(report, "reconciliations", reconciliation.clone());
3306 if strategy != "atomic_ish" {
3307 // atomic_ish is pre-funded end to end, so a hop's shortfall does
3308 // not shrink the next hop's order — the money for it was already
3309 // there before the first order went out.
3310 self.apply_resize(steps, &reconciliation);
3311 }
3312 if self.string_at(&reconciliation, "verdict", "") == "halt" {
3313 Self::put(report, "halted", Value::Bool(true));
3314 Self::put(report, "haltReason", Value::Str(self.string_at(&reconciliation, "reason", "").into()));
3315 Self::put(report, "haltStepIndex", Value::Float(i as f64));
3316 self.call_on_step(options, report, &result, &reconciliation, i, steps.len());
3317 self.mark_remaining_skipped(report, i + 1);
3318 return;
3319 }
3320 // the caller's own verdict, consulted only once the route is otherwise sound. It
3321 // can stop the route; it cannot restart one the reconciliation above already
3322 // stopped.
3323 if self.call_on_step(options, report, &result, &reconciliation, i, steps.len()) == "halt" {
3324 Self::put(report, "halted", Value::Bool(true));
3325 Self::put(report, "haltReason", Value::Str("halted_by_on_step".into()));
3326 Self::put(report, "haltStepIndex", Value::Float(i as f64));
3327 self.mark_remaining_skipped(report, i + 1);
3328 return;
3329 }
3330 }
3331 }
3332
3333 /// Runs the legs of one hop concurrently ACROSS venues and serially WITHIN
3334 /// a venue, and the hops strictly in order.
3335 async fn execute_parallel_within_hop(
3336 &self,
3337 report: &mut Value,
3338 steps: &mut Vec<Value>,
3339 venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
3340 options: &Value,
3341 usd_rates: &Value,
3342 ) {
3343 let mut cursor = 0usize;
3344 while cursor < steps.len() {
3345 let hop_index = self.number_at(&steps[cursor], "hopIndex", 0.0);
3346 let mut end = cursor;
3347 while end < steps.len() && self.number_at(&steps[end], "hopIndex", 0.0) == hop_index {
3348 end += 1;
3349 }
3350 // THE CONTRACT: concurrent ACROSS venues, serialised WITHIN a venue.
3351 // It is an ordering guarantee, not a performance promise, which is
3352 // what lets six very different runtimes honour the same words. Two
3353 // legs of one hop that land on the SAME venue must never have two
3354 // orders in flight against that venue's throttle and nonce state.
3355 //
3356 // DIVERGENCE, recorded rather than hidden: TypeScript, Python, C#
3357 // and Go run the venue groups concurrently. This port runs them one
3358 // after another. `place_step` takes `&mut Value` for the report, so
3359 // concurrent groups would need the report behind a lock, and a lock
3360 // around every record_error/record_open_order is a great deal of
3361 // machinery to buy back parallelism the contract does not promise.
3362 // Serialising everything satisfies the ordering guarantee strictly
3363 // more than grouping does — it is what the PHP port does, for the
3364 // same reason — so the report is identical either way.
3365 let mut group_ids: Vec<String> = Vec::new();
3366 for i in cursor..end {
3367 let exchange_id = self.string_at(&steps[i], "exchangeId", "");
3368 if !group_ids.contains(&exchange_id) {
3369 group_ids.push(exchange_id);
3370 }
3371 }
3372 for group in &group_ids {
3373 for i in cursor..end {
3374 if self.string_at(&steps[i], "exchangeId", "") != *group {
3375 continue;
3376 }
3377 let step = steps[i].clone();
3378 let result = self
3379 .place_step_with_retry(&step, venues, options, usd_rates, "parallel_within_hop", report)
3380 .await;
3381 let mut results = self.list_at(report, "steps");
3382 results[i] = result;
3383 Self::put(report, "steps", Value::List(results));
3384 }
3385 }
3386 for i in cursor..end {
3387 let results = self.list_at(report, "steps");
3388 let result = results[i].clone();
3389 let status = self.string_at(&result, "status", "");
3390 if status == "failed" || status == "outcome_unknown" {
3391 Self::put(report, "halted", Value::Bool(true));
3392 let reason = if status == "failed" { "order_failed" } else { "outcome_unknown" };
3393 Self::put(report, "haltReason", Value::Str(reason.into()));
3394 Self::put(report, "haltStepIndex", Value::Float(i as f64));
3395 self.call_on_step(options, report, &result, &Value::Map(HashMap::new()), i, steps.len());
3396 self.mark_remaining_skipped(report, end);
3397 return;
3398 }
3399 let mut reconcile_plan = HashMap::new();
3400 reconcile_plan.insert("steps".to_string(), Value::List(steps.clone()));
3401 reconcile_plan.insert(
3402 "reconcileToleranceRatio".to_string(),
3403 Value::Float(self.number_at(report, "reconcileToleranceRatio", DEFAULT_RECONCILE_TOLERANCE)),
3404 );
3405 let reconciliation = match self.reconcile_execution_step(
3406 &Value::Map(reconcile_plan), i as i64, self.number_at(&result, "outAmount", 0.0),
3407 ) {
3408 Ok(verdict) => verdict,
3409 Err(_) => return,
3410 };
3411 Self::append_to(report, "reconciliations", reconciliation.clone());
3412 self.apply_resize(steps, &reconciliation);
3413 if self.string_at(&reconciliation, "verdict", "") == "halt" {
3414 Self::put(report, "halted", Value::Bool(true));
3415 Self::put(report, "haltReason", Value::Str(self.string_at(&reconciliation, "reason", "").into()));
3416 Self::put(report, "haltStepIndex", Value::Float(i as f64));
3417 self.call_on_step(options, report, &result, &reconciliation, i, steps.len());
3418 self.mark_remaining_skipped(report, end);
3419 return;
3420 }
3421 if self.call_on_step(options, report, &result, &reconciliation, i, steps.len()) == "halt" {
3422 Self::put(report, "halted", Value::Bool(true));
3423 Self::put(report, "haltReason", Value::Str("halted_by_on_step".into()));
3424 Self::put(report, "haltStepIndex", Value::Float(i as f64));
3425 self.mark_remaining_skipped(report, end);
3426 return;
3427 }
3428 }
3429 cursor = end;
3430 }
3431 }
3432
3433 /// Places what it can and never halts, on a single hop only, up to
3434 /// maxOrders.
3435 async fn execute_best_effort(
3436 &self,
3437 report: &mut Value,
3438 steps: &mut [Value],
3439 venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
3440 options: &Value,
3441 usd_rates: &Value,
3442 ) {
3443 let max_orders = self.number_at(options, "maxOrders", 0.0);
3444 let mut placed = 0.0;
3445 for i in 0..steps.len() {
3446 let mut results = self.list_at(report, "steps");
3447 if placed >= max_orders {
3448 Self::put(&mut results[i], "status", Value::Str("skipped".into()));
3449 Self::put(&mut results[i], "errorCode", Value::Str("max_orders_reached".into()));
3450 Self::put(report, "steps", Value::List(results));
3451 continue;
3452 }
3453 let step = steps[i].clone();
3454 let result = self.place_step_with_retry(&step, venues, options, usd_rates, "best_effort", report).await;
3455 let mut results = self.list_at(report, "steps");
3456 results[i] = result.clone();
3457 Self::put(report, "steps", Value::List(results));
3458 placed += 1.0;
3459 // No reconciliation and no halt: that is the whole point of the strategy, and why
3460 // it is refused on anything but a single hop. The hook is still offered every step,
3461 // and stopping early is the one thing it may do here — that is a smaller commitment
3462 // than the strategy's own contract, never a larger one.
3463 if self.call_on_step(options, report, &result, &Value::Map(HashMap::new()), i, steps.len()) == "halt" {
3464 Self::put(report, "halted", Value::Bool(true));
3465 Self::put(report, "haltReason", Value::Str("halted_by_on_step".into()));
3466 Self::put(report, "haltStepIndex", Value::Float(i as f64));
3467 self.mark_remaining_skipped(report, i + 1);
3468 return;
3469 }
3470 }
3471 }
3472
3473 /// Executes a plan against live venues. THE ONLY IMPURE METHOD.
3474 ///
3475 /// `dry_run` is the default, and `options.live != true` forces `dry_run`
3476 /// regardless of the strategy requested, so a call that looks live but
3477 /// forgot the flag places nothing.
3478 ///
3479 /// `plan` is a plan from `build_execution_plan`, OR a caller-assembled plan of
3480 /// the same shape — this method never assumes the plan came from the routing
3481 /// service. `options.idempotencyKey` is the identity of this execution,
3482 /// required when the plan carries no `requestId`; it keys the re-execution
3483 /// guard and overrides the plan's `requestId` when both are given.
3484 /// `options.allowReexecution` must be exactly true to run a plan this instance
3485 /// has already executed live; the DEFAULT is refusal.
3486 ///
3487 /// `options.retryFailedSteps` is how many times to re-place a step the venue
3488 /// DEFINITIVELY REJECTED, default 0. An `outcome_unknown` step is never
3489 /// retried at any setting: it may already be a live position, and re-placing
3490 /// it is the double-fill this class exists to prevent. `options.retryDelayMs`
3491 /// is how long to wait before a retry, default `DEFAULT_RETRY_DELAY_MS` (1000).
3492 ///
3493 /// The third option the other five ports read out of `options` — `onStep` —
3494 /// is set on the router instead, by `set_on_step`; `Value` cannot carry a
3495 /// closure. See `OnStepHook`.
3496 pub async fn execute(
3497 &self,
3498 plan: &Value,
3499 venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
3500 options: &Value,
3501 ) -> RouterResult<Value> {
3502 // the argument wins; the router's own venues are the fallback. Nothing is ever
3503 // CONSTRUCTED here - this is the money path.
3504 let venues = if venues.is_empty() { &self.venues } else { venues };
3505 // plan-shaping options cannot be honoured once the plan exists
3506 if !self.list_at(plan, "steps").is_empty() {
3507 self.assert_no_plan_shaping_options(options)?;
3508 }
3509 // A ROUTE is accepted here as well as a plan. buildExecutionPlan is pure and derives
3510 // entirely from the route, so requiring the caller to run it first was ceremony: two
3511 // calls that can only ever happen in that order, with nothing to do in between unless
3512 // you actually want to inspect the plan. Told apart by shape rather than by a flag - a
3513 // route carries `hops`, a plan carries `steps`, and nothing carries both.
3514 let built_from_route;
3515 let plan = if self.list_at(plan, "steps").is_empty() && !self.list_at(plan, "hops").is_empty() {
3516 built_from_route = self.build_execution_plan(plan, options)?;
3517 &built_from_route
3518 } else {
3519 plan
3520 };
3521 let requested_strategy = self.string_at(options, "strategy", "sequential");
3522 if !KNOWN_STRATEGIES.contains(&requested_strategy.as_str()) {
3523 return Err(bad_request(&format!(
3524 "OrderRouter: unknown execution strategy {requested_strategy}"
3525 )));
3526 }
3527 // PLACING IS THE DEFAULT, and ONE knob decides it: `strategy` says only HOW,
3528 // `dryRun` says only WHETHER. The guardrails that do the work all still run
3529 // BEFORE anything is sent.
3530 let strategy = requested_strategy.clone();
3531 // REFUSED, not ignored. `live` was the old knob and it is gone; `live: false` meant
3532 // "place nothing" and now means nothing at all, so ignoring it silently would send
3533 // the orders while the caller believed they had opted out.
3534 if field(options, "live").is_some() {
3535 return Err(bad_request(
3536 "OrderRouter: options.live is gone — execute places orders, and a rehearsal is asked for with dryRun. Remove live, or pass dryRun to place nothing",
3537 ));
3538 }
3539 let dry_run = self.is_exactly_true(options, "dryRun");
3540 let mut steps = self.clone_steps(plan);
3541 let mut report = self.empty_report(plan, &strategy, dry_run, &steps);
3542 // Resolved from BOTH the plan and the options, so a hand-assembled plan can
3543 // carry an identity too; reported on every report, rehearsals included.
3544 let plan_id = self.plan_identity(plan, options);
3545 Self::put(&mut report, "planId", Value::Str(plan_id.clone().into()));
3546 // How old the prices in this plan are. ALWAYS reported, even when nothing is enforced: a plan
3547 // is a snapshot of a book, and how stale that snapshot is decides whether any number in it
3548 // means anything. -1 when the route carried no calculatedAt, which is not the same as "fresh"
3549 // and must not read like it. Enforced only if asked for, at whatever value is asked for — the
3550 // same shape as maxNotionalUsd, and for the same reason. But an age that cannot be determined
3551 // BLOCKS under an active limit: a freshness check that silently passes when the timestamp is
3552 // missing is not a freshness check.
3553 let calculated_at = self.number_at(plan, "calculatedAt", 0.0);
3554 let plan_age_ms = if calculated_at > 0.0 { self.now_ms() - calculated_at } else { -1.0 };
3555 Self::put(&mut report, "planAgeMs", Value::Float(plan_age_ms));
3556 let max_plan_age_ms = self.number_at(options, "maxPlanAgeMs", 0.0);
3557 if !dry_run && max_plan_age_ms > 0.0 {
3558 if plan_age_ms < 0.0 {
3559 return Err(exchange_error("OrderRouter: refusing to execute, the plan carries no calculatedAt and maxPlanAgeMs was set"));
3560 }
3561 if plan_age_ms > max_plan_age_ms {
3562 return Err(exchange_error("OrderRouter: refusing to execute a plan older than maxPlanAgeMs, recompute the route"));
3563 }
3564 }
3565 if dry_run {
3566 // Not one call is made against a venue on this path, not even a read.
3567 Self::put(&mut report, "wouldPlaceOrders", Value::Float(steps.len() as f64));
3568 return Ok(report);
3569 }
3570 if venues.is_empty() {
3571 return Err(arguments_required(
3572 "OrderRouter.execute requires a venues dictionary when live",
3573 ));
3574 }
3575 // IDEMPOTENCY, half one: a plan this instance has already run live is
3576 // REFUSED, and refused here — before a single read reaches a venue. The
3577 // ledger is consulted now and written only once the plan is about to be
3578 // dispatched, so a caller error that placed nothing does not burn the plan.
3579 // dry_run never reaches this line and never consumes a plan, because a
3580 // rehearsal places nothing.
3581 if plan_id.is_empty() {
3582 // No identity means no idempotency: the ledger below cannot key on it,
3583 // so a re-run of this plan would be indistinguishable from a first run.
3584 return Err(bad_request("OrderRouter: refusing to execute live without an identity, the plan carries no requestId — pass options.idempotencyKey"));
3585 }
3586 if !self.bool_at(options, "allowReexecution", false) {
3587 let ledger = self.executed_plan_ids.lock().unwrap();
3588 if ledger.contains(&plan_id) {
3589 return Err(bad_request("OrderRouter: refusing to re-execute a plan this instance already executed, pass allowReexecution to override"));
3590 }
3591 }
3592 // Derived from the steps about to be executed, NEVER read off the plan:
3593 // a plan that travelled through JSON, a persisted step list or a
3594 // hand-rebuilt tail of a halted route can be missing hopCount, and a
3595 // refusal that a missing key switches off is not a refusal.
3596 let hop_count = self.hop_count_of(&steps);
3597 if strategy == "best_effort" {
3598 if hop_count > 1 {
3599 // Best-effort multi-hop is the most reliable way to strand money
3600 // in a bridge asset.
3601 return Err(ExchangeError::new(
3602 "NotSupported",
3603 "OrderRouter: best_effort refuses multi-hop routes",
3604 ));
3605 }
3606 if !self.bool_at(options, "acknowledgeDispersion", false) {
3607 return Err(bad_request("OrderRouter: best_effort requires acknowledgeDispersion"));
3608 }
3609 if self.number_at(options, "maxOrders", 0.0) <= 0.0 {
3610 return Err(bad_request("OrderRouter: best_effort requires a positive maxOrders"));
3611 }
3612 }
3613 if strategy == "limit_protected" {
3614 // Refused HERE, before a single order is placed, because the alternative is worse than a
3615 // bad interval: the poll loop advances its clock by this value, so a zero or negative one
3616 // never reaches the timeout. It spins on fetchOrder forever with a real order resting on a
3617 // real venue, and the timeout that exists to cancel that order never arrives.
3618 if self.has_number_at(options, "pollIntervalMs")
3619 && self.number_at(options, "pollIntervalMs", 0.0) <= 0.0
3620 {
3621 return Err(bad_request("OrderRouter: pollIntervalMs must be positive, a resting order is polled on that clock"));
3622 }
3623 }
3624 // Markets are needed for the safety check and for precision snapping.
3625 // The caller supplies them: unlike the other five ports, this one cannot
3626 // call loadMarkets() through the venue trait — adding it there would put
3627 // a method on the trait that only this line uses, and every implementor
3628 // would have to write it.
3629 let markets = self.dict_at(options, "markets");
3630 let usd_rates = self.dict_at(options, "usdRates");
3631 let mut safety_options = HashMap::new();
3632 safety_options.insert("usdRates".to_string(), usd_rates.clone());
3633 safety_options.insert(
3634 "maxNotionalUsd".to_string(),
3635 Value::Float(self.number_at(options, "maxNotionalUsd", self.max_notional_usd)),
3636 );
3637 safety_options.insert(
3638 "precisionMode".to_string(),
3639 Value::Str(self.string_at(options, "precisionMode", "tick_size").into()),
3640 );
3641 let violations = self.check_execution_plan_safety(plan, &markets, &Value::Map(safety_options));
3642 let mut blockers: Vec<String> = Vec::new();
3643 for violation in &violations {
3644 if self.bool_at(violation, "blocking", false) {
3645 blockers.push(self.string_at(violation, "code", ""));
3646 }
3647 }
3648 if !blockers.is_empty() {
3649 // Returned as an error, not reported. A refusal a caller can forget
3650 // to read is not a refusal.
3651 return Err(exchange_error(&format!(
3652 "OrderRouter: refusing to execute, blocking safety violations: {}{}",
3653 blockers.join(", "),
3654 // notional_unvaluable gets its CAUSE named rather than its symptom: the cap
3655 // and the rates are one guardrail in two parts, and a caller who set
3656 // maxNotionalUsd believes they are protected.
3657 if blockers.iter().any(|code| code == "notional_unvaluable")
3658 && usd_rates.as_map().map(|m| m.is_empty()).unwrap_or(true)
3659 {
3660 " - maxNotionalUsd is set but options.usdRates is empty, and the cap cannot be evaluated without a USD price for the quote currency"
3661 } else {
3662 ""
3663 }
3664 )));
3665 }
3666 if strategy == "atomic_ish" {
3667 // The check the strategy is NAMED for. Without it this port accepted
3668 // atomic_ish, skipped the downstream resize that every other strategy
3669 // performs — on the strength of the route being pre-funded end to
3670 // end — and then never established that it was. A short hop would
3671 // have sized the next one off proceeds it did not have.
3672 self.assert_prefunded(&steps, venues).await?;
3673 }
3674 // The ledger is written BEFORE the first order goes out, never after: a run
3675 // that fails half way through has still placed orders, and a guard that only
3676 // recorded completed runs would wave through exactly the retry that
3677 // double-fills.
3678 {
3679 let mut ledger = self.executed_plan_ids.lock().unwrap();
3680 ledger.record(plan_id.clone());
3681 }
3682 // From here orders go out, so whatever balances were cached are about to be
3683 // wrong. Dropped BEFORE dispatch, for the same reason the ledger is written
3684 // here: a run that fails half way through has still moved money.
3685 self.invalidate_balances();
3686 if strategy == "parallel_within_hop" {
3687 self.execute_parallel_within_hop(&mut report, &mut steps, venues, options, &usd_rates).await;
3688 } else if strategy == "best_effort" {
3689 self.execute_best_effort(&mut report, &mut steps, venues, options, &usd_rates).await;
3690 } else {
3691 // sequential, limit_protected and atomic_ish all walk the plan one
3692 // order at a time; they differ in how a single order is placed and in
3693 // whether they lean on the previous hop's proceeds.
3694 self.execute_sequential(&mut report, &mut steps, venues, options, &usd_rates, &strategy).await;
3695 }
3696 // and AGAIN on the way out: a quote issued while the orders were in flight
3697 // repopulates the cache from wallets that had not settled yet.
3698 self.invalidate_balances();
3699 self.summarise_report(&mut report, &steps);
3700 Ok(report)
3701 }
3702}
3703
3704impl OrderRouter {
3705 /// Verifies every step's input is already sitting on its venue, which is what
3706 /// `atomic_ish` actually requires. There is no cross-venue atomicity and there
3707 /// cannot be, so the strategy names its own hedge: pre-fund the whole route,
3708 /// and no hop then depends on the previous one settling.
3709 ///
3710 /// Most routes fail this, and that is the correct outcome.
3711 async fn assert_prefunded(
3712 &self,
3713 steps: &[Value],
3714 venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
3715 ) -> RouterResult<()> {
3716 // Built as a Vec, not a map, so the first shortfall reported is the same
3717 // one in all six languages.
3718 let mut required: Vec<(String, String, f64)> = Vec::new();
3719 for step in steps {
3720 let exchange_id = self.string_at(step, "exchangeId", "");
3721 let amount = self.number_at(step, "amount", 0.0);
3722 let (asset, needed) = if self.string_at(step, "side", "") == "buy" {
3723 (self.string_at(step, "quote", ""), amount * self.step_limit_price(step))
3724 } else {
3725 (self.string_at(step, "base", ""), amount)
3726 };
3727 let mut found = false;
3728 for entry in required.iter_mut() {
3729 if entry.0 == exchange_id && entry.1 == asset {
3730 entry.2 += needed;
3731 found = true;
3732 break;
3733 }
3734 }
3735 if !found {
3736 required.push((exchange_id, asset, needed));
3737 }
3738 }
3739 // One fetch_balance per venue, cached: a route with four hops on one
3740 // exchange must not cost four balance calls.
3741 let mut balances: HashMap<String, Value> = HashMap::new();
3742 for (exchange_id, asset, needed) in &required {
3743 if !balances.contains_key(exchange_id) {
3744 let venue = match venues.get(exchange_id) {
3745 Some(found) => found,
3746 None => {
3747 return Err(exchange_error(&format!(
3748 "OrderRouter: atomic_ish cannot check funding, no venue was passed for {exchange_id}"
3749 )))
3750 }
3751 };
3752 balances.insert(exchange_id.clone(), venue.fetch_balance().await?);
3753 }
3754 let balance = balances.get(exchange_id).expect("just inserted");
3755 let free = self.dict_at(balance, "free");
3756 let available = self.number_at(&free, asset, 0.0);
3757 if available < *needed {
3758 return Err(insufficient_funds(&format!(
3759 "OrderRouter: atomic_ish requires the whole route pre-funded, and {exchange_id} is short of {asset}"
3760 )));
3761 }
3762 }
3763 Ok(())
3764 }
3765
3766 // NO markets_of HERE, and it is not an omission. The other five ports offer one because
3767 // their venues expose their markets; `RouterVenue` deliberately does not — it is narrowed
3768 // to the operations the money path performs — so Rust's execute reads `options.markets`
3769 // and the caller assembles that dict either way. A helper taking venues would have
3770 // nothing to read.
3771
3772 /// Refuses plan-shaping options alongside an already-built plan, where they cannot apply.
3773 pub fn assert_no_plan_shaping_options(&self, options: &Value) -> RouterResult<()> {
3774 for key in ["slippageBps", "reconcileToleranceRatio"] {
3775 if field(options, key).is_some() {
3776 return Err(bad_request(&format!(
3777 "OrderRouter: {key} shapes a plan and this plan is already built, so it cannot be applied - pass it to build_execution_plan, or hand execute the route instead of the plan"
3778 )));
3779 }
3780 }
3781 Ok(())
3782 }
3783
3784 /// Turns whatever a caller wrote for `balances` into the router's wire form: the rendered
3785 /// string itself, a list of entries, a per-venue wallet, or a flat single-venue wallet.
3786 pub fn render_balances(&self, value: &Value) -> RouterResult<String> {
3787 if let Value::Str(text) = value {
3788 return Ok(text.to_string());
3789 }
3790 if let Value::Arr(_) = value {
3791 return self.query_text(value);
3792 }
3793 match value.as_map() {
3794 Some(map) => {
3795 // Two shapes, told apart by what the values are: a per-venue wallet nests one
3796 // level, a flat wallet does not. Zero holdings are dropped.
3797 let mut outer_keys: Vec<String> = map.keys().cloned().collect();
3798 outer_keys.sort();
3799 let mut entries: Vec<Value> = Vec::new();
3800 for outer in outer_keys.iter() {
3801 let inner = map.get(outer);
3802 let nested = match inner {
3803 Some(found) => found.as_map(),
3804 None => None,
3805 };
3806 if let Some(wallet) = nested {
3807 let mut codes: Vec<String> = wallet.keys().cloned().collect();
3808 codes.sort();
3809 for code in codes.iter() {
3810 let amount = self.number_at(inner.unwrap(), code, 0.0);
3811 if amount > 0.0 {
3812 let mut entry = HashMap::new();
3813 entry.insert("exchangeId".to_string(), Value::Str(outer.clone().into()));
3814 entry.insert("asset".to_string(), Value::Str(code.clone().into()));
3815 entry.insert("amount".to_string(), Value::Float(amount));
3816 entries.push(Value::Map(entry));
3817 }
3818 }
3819 continue;
3820 }
3821 let amount = self.number_at(value, outer, 0.0);
3822 if amount > 0.0 {
3823 // no venue: a bare ASSET:amount means "wherever you hold it"
3824 let mut entry = HashMap::new();
3825 entry.insert("exchangeId".to_string(), Value::Str(Cow::Borrowed("")));
3826 entry.insert("asset".to_string(), Value::Str(outer.clone().into()));
3827 entry.insert("amount".to_string(), Value::Float(amount));
3828 entries.push(Value::Map(entry));
3829 }
3830 }
3831 self.join_balances(&entries)
3832 }
3833 None => Err(bad_request(
3834 "OrderRouter: balances must be \"[exchangeId.]ASSET:amount\" entries, or a wallet like {\"mexc\": {\"USDT\": 100}} or {\"USDT\": 100}",
3835 )),
3836 }
3837 }
3838
3839 pub(crate) fn join_balances(&self, entries: &[Value]) -> RouterResult<String> {
3840 let mut text = String::new();
3841 for (i, entry) in entries.iter().enumerate() {
3842 if i > 0 {
3843 text.push(',');
3844 }
3845 // a bare ASSET:amount, with no venue, means "wherever you hold it"
3846 let venue_prefix = self.string_at(entry, "exchangeId", "");
3847 if !venue_prefix.is_empty() {
3848 text.push_str(&venue_prefix);
3849 text.push('.');
3850 }
3851 text.push_str(&self.string_at(entry, "asset", ""));
3852 text.push(':');
3853 text.push_str(&self.format_number(self.number_at(entry, "amount", 0.0))?);
3854 }
3855 Ok(text)
3856 }
3857
3858 /// Reads the live balances of the supplied venues, sends them to the router,
3859 /// and returns a route you can actually fund.
3860 ///
3861 /// The returned route carries two client-side additions: `balancesUsed`,
3862 /// the exact string sent, and `balancesDropped`, everything that did not fit
3863 /// and why.
3864 /// Reads the venues' wallets once and caches the result, so a quote stays a single HTTP
3865 /// request. Called for you by `fetch_route`; call it yourself to prime the cache at
3866 /// start-up, or with `reload` to refresh it.
3867 pub async fn load_balances(&self, reload: bool) -> RouterResult<String> {
3868 if !self.track_balances || self.venues.is_empty() {
3869 // not this router's job: it was not asked to manage balances
3870 return Ok(String::new());
3871 }
3872 if !reload {
3873 if let Ok(guard) = self.balances_cache.lock() {
3874 if let Some(cached) = guard.as_ref() {
3875 return Ok(cached.clone());
3876 }
3877 }
3878 }
3879 let generation = self
3880 .balances_generation
3881 .load(std::sync::atomic::Ordering::SeqCst);
3882 let (balances, _dropped) = self.collect_balances(&self.venues).await?;
3883 // an invalidation landed while these wallets were being read, which means money
3884 // moved under this snapshot. It is still the right answer for THIS caller, but it
3885 // must not become the cache the next quote trusts.
3886 if generation
3887 == self
3888 .balances_generation
3889 .load(std::sync::atomic::Ordering::SeqCst)
3890 {
3891 if let Ok(mut guard) = self.balances_cache.lock() {
3892 *guard = Some(balances.clone());
3893 }
3894 }
3895 Ok(balances)
3896 }
3897
3898 /// Drops the cached balances, so the next quote re-reads the wallets.
3899 pub fn invalidate_balances(&self) {
3900 self.balances_generation
3901 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
3902 if let Ok(mut guard) = self.balances_cache.lock() {
3903 *guard = None;
3904 }
3905 }
3906
3907 /// Reports whether a balances snapshot is currently cached.
3908 pub fn balances_are_loaded(&self) -> bool {
3909 match self.balances_cache.lock() {
3910 Ok(guard) => guard.is_some(),
3911 Err(_) => false,
3912 }
3913 }
3914
3915 /// Reads every supplied venue's wallet and renders it as the router's balances string,
3916 /// trimmed to the router's caps. Returns the string and the entries that did not fit.
3917 pub async fn collect_balances(
3918 &self,
3919 venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
3920 ) -> RouterResult<(String, Vec<Value>)> {
3921 let mut entries: Vec<Value> = Vec::new();
3922 let mut dropped: Vec<Value> = Vec::new();
3923 // BTreeMap iterates in key order, which is the sort the other five ports
3924 // do explicitly — six languages must build the same string from the same
3925 // wallet.
3926 for (exchange_id, venue) in venues.iter() {
3927 let balance = venue.fetch_balance().await?;
3928 let mut holdings = self.dict_at(&balance, "free");
3929 if holdings.as_map().map(|m| m.is_empty()).unwrap_or(true) {
3930 holdings = self.dict_at(&balance, "total");
3931 }
3932 let mut codes: Vec<String> = match holdings.as_map() {
3933 Some(map) => map.keys().cloned().collect(),
3934 None => Vec::new(),
3935 };
3936 codes.sort();
3937 for code in &codes {
3938 let amount = self.number_at(&holdings, code, 0.0);
3939 if amount <= 0.0 {
3940 // A zero holding is not information, and it costs one of the
3941 // router's 64 entries.
3942 continue;
3943 }
3944 let mut entry = HashMap::new();
3945 entry.insert("exchangeId".to_string(), Value::Str(exchange_id.clone().into()));
3946 entry.insert("asset".to_string(), Value::Str(code.clone().into()));
3947 entry.insert("amount".to_string(), Value::Float(amount));
3948 if amount >= 1e18 {
3949 // Beyond fixed-point rendering; reported rather than sent,
3950 // because a silently reshaped amount is worse than a missing
3951 // one.
3952 entry.insert("reason".to_string(), Value::Str("amount_out_of_range".to_string().into()));
3953 dropped.push(Value::Map(entry));
3954 continue;
3955 }
3956 entries.push(Value::Map(entry));
3957 }
3958 }
3959 // Largest first, so trimming to the router's caps drops the smallest
3960 // holdings. Ties break on exchangeId then asset so six languages produce
3961 // the same list from the same wallet.
3962 entries.sort_by(|a, b| {
3963 let amount_a = self.number_at(a, "amount", 0.0);
3964 let amount_b = self.number_at(b, "amount", 0.0);
3965 if amount_a != amount_b {
3966 // Descending. partial_cmp cannot be None here: number_at only
3967 // ever returns a finite number.
3968 return amount_b.partial_cmp(&amount_a).unwrap_or(std::cmp::Ordering::Equal);
3969 }
3970 let id_a = self.string_at(a, "exchangeId", "");
3971 let id_b = self.string_at(b, "exchangeId", "");
3972 if id_a != id_b {
3973 return id_a.cmp(&id_b);
3974 }
3975 self.string_at(a, "asset", "").cmp(&self.string_at(b, "asset", ""))
3976 });
3977 while entries.len() > MAX_BALANCE_ENTRIES {
3978 let mut removed = entries.pop().expect("entries is non-empty inside this loop");
3979 Self::put(&mut removed, "reason", Value::Str("entry_cap".to_string().into()));
3980 dropped.push(removed);
3981 }
3982 let mut balances = self.join_balances(&entries)?;
3983 while balances.len() > MAX_BALANCE_CHARS && !entries.is_empty() {
3984 let mut removed = entries.pop().expect("entries is non-empty inside this loop");
3985 Self::put(&mut removed, "reason", Value::Str("char_cap".to_string().into()));
3986 dropped.push(removed);
3987 balances = self.join_balances(&entries)?;
3988 }
3989 Ok((balances, dropped))
3990 }
3991
3992 pub async fn fetch_route_with_balances(
3993 &self,
3994 from_asset: &str,
3995 to_asset: &str,
3996 venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
3997 params: &Value,
3998 ) -> RouterResult<Value> {
3999 let require_applied = self.bool_at(params, "requireBalancesApplied", true);
4000 let venues = if venues.is_empty() { &self.venues } else { venues };
4001 let (balances, dropped) = self.collect_balances(venues).await?;
4002 let mut route_params = HashMap::new();
4003 if let Some(map) = params.as_map() {
4004 for (key, value) in map.iter() {
4005 route_params.insert(key.clone(), value.clone());
4006 }
4007 }
4008 route_params.insert("balances".to_string(), Value::Str(balances.clone().into()));
4009 let mut route = self.fetch_route(from_asset, to_asset, &Value::Map(route_params)).await?;
4010 if require_applied && !balances.is_empty() && self.string_at(&route, "balancesApplied", "").is_empty() {
4011 // /route declares its query without a JSON schema, so a router that
4012 // predates the balances feature answers byte-identically to one that
4013 // never received it. Executing a plan computed against a portfolio
4014 // the server never saw is the case worth failing on.
4015 return Err(exchange_error(
4016 "OrderRouter did not echo balancesApplied: the balances were ignored, so this route is not funded-aware",
4017 ));
4018 }
4019 Self::put(&mut route, "balancesUsed", Value::Str(balances.into()));
4020 Self::put(&mut route, "balancesDropped", Value::List(dropped));
4021 Ok(route)
4022 }
4023}