longtrader-worker 0.2.1

Local strategy host running portable strategies against pluggable backends (exchange daemon / terminal API / mock)
Documentation
//! Portable strategies. A strategy depends only on the ports in
//! [`crate::ports`]; backend selection is config-driven.
//!
//! The candle-driven family shares one pattern: each strategy polls candles
//! via [`MarketDataSource::get_candles`](crate::ports::MarketDataSource) and
//! trades through [`TradingGateway`](crate::ports::TradingGateway).
//! Every strategy ships its own `README.md` alongside the module.

pub mod adx_trend;
pub mod amm_arb;
pub mod apt_mm;
pub mod autoborrow;
pub mod avellaneda_mm_v2;
pub mod balance_align;
pub mod basis_mm;
pub mod bb_keltner_squeeze;
pub mod boll_grid;
pub mod bollinger_v2;
pub mod convert;
pub mod cross_depth_maker;
pub mod cross_exchange_mm;
pub mod cross_fixed_maker;
pub mod cross_maker;
pub mod cvd_divergence;
pub mod darvas_box;
pub mod dca_executor;
pub mod dca_scheduler;
pub mod deposit_transfer;
pub mod dman_v3;
pub mod dual_thrust;
pub mod ema_cross;
pub mod fixed_maker;
pub mod glft_mm;
pub mod grid_strike;
pub mod hedge;
pub mod hedge_grid;
pub mod ichimoku;
pub mod irr;
pub mod liquidity_mining;
pub mod macd_bb;
pub mod market_cap;
pub mod mean_reversion;
pub mod momentum_factor;
pub mod nav_recorder;
pub mod obi_mm;
pub mod params;
pub mod perpetual_mm;
pub mod pmm_dynamic;
pub mod premium_monitor;
pub mod pure_market_making;
pub mod queue_mm;
pub mod random_entry;
pub mod rebalance;
pub mod registry;
pub mod sentinel;
pub mod simple_grid;
pub mod simplified_glft_mm;
pub mod skewed_grid;
pub mod spot_perp_arb;
pub mod stat_arb;
pub mod supertrend;
pub mod twap_executor;
pub mod vwap_executor;
pub mod xfunding_lite;

use async_trait::async_trait;
use color_eyre::Result;
use longtrader_contract::ext::decimal_to_common;
pub use params::{CommonParams, CrossVenueParams, VenueRef, params_from_table};
pub(crate) use params::{closes_of, fetch_candles, fetch_closes_of};
pub use registry::{
    StrategyContext, StrategyDescriptor, StrategyFactory, build_strategy, registry,
};
use rust_decimal::Decimal;

use crate::{
    ports::TradingGateway,
    proto::{common, trading},
};

#[async_trait]
pub trait Strategy: Send + Sync {
    /// Called once before `run()` starts. Default implementation does nothing.
    async fn start(&self) -> Result<()> {
        Ok(())
    }

    /// Main strategy loop. Runs until an error occurs or `stop()` is called.
    async fn run(&self) -> Result<()>;

    /// Called once after `run()` exits (whether normally or due to error).
    /// Default implementation does nothing.
    async fn stop(&self) -> Result<()> {
        Ok(())
    }

    /// Request the strategy to pause. Default implementation does nothing.
    async fn pause(&self) -> Result<()> {
        Ok(())
    }

    /// Request the strategy to resume. Default implementation does nothing.
    async fn resume(&self) -> Result<()> {
        Ok(())
    }
}

/// Builds a limit-order create request.
pub(crate) fn limit_order(
    exchange_id: &common::ExchangeId,
    symbol: &str,
    client_order_id: String,
    is_buy: bool,
    price: Decimal,
    qty: Decimal,
) -> trading::CreateOrderRequest {
    order_request(exchange_id, symbol, client_order_id, is_buy, Some(price), qty, false)
}

/// Builds a market-order create request.
pub(crate) fn market_order(
    exchange_id: &common::ExchangeId,
    symbol: &str,
    client_order_id: String,
    is_buy: bool,
    qty: Decimal,
) -> trading::CreateOrderRequest {
    order_request(exchange_id, symbol, client_order_id, is_buy, None, qty, true)
}

/// Midpoint of a two-sided quote.
///
/// Every quoting strategy computed `(bid + ask) / 2` by hand; one owner keeps
/// the arithmetic identical across them and gives the rounding rule a single
/// home if it ever needs to change.
#[must_use]
pub(crate) fn mid_price(bid: Decimal, ask: Decimal) -> Decimal {
    (bid + ask) / Decimal::from(2)
}

/// Cancels every open order of `symbol` on `exchange_id`.
///
/// The request shape is the same in every quoting strategy; building it once
/// keeps the cancel-all semantics (which exchange, which symbol filter) from
/// drifting between them.
///
/// # Errors
///
/// Propagates the venue's refusal.
pub(crate) async fn cancel_all_orders(
    gateway: &dyn TradingGateway,
    exchange_id: &common::ExchangeId,
    symbol: &str,
) -> Result<Vec<trading::Order>, crate::ports::PortError> {
    gateway
        .cancel_all_orders(trading::CancelAllOrdersRequest {
            exchange_id: buffa::MessageField::some(exchange_id.clone()),
            symbol: symbol.to_string(),
            ..Default::default()
        })
        .await
}

#[allow(clippy::too_many_arguments)]
fn order_request(
    exchange_id: &common::ExchangeId,
    symbol: &str,
    client_order_id: String,
    is_buy: bool,
    price: Option<Decimal>,
    qty: Decimal,
    is_market: bool,
) -> trading::CreateOrderRequest {
    trading::CreateOrderRequest {
        exchange_id: buffa::MessageField::some(exchange_id.clone()),
        order: buffa::MessageField::some(trading::OrderRequest {
            client_order_id,
            symbol: symbol.to_string(),
            r#type: buffa::EnumValue::Known(if is_market {
                trading::OrderType::Market
            } else {
                trading::OrderType::Limit
            }),
            side: buffa::EnumValue::Known(if is_buy {
                trading::OrderSide::Buy
            } else {
                trading::OrderSide::Sell
            }),
            amount: buffa::MessageField::some(decimal_to_common(qty)),
            price: price.map(decimal_to_common).map_or_default(buffa::MessageField::some),
            trigger_price: buffa::MessageField::none(),
            time_in_force: buffa::EnumValue::Known(trading::TimeInForce::Gtc),
            post_only: false,
            reduce_only: false,
            params: Default::default(),
            ..Default::default()
        }),
        ..Default::default()
    }
}

#[cfg(test)]
mod tests {
    use rust_decimal_macros::dec;

    use super::*;
    use crate::adapters::MockAdapter;

    /// The midpoint is symmetric and exact: quoting strategies compare their
    /// generated bid/ask against it, so an asymmetric or rounding midpoint
    /// would skew every quote by half a tick.
    #[test]
    fn mid_price_is_symmetric_and_exact() {
        assert_eq!(mid_price(dec!(100), dec!(101)), dec!(100.5));
        assert_eq!(mid_price(dec!(101), dec!(100)), dec!(100.5));
        assert_eq!(mid_price(dec!(7), dec!(7)), dec!(7));
    }

    /// The shared cancel-all must reach the venue with the exchange and symbol
    /// it was given — an empty symbol would cancel the whole account, and a
    /// wrong exchange would silently cancel nothing.
    #[tokio::test]
    async fn cancel_all_orders_targets_the_given_exchange_and_symbol() {
        let mock = std::sync::Arc::new(MockAdapter::new(dec!(100)));
        let exchange = common::ExchangeId {
            id: "binance".to_string(),
            label: String::new(),
            ..Default::default()
        };
        cancel_all_orders(mock.as_ref(), &exchange, "BTC/USDT").await.expect("cancel-all");
        assert_eq!(
            mock.cancel_all_seen().await,
            vec![("binance".to_string(), "BTC/USDT".to_string())]
        );
    }
}