Skip to main content

weirdnet_exchange/
exchange.rs

1//! The adapter traits.
2//!
3//! An adapter for a venue implements [`MarketData`] (public data, no credentials) and, with
4//! credentials, [`Trading`]. Anything that implements both is an [`Exchange`]. Apps hold
5//! `Arc<dyn Exchange>` (or the narrower trait) and don't care which venue is behind it;
6//! [`crate::Paper`] is the in-memory one for tests and dry runs.
7//!
8//! Placing is idempotent per [`ClientOrderId`]: placing the same request again returns the
9//! first acknowledgement instead of a second order, so a placement whose outcome is unknown
10//! (a timeout) can be retried. Adapters for venues without that guarantee look the client id
11//! up before resending.
12
13use async_trait::async_trait;
14use futures::stream::BoxStream;
15use serde::{Deserialize, Serialize};
16
17use crate::account::{Balance, FeeTier, Fill, MarginSummary, Position};
18use crate::instrument::{Product, ProductId, VenueId};
19use crate::market::{BookSnapshot, Candle, Channel, Granularity, MarketEvent, Ticker, Trade};
20use crate::num::{Decimal, Price, Qty};
21use crate::order::{ClientOrderId, Order, OrderAck, OrderId, OrderRequest, OrderType, TimeInForce};
22use crate::{ExchangeError, RejectReason, Result};
23
24/// Test (sandbox, paper) or live (real money).
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
26#[serde(rename_all = "snake_case")]
27pub enum Environment {
28    Test,
29    Live,
30}
31
32impl Environment {
33    pub fn as_str(self) -> &'static str {
34        match self {
35            Environment::Test => "test",
36            Environment::Live => "live",
37        }
38    }
39}
40
41/// A stream of events. An `Err` item reports a problem (such as a lagging consumer that missed
42/// events); the stream may continue after it. The stream ends when the connection does.
43pub type EventStream<T> = BoxStream<'static, Result<T>>;
44
45/// What an adapter supports. Unset fields are unsupported.
46#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
47#[non_exhaustive]
48pub struct Capabilities {
49    pub market_orders: bool,
50    pub limit_orders: bool,
51    pub stop_orders: bool,
52    pub post_only: bool,
53    pub ioc: bool,
54    pub fok: bool,
55    pub gtd: bool,
56    /// Market orders sized in the quote asset.
57    pub quote_size: bool,
58    pub reduce_only: bool,
59    pub preview: bool,
60    pub cancel_all: bool,
61    pub positions: bool,
62    pub margin: bool,
63    pub user_stream: bool,
64}
65
66impl Capabilities {
67    /// Everything on.
68    pub fn all() -> Self {
69        Self {
70            market_orders: true,
71            limit_orders: true,
72            stop_orders: true,
73            post_only: true,
74            ioc: true,
75            fok: true,
76            gtd: true,
77            quote_size: true,
78            reduce_only: true,
79            preview: true,
80            cancel_all: true,
81            positions: true,
82            margin: true,
83            user_stream: true,
84        }
85    }
86
87    /// Checks a request uses only supported features.
88    pub fn check(&self, r: &OrderRequest) -> Result<()> {
89        let ok = match r.order_type {
90            OrderType::Market => self.market_orders,
91            OrderType::Limit { post_only, .. } => self.limit_orders && (!post_only || self.post_only),
92            OrderType::StopLimit { .. } | OrderType::StopMarket { .. } => self.stop_orders,
93        } && match r.time_in_force {
94            TimeInForce::Gtc => true,
95            TimeInForce::Gtd { .. } => self.gtd,
96            TimeInForce::Ioc => self.ioc || matches!(r.order_type, OrderType::Market),
97            TimeInForce::Fok => self.fok,
98        } && (r.base_size().is_some() || self.quote_size)
99            && (!r.reduce_only || self.reduce_only);
100        if ok { Ok(()) } else { Err(ExchangeError::rejected(RejectReason::UnsupportedOrder, "order type, time in force or size not supported")) }
101    }
102}
103
104/// A page of results; pass `next` back as the query's cursor for more.
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
106pub struct Page<T> {
107    pub items: Vec<T>,
108    pub next: Option<String>,
109}
110
111/// Candles for one product over `[start_ms, end_ms)`, oldest first.
112#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
113pub struct CandleQuery {
114    pub product: ProductId,
115    pub granularity: Granularity,
116    pub start_ms: i64,
117    pub end_ms: i64,
118    pub limit: Option<usize>,
119    pub cursor: Option<String>,
120}
121
122/// Which orders to list.
123#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
124pub struct OrderQuery {
125    pub product: Option<ProductId>,
126    /// Only orders that may still fill.
127    pub open_only: bool,
128    pub start_ms: Option<i64>,
129    pub end_ms: Option<i64>,
130    pub limit: Option<usize>,
131    pub cursor: Option<String>,
132}
133
134/// Which fills to list.
135#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
136pub struct FillQuery {
137    pub product: Option<ProductId>,
138    pub order_id: Option<OrderId>,
139    pub start_ms: Option<i64>,
140    pub end_ms: Option<i64>,
141    pub limit: Option<usize>,
142    pub cursor: Option<String>,
143}
144
145/// An order by the venue's id or the client's.
146#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
147#[serde(rename_all = "snake_case")]
148pub enum OrderRef {
149    Id(OrderId),
150    Client(ClientOrderId),
151}
152
153impl From<OrderId> for OrderRef {
154    fn from(id: OrderId) -> Self {
155        OrderRef::Id(id)
156    }
157}
158
159impl From<ClientOrderId> for OrderRef {
160    fn from(id: ClientOrderId) -> Self {
161        OrderRef::Client(id)
162    }
163}
164
165/// What an order would do if placed now.
166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
167pub struct Preview {
168    /// Base size that would fill immediately.
169    pub size: Qty,
170    pub notional: Decimal,
171    pub average_price: Option<Price>,
172    pub fee: Decimal,
173    pub warnings: Vec<String>,
174}
175
176/// Something that happened on the account.
177#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
178#[serde(rename_all = "snake_case")]
179#[non_exhaustive]
180pub enum UserEvent {
181    /// An order changed; the latest state.
182    Order(Order),
183    Fill(Fill),
184    Balance(Balance),
185    Position(Position),
186}
187
188/// Public market data.
189#[async_trait]
190pub trait MarketData: Send + Sync {
191    fn venue(&self) -> &VenueId;
192
193    async fn products(&self) -> Result<Vec<Product>>;
194
195    async fn product(&self, id: &ProductId) -> Result<Product> {
196        self.products().await?.into_iter().find(|p| p.market.product == *id).ok_or_else(|| ExchangeError::not_found(format!("product {id}")))
197    }
198
199    async fn ticker(&self, product: &ProductId) -> Result<Ticker>;
200
201    /// The book, `depth` levels a side (all for `None`).
202    async fn book(&self, product: &ProductId, depth: Option<usize>) -> Result<BookSnapshot>;
203
204    /// Recent public trades, newest first.
205    async fn trades(&self, product: &ProductId, limit: usize) -> Result<Vec<Trade>> {
206        let _ = (product, limit);
207        Err(ExchangeError::unsupported("recent trades"))
208    }
209
210    async fn candles(&self, query: &CandleQuery) -> Result<Page<Candle>>;
211
212    /// The venue's clock, in milliseconds since the epoch.
213    async fn server_time(&self) -> Result<i64> {
214        Ok(crate::now_ms())
215    }
216
217    /// Live events for these products and channels. A [`Channel::Book`] subscription starts
218    /// with a [`MarketEvent::Book`] snapshot, then deltas.
219    async fn subscribe(&self, products: &[ProductId], channels: &[Channel]) -> Result<EventStream<MarketEvent>>;
220}
221
222/// Trading on an account.
223#[async_trait]
224pub trait Trading: Send + Sync {
225    /// Test or live; an adapter built from [`crate::Credential<Live>`](crate::Credential) is live.
226    fn environment(&self) -> Environment;
227
228    fn capabilities(&self) -> Capabilities;
229
230    async fn balances(&self) -> Result<Vec<Balance>>;
231
232    async fn fee_tier(&self) -> Result<FeeTier>;
233
234    async fn preview_order(&self, request: &OrderRequest) -> Result<Preview> {
235        let _ = request;
236        Err(ExchangeError::unsupported("order preview"))
237    }
238
239    /// Places an order. Idempotent per client id (see the module docs).
240    async fn place_order(&self, request: &OrderRequest) -> Result<OrderAck>;
241
242    async fn cancel(&self, order: &OrderRef) -> Result<()>;
243
244    /// Cancels every working order, or those for one product. Returns the ids cancelled.
245    async fn cancel_all(&self, product: Option<&ProductId>) -> Result<Vec<OrderId>>;
246
247    async fn order(&self, order: &OrderRef) -> Result<Order>;
248
249    async fn orders(&self, query: &OrderQuery) -> Result<Page<Order>>;
250
251    async fn fills(&self, query: &FillQuery) -> Result<Page<Fill>>;
252
253    async fn positions(&self) -> Result<Vec<Position>> {
254        Err(ExchangeError::unsupported("positions"))
255    }
256
257    async fn margin(&self) -> Result<MarginSummary> {
258        Err(ExchangeError::unsupported("margin"))
259    }
260
261    /// Order, fill and balance changes on the account.
262    async fn subscribe_user(&self) -> Result<EventStream<UserEvent>>;
263}
264
265/// Market data and trading on one venue.
266pub trait Exchange: MarketData + Trading {}
267
268impl<T: MarketData + Trading + ?Sized> Exchange for T {}