Skip to main content

Engine

Struct Engine 

Source
pub struct Engine<Clock, State, ExecutionTxs, Strategy, Risk> {
    pub clock: Clock,
    pub meta: EngineMeta,
    pub state: State,
    pub execution_txs: ExecutionTxs,
    pub strategy: Strategy,
    pub risk: Risk,
}
Expand description

Algorithmic trading Engine.

The Engine:

  • Processes input EngineEvent (or custom events if implemented).
  • Maintains the internal EngineState (instrument data state, open orders, positions, etc.).
  • Generates algo orders (if TradingState::Enabled).

§Type Parameters

Fields§

§clock: Clock§meta: EngineMeta§state: State§execution_txs: ExecutionTxs§strategy: Strategy§risk: Risk

Implementations§

Source§

impl<Clock, GlobalData, InstrumentData, ExecutionTxs, Strategy, Risk> Engine<Clock, EngineState<GlobalData, InstrumentData>, ExecutionTxs, Strategy, Risk>

Source

pub fn action(&mut self, command: &Command) -> ActionOutput
where InstrumentData: InFlightRequestRecorder, ExecutionTxs: ExecutionTxMap, Strategy: ClosePositionsStrategy<State = EngineState<GlobalData, InstrumentData>>, Risk: RiskManager,

Action an Engine Command, producing an ActionOutput of work done.

Source

pub fn update_from_trading_state_update( &mut self, update: TradingState, ) -> Option<Strategy::OnTradingDisabled>
where Strategy: OnTradingDisabled<Clock, EngineState<GlobalData, InstrumentData>, ExecutionTxs, Risk>,

Update the Engine TradingState.

If the TradingState transitions to TradingState::Disabled, the Engine will call the configured OnTradingDisabled strategy logic.

Source

pub fn update_from_account_stream( &mut self, event: &AccountStreamEvent, ) -> UpdateFromAccountOutput<Strategy::OnDisconnect>
where InstrumentData: for<'a> Processor<&'a AccountEvent>, GlobalData: for<'a> Processor<&'a AccountEvent>, Strategy: OnDisconnectStrategy<Clock, EngineState<GlobalData, InstrumentData>, ExecutionTxs, Risk>,

Update the Engine from an AccountStreamEvent.

If the input AccountStreamEvent indicates the exchange execution link has disconnected, the Engine will call the configured OnDisconnectStrategy strategy logic.

Source

pub fn update_from_market_stream( &mut self, event: &MarketStreamEvent<InstrumentIndex, InstrumentData::MarketEventKind>, ) -> UpdateFromMarketOutput<Strategy::OnDisconnect>
where InstrumentData: InstrumentDataState, GlobalData: for<'a> Processor<&'a MarketEvent<InstrumentIndex, InstrumentData::MarketEventKind>>, Strategy: OnDisconnectStrategy<Clock, EngineState<GlobalData, InstrumentData>, ExecutionTxs, Risk>,

Update the Engine from a MarketStreamEvent.

If the input MarketStreamEvent indicates the exchange market data link has disconnected, the Engine will call the configured OnDisconnectStrategy strategy logic.

Source

pub fn trading_summary_generator( &self, risk_free_return: Decimal, ) -> TradingSummaryGenerator
where Clock: EngineClock,

Returns a TradingSummaryGenerator for the current trading session.

Source

pub fn process_contract_expiry( &mut self, key: &InstrumentIndex, ) -> Vec<PositionExited<AssetIndex, InstrumentIndex>>
where Clock: EngineClock, InstrumentData: InstrumentDataState + InFlightRequestRecorder, ExecutionTxs: ExecutionTxMap,

Processes a ContractExpiry event for the given InstrumentIndex.

§Algorithm
  1. Guards on expiration_processed (idempotent).
  2. Cancels all open orders for the instrument by sending ExecutionRequest::Cancel for each.
  3. Derives settlement price from instrument data and contract specification:
    • OTM: settlement price = 0
    • ITM call: settlement = spot - strike (per-contract intrinsic value)
    • ITM put: settlement = strike - spot (per-contract intrinsic value)
  4. Synthesises a closing Trade at the settlement price and routes it through instrument_state.update_from_trade.
  5. Sets instrument_state.expiration_processed = true.

If no position is open for the instrument, steps 3–4 are skipped. If no market price is available, settlement cannot be computed and the method logs a warning and returns without synthesising a fill. The expiration_processed flag is not set in this case, making the event retryable — re-inject ContractExpiry once the underlying spot instrument has received market data.

§Not modelled (deferred)
  • Assignment for short writers: short positions at expiry are closed at intrinsic value identical to long positions (OTM at 0, ITM at |spot − strike|). True assignment — where the short writer is obligated to deliver the underlying — is not modelled. A future enhancement would detect net-short positions and open a synthetic underlying position instead of (or in addition to) closing the option position.

  • Physical settlement: all settlements are cash-equivalent (a synthetic fill at the settlement price adjusts PnL). No separate “deliver/receive underlying” position is opened. Physically-settled contracts (e.g. some futures-style options) are out of scope until this is revisited.

Source§

impl<Clock, State, ExecutionTxs, Strategy, Risk> Engine<Clock, State, ExecutionTxs, Strategy, Risk>
where Clock: EngineClock,

Source

pub fn new( clock: Clock, state: State, execution_txs: ExecutionTxs, strategy: Strategy, risk: Risk, ) -> Self

Construct a new Engine.

An initial EngineMeta is constructed form the provided clock and Sequence(0).

Source

pub fn time(&self) -> DateTime<Utc>

Return Engine clock time.

Source

pub fn reset_metadata(&mut self)

Reset the internal EngineMeta to the clock time and Sequence(0).

Trait Implementations§

Source§

impl<Audit, Clock, State, ExecutionTxs, Strategy, Risk> Auditor<Audit> for Engine<Clock, State, ExecutionTxs, Strategy, Risk>
where Clock: EngineClock, State: Clone, Strategy: OnTradingDisabled<Clock, State, ExecutionTxs, Risk> + OnDisconnectStrategy<Clock, State, ExecutionTxs, Risk>,

Source§

type Snapshot = State

Full state snapshot.
Source§

type Context = EngineContext

AuditTick context. Read more
Source§

fn audit_snapshot(&mut self) -> AuditTick<Self::Snapshot, Self::Context>

Build an AuditTick containing a full state snapshot.
Source§

fn audit<Kind>(&mut self, kind: Kind) -> AuditTick<Audit, Self::Context>
where Audit: From<Kind>,

Build an AuditTick from the provided Kind.
Source§

impl<Clock, GlobalData, InstrumentData, ExecutionTxs, Strategy, Risk> CancelOrders for Engine<Clock, EngineState<GlobalData, InstrumentData>, ExecutionTxs, Strategy, Risk>
where InstrumentData: InFlightRequestRecorder, ExecutionTxs: ExecutionTxMap,

Source§

impl<Clock: Clone, State: Clone, ExecutionTxs: Clone, Strategy: Clone, Risk: Clone> Clone for Engine<Clock, State, ExecutionTxs, Strategy, Risk>

Source§

fn clone(&self) -> Engine<Clock, State, ExecutionTxs, Strategy, Risk>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<Clock, State, ExecutionTxs, Strategy, Risk, ExchangeKey, AssetKey, InstrumentKey> ClosePositions<ExchangeKey, AssetKey, InstrumentKey> for Engine<Clock, State, ExecutionTxs, Strategy, Risk>
where State: InFlightRequestRecorder<ExchangeKey, InstrumentKey>, ExecutionTxs: ExecutionTxMap<ExchangeKey, InstrumentKey>, Strategy: ClosePositionsStrategy<ExchangeKey, AssetKey, InstrumentKey, State = State>, ExchangeKey: Debug + Clone, InstrumentKey: Debug + Clone,

Source§

fn close_positions( &mut self, filter: &InstrumentFilter<ExchangeKey, AssetKey, InstrumentKey>, ) -> SendCancelsAndOpensOutput<ExchangeKey, InstrumentKey>

Generates and sends order requests to close open positions. Read more
Source§

impl<Clock: Copy, State: Copy, ExecutionTxs: Copy, Strategy: Copy, Risk: Copy> Copy for Engine<Clock, State, ExecutionTxs, Strategy, Risk>

Source§

impl<Clock: Debug, State: Debug, ExecutionTxs: Debug, Strategy: Debug, Risk: Debug> Debug for Engine<Clock, State, ExecutionTxs, Strategy, Risk>

Source§

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

Formats the value using the given formatter. Read more
Source§

impl<Clock: Eq, State: Eq, ExecutionTxs: Eq, Strategy: Eq, Risk: Eq> Eq for Engine<Clock, State, ExecutionTxs, Strategy, Risk>

Source§

impl<Clock, State, ExecutionTxs, Strategy, Risk, ExchangeKey, InstrumentKey> GenerateAlgoOrders<ExchangeKey, InstrumentKey> for Engine<Clock, State, ExecutionTxs, Strategy, Risk>
where State: InFlightRequestRecorder<ExchangeKey, InstrumentKey>, ExecutionTxs: ExecutionTxMap<ExchangeKey, InstrumentKey>, Strategy: AlgoStrategy<ExchangeKey, InstrumentKey, State = State>, Risk: RiskManager<ExchangeKey, InstrumentKey, State = State>, ExchangeKey: Debug + Clone, InstrumentKey: Debug + Clone,

Source§

fn generate_algo_orders( &mut self, ) -> GenerateAlgoOrdersOutput<ExchangeKey, InstrumentKey>

Generates and sends algorithmic order requests. Read more
Source§

impl<Clock: Hash, State: Hash, ExecutionTxs: Hash, Strategy: Hash, Risk: Hash> Hash for Engine<Clock, State, ExecutionTxs, Strategy, Risk>

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<Clock: Ord, State: Ord, ExecutionTxs: Ord, Strategy: Ord, Risk: Ord> Ord for Engine<Clock, State, ExecutionTxs, Strategy, Risk>

Source§

fn cmp( &self, other: &Engine<Clock, State, ExecutionTxs, Strategy, Risk>, ) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<Clock: PartialEq, State: PartialEq, ExecutionTxs: PartialEq, Strategy: PartialEq, Risk: PartialEq> PartialEq for Engine<Clock, State, ExecutionTxs, Strategy, Risk>

Source§

fn eq(&self, other: &Engine<Clock, State, ExecutionTxs, Strategy, Risk>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<Clock: PartialOrd, State: PartialOrd, ExecutionTxs: PartialOrd, Strategy: PartialOrd, Risk: PartialOrd> PartialOrd for Engine<Clock, State, ExecutionTxs, Strategy, Risk>

Source§

fn partial_cmp( &self, other: &Engine<Clock, State, ExecutionTxs, Strategy, Risk>, ) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<Clock, GlobalData, InstrumentData, ExecutionTxs, Strategy, Risk> Processor<EngineEvent<<InstrumentData as InstrumentDataState>::MarketEventKind>> for Engine<Clock, EngineState<GlobalData, InstrumentData>, ExecutionTxs, Strategy, Risk>
where Clock: EngineClock + for<'a> Processor<&'a EngineEvent<InstrumentData::MarketEventKind>>, InstrumentData: InstrumentDataState, GlobalData: for<'a> Processor<&'a AccountEvent> + for<'a> Processor<&'a MarketEvent<InstrumentIndex, InstrumentData::MarketEventKind>>, ExecutionTxs: ExecutionTxMap<ExchangeIndex, InstrumentIndex>, Strategy: OnTradingDisabled<Clock, EngineState<GlobalData, InstrumentData>, ExecutionTxs, Risk> + OnDisconnectStrategy<Clock, EngineState<GlobalData, InstrumentData>, ExecutionTxs, Risk> + AlgoStrategy<State = EngineState<GlobalData, InstrumentData>> + ClosePositionsStrategy<State = EngineState<GlobalData, InstrumentData>>, Risk: RiskManager<State = EngineState<GlobalData, InstrumentData>>,

Source§

type Audit = EngineAudit<EngineEvent<<InstrumentData as InstrumentDataState>::MarketEventKind>, EngineOutput<<Strategy as OnTradingDisabled<Clock, EngineState<GlobalData, InstrumentData>, ExecutionTxs, Risk>>::OnTradingDisabled, <Strategy as OnDisconnectStrategy<Clock, EngineState<GlobalData, InstrumentData>, ExecutionTxs, Risk>>::OnDisconnect>>

Source§

fn process( &mut self, event: EngineEvent<InstrumentData::MarketEventKind>, ) -> Self::Audit

Source§

impl<Clock, State, ExecutionTxs, Strategy, Risk, ExchangeKey, InstrumentKey> SendRequests<ExchangeKey, InstrumentKey> for Engine<Clock, State, ExecutionTxs, Strategy, Risk>
where ExecutionTxs: ExecutionTxMap<ExchangeKey, InstrumentKey>, ExchangeKey: Debug + Clone, InstrumentKey: Debug + Clone,

Source§

fn send_requests<Kind>( &self, requests: impl IntoIterator<Item = OrderEvent<Kind, ExchangeKey, InstrumentKey>>, ) -> SendRequestsOutput<Kind, ExchangeKey, InstrumentKey>
where Kind: Debug + Clone, ExecutionRequest<ExchangeKey, InstrumentKey>: From<OrderEvent<Kind, ExchangeKey, InstrumentKey>>,

Source§

fn send_request<Kind>( &self, request: &OrderEvent<Kind, ExchangeKey, InstrumentKey>, ) -> Result<(), EngineError>
where Kind: Debug + Clone, ExecutionRequest<ExchangeKey, InstrumentKey>: From<OrderEvent<Kind, ExchangeKey, InstrumentKey>>,

Source§

impl<Clock: PartialEq, State: PartialEq, ExecutionTxs: PartialEq, Strategy: PartialEq, Risk: PartialEq> StructuralPartialEq for Engine<Clock, State, ExecutionTxs, Strategy, Risk>

Source§

impl<Clock, GlobalData, InstrumentData, ExecutionTxs, Strategy, Risk> SyncShutdown for Engine<Clock, EngineState<GlobalData, InstrumentData>, ExecutionTxs, Strategy, Risk>
where ExecutionTxs: ExecutionTxMap,

Source§

type Result = ()

Source§

fn shutdown(&mut self) -> Self::Result

Auto Trait Implementations§

§

impl<Clock, State, ExecutionTxs, Strategy, Risk> Freeze for Engine<Clock, State, ExecutionTxs, Strategy, Risk>
where Clock: Freeze, State: Freeze, ExecutionTxs: Freeze, Strategy: Freeze, Risk: Freeze,

§

impl<Clock, State, ExecutionTxs, Strategy, Risk> RefUnwindSafe for Engine<Clock, State, ExecutionTxs, Strategy, Risk>
where Clock: RefUnwindSafe, State: RefUnwindSafe, ExecutionTxs: RefUnwindSafe, Strategy: RefUnwindSafe, Risk: RefUnwindSafe,

§

impl<Clock, State, ExecutionTxs, Strategy, Risk> Send for Engine<Clock, State, ExecutionTxs, Strategy, Risk>
where Clock: Send, State: Send, ExecutionTxs: Send, Strategy: Send, Risk: Send,

§

impl<Clock, State, ExecutionTxs, Strategy, Risk> Sync for Engine<Clock, State, ExecutionTxs, Strategy, Risk>
where Clock: Sync, State: Sync, ExecutionTxs: Sync, Strategy: Sync, Risk: Sync,

§

impl<Clock, State, ExecutionTxs, Strategy, Risk> Unpin for Engine<Clock, State, ExecutionTxs, Strategy, Risk>
where Clock: Unpin, State: Unpin, ExecutionTxs: Unpin, Strategy: Unpin, Risk: Unpin,

§

impl<Clock, State, ExecutionTxs, Strategy, Risk> UnsafeUnpin for Engine<Clock, State, ExecutionTxs, Strategy, Risk>
where Clock: UnsafeUnpin, State: UnsafeUnpin, ExecutionTxs: UnsafeUnpin, Strategy: UnsafeUnpin, Risk: UnsafeUnpin,

§

impl<Clock, State, ExecutionTxs, Strategy, Risk> UnwindSafe for Engine<Clock, State, ExecutionTxs, Strategy, Risk>
where Clock: UnwindSafe, State: UnwindSafe, ExecutionTxs: UnwindSafe, Strategy: UnwindSafe, Risk: UnwindSafe,

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Comparable<K> for Q
where Q: Ord + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn compare(&self, key: &K) -> Ordering

Compare self to key and return their ordering.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.
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