Skip to main content

BotHandle

Struct BotHandle 

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

Cheap cloneable handle into a running Bot.

See the module docs for the host-side contract.

§Example

let config = BotConfig::builder()
    .name("demo")
    .symbol("BTCUSDT")
    .without_signal_handler()
    .build()?;
let bot = Bot::new(config, exchange, brains)?;
let handle: BotHandle = bot.handle();

// Subscribe to non-Hold decisions before the bot starts.
let mut signals = handle.subscribe_signals();

// Drive the bot from one task, observe from another.
let task = tokio::spawn(async move { bot.run_until_shutdown().await });
tokio::spawn({
    let handle = handle.clone();
    async move {
        while let Ok(sig) = signals.recv().await {
            tracing::info!(?sig, "saw a signal");
        }
        handle.shutdown();
    }
});
task.await??;

Implementations§

Source§

impl BotHandle

Source

pub async fn tracked_orders(&self) -> Vec<TrackedOrder>

Snapshot of the resting orders the framework is currently tracking.

Empty unless order tracking is wired via Bot::with_order_tracking and the adapter advertises Capability::OrderTracking.

Source

pub fn shutdown(&self)

Trigger a graceful shutdown. Fire-and-forget; idempotent.

Source

pub fn is_shutting_down(&self) -> bool

Has shutdown been triggered?

Source

pub async fn await_shutdown(&self)

Resolves once shutdown has been triggered by anyone (signal, shutdown() call on this or any other handle clone, or programmatic supervisor cancellation).

Source

pub async fn record_trade_outcome( &self, symbol: &Symbol, gross_pnl: f64, fee: f64, )

Feed a realised trade outcome into the per-symbol risk state.

Called by the host (or a brain) when a position closes. Updates the symbol’s SessionPnl and records a win/loss on the CircuitBreaker based on the net PnL.

Non-finite gross_pnl / fee values are rejected (logged at error level, risk state unchanged) — a NaN would otherwise make the accumulated PnL NaN and permanently disable the loss-limit gate.

Phase 2b does not automate this from the fill stream — that’s FillRoutingService territory in Phase 2c.

Source

pub async fn position(&self, symbol: &Symbol) -> Position

Read the current cached position for a symbol, or Position::FLAT if the symbol isn’t tracked.

Source

pub async fn set_position(&self, symbol: &Symbol, position: Position)

Overwrite the cached position for a symbol. Typically called by the host’s fill-handling code; Phase 2c’s FillRoutingService will do this automatically.

Source

pub fn subscribe_signals(&self) -> Receiver<Signal>

Subscribe to the bot’s signal stream.

The ExecutionService publishes a Signal on every non-Hold decision a brain emits, before the risk gates run. Subscribers see the strategic intent; whether each signal was acted on is observable from order logs and metrics.

The underlying channel is tokio::sync::broadcast, so slow subscribers will see RecvError::Lagged(n) if they fall behind.

§Subscriber lifetime

Because BotHandle keeps a Sender clone alive, the channel does not close when the bot exits. A subscriber that loops on recv() will block forever after shutdown unless it also watches a cancellation signal:

let mut rx = handle.subscribe_signals();
let shutdown = host.shutdown_token();
loop {
    tokio::select! {
        _ = shutdown.cancelled() => break,
        r = rx.recv() => match r {
            Ok(sig) => handle_signal(sig),
            Err(_)  => break,
        },
    }
}
Source

pub fn signal_subscriber_count(&self) -> usize

Number of currently-attached signal subscribers.

Source

pub async fn health(&self) -> BotHealth

Snapshot of bot-wide health.

Trait Implementations§

Source§

impl Clone for BotHandle

Source§

fn clone(&self) -> BotHandle

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 Debug for BotHandle

Source§

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

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