Skip to main content

UdCore

Struct UdCore 

pub struct UdCore { /* private fields */ }
Expand description

Sans-io core of the user data of ONE account: order state machine, own trades, portfolio.

It links our cid to the exchange order id and the instrument, drops every message that belongs to another account, and turns the rest into events. The connector calls the command methods (begin_place, place_response, …) around its requests, and feeds stream messages through [BrokerCore::on_frame] as UdFrames.

§Examples

use std::time::Instant;
use brokapi_core::{ClientOrderId, InstrumentId, InstrumentKey, NativeId, OrderType, PlaceOrderRequest, Price, Qty, Side};
use brokapi_tbank::core::UdCore;

let mut core = UdCore::new("acc-main");
let sber = InstrumentId::new(InstrumentKey::new("SBER", "TQBR"), NativeId::Uid("uid-sber".into()));
let req = PlaceOrderRequest {
    cid: ClientOrderId::new_v4(),
    instrument: sber,
    side: Side::Buy,
    order_type: OrderType::Limit,
    qty: Qty::from(1),
    price: Some(Price::from(250)),
};

// A cid is registered for one placement at most. The second try is refused before any send.
assert!(core.begin_place(&req, Instant::now()).is_ok());
assert!(core.begin_place(&req, Instant::now()).is_err());
assert!(core.order_state(req.cid).is_some());

Implementations§

§

impl UdCore

pub fn new(account_id: impl Into<String>) -> UdCore

A core for the account account_id. Messages with another account id are dropped.

pub fn lots(&self) -> &Arc<LotBook> ⓘ

The lot sizes this core knows. The connector fills the book before it feeds a message of an instrument it has not met (the messages count in lots, the events in units).

pub fn account_id(&self) -> &str

The account this core serves.

pub fn orders_mut(&mut self) -> &mut OrderRuntime

The order runtime, for the shutdown sequence.

pub fn order_state(&self, cid: Uuid) -> Option<&OrderState>

The state this core holds for cid, or None if it never saw that cid.

pub fn take_forgotten(&mut self) -> Vec<Uuid>

Takes the cids the core forgot since the last call (orders finished long ago, see the memory window of [OrderRuntime]). The connector drops what else it keeps for them.

pub fn take_updates(&mut self) -> Vec<SubUpdate>

Takes the subscription confirmations and refusals since the last call.

pub fn take_reconnected(&mut self) -> Vec<StreamKind>

Streams that were reopened after a break (not the first open). The runtime refreshes order state from GetOrders for OrderState.

pub fn add_sub(&mut self, id: SubscriptionId, kind: UdSubKind)

Registers a subscription of kind under id. A later one of the same kind replaces it.

pub fn remove_sub(&mut self, kind: UdSubKind)

Forgets the subscription of kind, if any.

pub fn sub(&self, kind: UdSubKind) -> Option<SubscriptionId>

The id of the active subscription of kind, if any.

pub fn learn(&mut self, id: &InstrumentId)

Teach the core an instrument (uid/figi -> ticker@class), e.g. the one an order is placed on.

pub fn resolve( &self, uid: &str, figi: &str, ticker: &str, class_code: &str, ) -> InstrumentId

Instrument id from message fields; the ticker is filled from earlier messages when missing.

pub fn begin_place( &mut self, req: &PlaceOrderRequest, now: Instant, ) -> Result<(), Error>

Registers a placement before the request is sent. At most one placement per cid, ever (no automatic retry of place).

pub fn place_response( &mut self, cid: Uuid, resp: &PostOrderResponse, now: Instant, out: &mut EventSink, )

The placement response arrived.

pub fn place_rejected( &mut self, cid: Uuid, reason: String, now: Instant, out: &mut EventSink, )

The broker refused the placement: nothing exists at the broker.

pub fn place_unknown(&mut self, cid: Uuid, now: Instant, out: &mut EventSink)

Timeout or break during place: the outcome is unknown, never Rejected.

pub fn cancel_ok(&mut self, cid: Uuid, now: Instant, out: &mut EventSink)

The broker accepted a cancel.

pub fn begin_replace( &mut self, new_cid: Uuid, original: Uuid, now: Instant, ) -> Result<(), Error>

Registers a replace before the request is sent: the new cid is placed at most once, and it inherits the instrument and side of the original when we know them.

pub fn replace_response( &mut self, new_cid: Uuid, resp: &PostOrderResponse, now: Instant, out: &mut EventSink, )

The broker accepted a replace: the new cid is a new live order.

pub fn replace_failed( &mut self, new_cid: Uuid, unknown: bool, reason: String, now: Instant, out: &mut EventSink, )

The replace failed with a definite refusal or an unknown outcome.

pub fn sweep_timeouts(&mut self, now: Instant, out: &mut EventSink)

Moves the placements that have had no answer for the command timeout to Unknown, one event each. The connector calls it on a timer. It is the safety net: a command normally ends by itself, within the request timeout.

pub fn set_command_timeout(&mut self, timeout: Duration)

Sets how long a placement may wait for its answer before sweep_timeouts gives it up. Keep it above the request timeout of the connector.

pub fn abandon_inflight( &mut self, now: Instant, out: &mut EventSink, ) -> Vec<Uuid>

In-flight placements become Unknown at shutdown, one event each.

pub fn exchange_id(&self, cid: Uuid) -> Option<&str>

Exchange order id of a cid we know (placed here or seen on the stream).

pub fn instrument_of(&self, cid: Uuid) -> Option<InstrumentId>

Instrument of an order we know, for ordering commands per instrument.

pub fn order_basis(&self, cid: Uuid) -> Option<(Qty, Option<Price>)>

Lots and price of an order we know, for building a replace without a round trip.

pub fn note_order(&mut self, parts: &OrderParts)

Learns ids from a GetOrderState / GetOrders answer.

Trait Implementations§

§

impl BrokerCore for UdCore

§

fn poll_transmit(&mut self) -> Option<Outbound>

Streams are server-side and their requests are fixed: nothing to transmit.

§

fn apply(&mut self, desired: &SubscriptionSet)

Takes the order-state and portfolio subscriptions from the set (executions: UdCore::add_sub).

§

type Frame = UdFrame

The inbound frame type: for example String for WebSocket text, or a decoded message.
§

fn on_frame(&mut self, frame: UdFrame, now: Instant, out: &mut EventSink)

Handles one inbound transport frame received at now. Read more
§

fn poll_timeout(&self) -> Option<Instant>

When the core wants on_timeout to be called next, or None if it has no timer pending. Read more
§

fn on_timeout(&mut self, _now: Instant, _out: &mut EventSink)

Handles a timer that fired. now is the time the timer was due.
§

impl Debug for UdCore

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

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
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

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

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

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.

§

impl<T> IntoRequest<T> for T

§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
§

impl<L> LayerExt<L> for L

§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in [Layered].
§

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

§

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
§

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
§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.
§

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

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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