Skip to main content

OrderRouter

Struct OrderRouter 

Source
pub struct OrderRouter { /* private fields */ }
Expand description

A client for the CCXT order-router service.

Implementations§

Source§

impl OrderRouter

Source

pub fn step_limit_price(&self, step: &Value) -> f64

The price a step is sent at, derived from expectedPrice when the caller gave no limitPrice. 0 only when the step has neither field.

build_execution_plan always sets limitPrice, but a HAND-BUILT plan need not: the manual documents it as optional, and the “execute your own plans” path is the whole point of execute taking a plan rather than a route. Reading it as 0 made every such plan fail three different ways — a blocking price_out_of_range from check_execution_plan_safety, a rounded_to_zero before any strategy branch in place_step, and a buy-side balance requirement of amount * 0 — so the documented example could not place one order. expectedPrice is the honest fallback: it is what the caller says the step is worth, and it is already guaranteed positive by the invalid_step guard. A caller wanting a tighter or looser bound sets limitPrice explicitly.

Source

pub fn step_notional_quote(&self, step: &Value) -> f64

The step’s quote-side value, derived from amount and expectedPrice when absent.

Same reasoning as step_limit_price, and the same formula build_execution_plan uses. Read as 0, a hand-built plan tripped the BLOCKING cost_below_minimum on every market declaring a minimum cost.

Source

pub fn number_at(&self, container: &Value, key: &str, default_value: f64) -> f64

Reads a numeric field, with a default for missing, null and unparseable values.

Source

pub fn is_finite_number(value: f64) -> bool

Reports whether a double is a real number, i.e. neither NaN nor an infinity.

Source

pub fn parse_number(&self, text: &str, default_value: f64) -> f64

Reads the leading numeric prefix of a string exactly as JavaScript’s parseFloat does, returning the default when there is not one or when the result is not finite.

Source

pub fn string_at( &self, container: &Value, key: &str, default_value: &str, ) -> String

Reads a string field, with a default for missing and null values.

Source

pub fn is_exactly_true(&self, container: &Value, key: &str) -> bool

Reads a boolean field, with a default for missing and null values. Whether the key holds the boolean true and nothing else. A config that stringifies its booleans must not silently stop trading, so "true" is NOT true here.

Source

pub fn bool_at(&self, container: &Value, key: &str, default_value: bool) -> bool

Source

pub fn list_at(&self, container: &Value, key: &str) -> Vec<Value>

Reads an array field, returning an empty vector when absent. Never None, for the same reason listAt never returns undefined.

Source

pub fn dict_at(&self, container: &Value, key: &str) -> Value

Reads a nested dictionary, returning an empty one when absent.

Source

pub fn format_number(&self, value: f64) -> Result<String, ExchangeError>

Formats a double as decimal text with no exponent, so that six languages produce the same string.

Source§

impl OrderRouter

Source

pub fn new(config: &Value) -> Result<OrderRouter, ExchangeError>

Creates a client for the CCXT order-router service.

config keys: apiKey (optional; the service rate-limits by IP), baseUrl, timeoutMs, maxNotionalUsd (an OPT-IN per-trade USD cap, honoured exactly at whatever value is given; 0 — the default — means NO CAP, and a negative value is refused), userAgent (optional User-Agent header sent with every router request so the service can attribute traffic, e.g. ccxt-mcp/1.2.3 (ccxt 4.5.6); empty — the default — keeps reqwest’s default).

Source

pub fn set_on_step(&mut self, hook: Arc<dyn Fn(&Value) -> String + Sync + Send>)

Installs the onStep hook: called after each step completes and reconciles, never mid-order, with one event describing that step. Return "halt" to stop the route cleanly (haltReason becomes halted_by_on_step); any other value continues. It can only STOP a route, never resume one already halted. Do NO network I/O here — it sits between orders on the money path. A hook that PANICS is recorded as on_step_hook_failed and the run continues, because losing the report would destroy the only account of orders that are already live.

Source

pub fn set_venues(&mut self, venues: BTreeMap<String, Box<dyn RouterVenue>>)

Installs the venues this router trades through. See the venues field for why this is a setter in Rust and a constructor key everywhere else.

Source

pub fn set_track_balances(&mut self, track: bool)

Turns balance tracking on or off. Off (the default), fetch_route never touches a venue and stays a single HTTP request; on, it routes on what you can actually fund.

Source

pub fn clear_venues(&mut self)

Removes the stored venues, so fetch_route stops filtering and funding on them.

Source

pub fn venues(&self) -> &BTreeMap<String, Box<dyn RouterVenue>>

The venues this router holds, empty when none were installed.

Source

pub fn clear_on_step(&mut self)

Removes the onStep hook.

Source

pub fn has_executed_plan(&self, plan_id: &str) -> bool

Reports whether this instance has executed the given plan id recently enough for the bounded ledger to still remember it.

Source

pub fn record_executed_plan(&self, plan_id: &str)

Records one plan id in the bounded ledger, evicting the oldest entry when full.

Source

pub fn executed_plan_count(&self) -> usize

How many plan ids the ledger currently holds, and the id at one position in insertion order. Both exist so the self-test can assert the bound and the eviction order without reaching through the mutex itself.

Source

pub fn executed_plan_at(&self, index: usize) -> String

Source

pub fn set_now_ms(&mut self, now_ms: f64)

Pins the clock, for tests. Production never calls this.

Source

pub fn max_notional_usd(&self) -> f64

The per-trade USD notional cap this client will enforce, or NO_CAP when the caller never asked for one.

Source

pub fn api_key(&self) -> &str

The api key this client carries, empty when it has none. The service is public and needs no key; one supplied anyway is sent as x-api-key, so a deployment fronting the router with its own authentication still works.

Source

pub fn user_agent(&self) -> &str

The User-Agent this client sends, empty when it keeps the http client’s default.

Source

pub fn base_url(&self) -> &str

The router base url, with any trailing slashes removed.

Source

pub fn timeout_ms(&self) -> f64

The configured request timeout, in milliseconds.

Source§

impl OrderRouter

Source

pub fn assert_route_chain_is_coherent( &self, route: &Value, hops: &[Value], ) -> Result<(), ExchangeError>

Refuses a route whose hops do not connect, or that does not run from the asset the caller offered to the asset the caller wanted.

build_execution_plan used to copy from, to, pair and side straight out of the server’s JSON, and the safety checks only tested internal consistency against whatever market that named — so a compromised, or simply buggy, router response could steer real orders into any real market and every check would pass it, under the 25 USD cap.

Source

pub fn build_execution_plan( &self, route: &Value, options: &Value, ) -> Result<Value, ExchangeError>

Turns a RouteResult into an ordered list of concrete orders. PURE — no I/O, and the same input produces the same output in all six languages.

options keys: slippageBps (default 25) and reconcileToleranceRatio (default 0.02).

Source§

impl OrderRouter

Source

pub fn check_execution_plan_safety( &self, plan: &Value, markets: &Value, options: &Value, ) -> Vec<Value>

Checks a plan against per-venue market rules and the hard per-trade USD notional cap. PURE — no I/O. A step that cannot be valued in USD BLOCKS; it is never skipped, because a cap that silently disappears when a rate is missing is not a cap.

markets is markets[exchangeId][symbol].

Source§

impl OrderRouter

Source

pub fn step_expected_out(&self, step: &Value) -> f64

How much of its output asset a step is expected to produce, gross of fees: base units for a buy, quote units for a sell.

Source

pub fn has_number_at(&self, container: &Value, key: &str) -> bool

Reports whether a field holds a usable number, as opposed to holding zero or nothing at all.

“The venue said zero” and “the venue said nothing” are different facts and used to produce the same number. Reuses number_of rather than re-deriving the coercion: “the value is usable” and “the value is present” must never disagree, and two copies of that rule is how they would.

Source

pub fn reconcile_execution_step( &self, plan: &Value, step_index: i64, realised_out: f64, ) -> Result<Value, ExchangeError>

Compares what a step actually produced against what the route predicted, resizes every downstream hop, and returns the proceed-or-halt verdict. PURE — no I/O.

The halt decision lives here rather than in the execution loop because it is a money decision, and six separate loops is six chances to omit it.

Source

pub fn apply_resize(&self, steps: &mut [Value], reconciliation: &Value)

Writes a reconciliation’s downstream resize back into the working steps.

Records what this leg actually produced BEFORE resizing anything. reconcile_execution_step is pure and cannot remember across calls, so the hop’s cumulative shortfall has to live on the steps themselves — this is what stops the next leg of the same hop compounding its scale onto an already-scaled amount.

Source

pub fn set_key(container: &mut Value, key: &str, value: Value)

Sets a key on a Value::Dict in place, through Arc::make_mut so the copy-on-write only deep-copies when the map is actually shared.

Public because callers building a route by hand need it too — stamping clientRequestedFrom/clientRequestedTo onto a route obtained by some route other than fetch_route, for one. The other five ports get this for free from assignment into a dictionary.

Source§

impl OrderRouter

Source

pub fn build_unwind_plan(&self, report: &Value) -> Value

Given a halted execution report, computes the reverse orders that sell each stranded residual back toward the original from-asset, on the venue that actually holds it. PURE — no I/O.

NEVER automatic: the result carries requiresConfirmation and nothing in this class executes it.

Source§

impl OrderRouter

Source

pub fn assert_route_amounts( params: &Value, method: &str, ) -> Result<(), ExchangeError>

Refuses neither-or-both amounts before a byte reaches the wire.

Shared by fetch_route and watch_route because the service runs ONE parser for both and they must not disagree about what is valid.

Source

pub fn stream_url( &self, from_asset: &str, to_asset: &str, params: &Value, ) -> Result<String, ExchangeError>

Builds the wss url for GET /stream/route, refusing what the endpoint refuses.

Source

pub fn stream_close_error( &self, code: u16, last_frame: &Value, ) -> Option<ExchangeError>

Maps a websocket close code onto the error the same refusal raises over REST. None for an ordinary close.

Source

pub async fn watch_route( &self, from_asset: &str, to_asset: &str, params: &Value, on_route: &mut dyn FnMut(&Value) -> String, ) -> Result<Value, ExchangeError>

The same route as fetch_route, pushed over a websocket whenever any market it depends on moves.

BLOCKS until the stream ends: on_route is how you read it. Return "stop" from the hook to close the socket cleanly; the call then returns the last route it saw. Every frame is stamped with the same client-side keys fetch_route stamps, so it can go straight into build_execution_plan.

balances and balanceMode are refused — see stream_url for why — and includeQuotes is left to the endpoint’s own default, which is false here.

Unlike execute’s step hook, this one is a plain parameter rather than something stored on the client: nothing here has to survive in a Value, so the closed-enum workaround set_on_step needs does not apply.

Source

pub fn stream_handshake_error(&self, message: &str) -> ExchangeError

Maps a failed websocket upgrade onto the same error the REST path raises for that status. 401, 429 and 503 happen BEFORE the upgrade, so they never arrive as close codes, and the transport reports them only as text.

Source

pub fn build_route_url( &self, from_asset: &str, to_asset: &str, params: &Value, ) -> Result<String, ExchangeError>

Builds the fully-formed /route url, including the query string.

Split out from fetch_route so the URL construction — the part that has to be byte-identical across six languages — is testable without a network.

Source

pub fn build_route_body( &self, from_asset: &str, to_asset: &str, params: &Value, ) -> Result<Value, ExchangeError>

Builds the POST /route JSON body — the same fields as the query string, by the same names.

HOLDINGS NEVER TRAVEL IN A URL. The service scrubs balances out of its own logs, but a URL does not stay inside that process: the standard deployment puts a reverse proxy in front, and nginx, an ALB and a CDN all log the full request line by default. So do browser history and client-side tracing, and a Referer carries it off-origin. None of that is reachable from the router, and no amount of in-process redaction fixes it — the fix is for the wallet not to be in the URL.

Source

pub async fn fetch_route( &self, from_asset: &str, to_asset: &str, params: &Value, ) -> Result<Value, ExchangeError>

Asks the router how to convert one asset into another, over the venues and bridges it has live books for.

An unroutable pair comes back as a RouteResult carrying an unroutableReason, NOT as an error: refusing to quote is a deliberate outcome, not a failure.

Source

pub fn assert_balances_applied( &self, route: &Value, params: &Value, ) -> Result<(), ExchangeError>

Errors unless the router confirmed it read the holdings that were sent.

Source

pub async fn request( &self, url: &str, method: &str, request_body: &Value, request_id: &str, ) -> Result<Value, ExchangeError>

Performs the authenticated call and maps router status codes onto ccxt error kinds.

Source

pub async fn fetch_health(&self) -> Result<Value, ExchangeError>

Liveness only — the service answers 200 from the first millisecond of boot, before a single venue has connected. Use fetch_readiness to decide whether the router can actually price anything.

Source

pub async fn fetch_readiness(&self) -> Result<Value, ExchangeError>

Whether the router has enough fresh books to rank on, measured with the same staleness cutoff /route uses.

NOT_READY IS A NORMAL ANSWER: the service replies 503 with the same body it returns on 200, and this method returns it rather than erroring, because a caller asking “are you ready” needs the counts that say why not.

Source

pub async fn fetch_version(&self) -> Result<Value, ExchangeError>

Build provenance of the running process. This is what a deploy pipeline asserts against — /health answers 200 from the OLD process just as happily when a deploy silently no-ops, and commit is the only field that tells the two apart.

Source

pub async fn fetch_symbols(&self) -> Result<Vec<Value>, ExchangeError>

The unified symbols the router currently holds a cached book for. A pair absent from this list cannot be routed no matter how it is spelled.

Source

pub async fn fetch_exchanges_status(&self) -> Result<Vec<Value>, ExchangeError>

Per-venue connection health. A venue can hold an open socket while its subscription is silently dead, so read the per-venue update age and not only the connected flag.

Source

pub async fn fetch_cached_order_book( &self, exchange_id: &str, symbol: &str, ) -> Result<Value, ExchangeError>

The router’s own cached L2 book for one venue and symbol — the exact depth a route was ranked on, which is what makes a surprising route auditable.

Source§

impl OrderRouter

Source

pub fn plan_identity(&self, plan: &Value, options: &Value) -> String

The stable identity of an execution, used for the re-execution guard.

A caller-supplied idempotencyKey WINS over the plan’s own requestId: passing one is a deliberate statement about what this execution is, and it is the only identity a hand-assembled plan can have — execute takes any dictionary of the plan shape, not only the output of build_execution_plan, and a plan a user built themselves never went through a routing request and so never had a requestId. Nothing is invented when both are absent: a generated identity would be either random, which defeats the guard that depends on it, or a fingerprint of the plan’s contents, which makes two plans that happen to agree indistinguishable.

Source§

impl OrderRouter

Source

pub async fn execute( &self, plan: &Value, venues: &BTreeMap<String, Box<dyn RouterVenue>>, options: &Value, ) -> Result<Value, ExchangeError>

Executes a plan against live venues. THE ONLY IMPURE METHOD.

dry_run is the default, and options.live != true forces dry_run regardless of the strategy requested, so a call that looks live but forgot the flag places nothing.

plan is a plan from build_execution_plan, OR a caller-assembled plan of the same shape — this method never assumes the plan came from the routing service. options.idempotencyKey is the identity of this execution, required when the plan carries no requestId; it keys the re-execution guard and overrides the plan’s requestId when both are given. options.allowReexecution must be exactly true to run a plan this instance has already executed live; the DEFAULT is refusal.

options.retryFailedSteps is how many times to re-place a step the venue DEFINITIVELY REJECTED, default 0. An outcome_unknown step is never retried at any setting: it may already be a live position, and re-placing it is the double-fill this class exists to prevent. options.retryDelayMs is how long to wait before a retry, default DEFAULT_RETRY_DELAY_MS (1000).

The third option the other five ports read out of options — onStep — is set on the router instead, by set_on_step; Value cannot carry a closure. See OnStepHook.

Source§

impl OrderRouter

Source

pub fn assert_no_plan_shaping_options( &self, options: &Value, ) -> Result<(), ExchangeError>

Refuses plan-shaping options alongside an already-built plan, where they cannot apply.

Source

pub fn render_balances(&self, value: &Value) -> Result<String, ExchangeError>

Turns whatever a caller wrote for balances into the router’s wire form: the rendered string itself, a list of entries, a per-venue wallet, or a flat single-venue wallet.

Source

pub async fn load_balances(&self, reload: bool) -> Result<String, ExchangeError>

Reads the live balances of the supplied venues, sends them to the router, and returns a route you can actually fund.

The returned route carries two client-side additions: balancesUsed, the exact string sent, and balancesDropped, everything that did not fit and why. Reads the venues’ wallets once and caches the result, so a quote stays a single HTTP request. Called for you by fetch_route; call it yourself to prime the cache at start-up, or with reload to refresh it.

Source

pub fn invalidate_balances(&self)

Drops the cached balances, so the next quote re-reads the wallets.

Source

pub fn balances_are_loaded(&self) -> bool

Reports whether a balances snapshot is currently cached.

Source

pub async fn collect_balances( &self, venues: &BTreeMap<String, Box<dyn RouterVenue>>, ) -> Result<(String, Vec<Value>), ExchangeError>

Reads every supplied venue’s wallet and renders it as the router’s balances string, trimmed to the router’s caps. Returns the string and the entries that did not fit.

Source

pub async fn fetch_route_with_balances( &self, from_asset: &str, to_asset: &str, venues: &BTreeMap<String, Box<dyn RouterVenue>>, params: &Value, ) -> Result<Value, ExchangeError>

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more