1use 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#[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
41pub type EventStream<T> = BoxStream<'static, Result<T>>;
44
45#[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 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 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
106pub struct Page<T> {
107 pub items: Vec<T>,
108 pub next: Option<String>,
109}
110
111#[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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
124pub struct OrderQuery {
125 pub product: Option<ProductId>,
126 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#[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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
167pub struct Preview {
168 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
178#[serde(rename_all = "snake_case")]
179#[non_exhaustive]
180pub enum UserEvent {
181 Order(Order),
183 Fill(Fill),
184 Balance(Balance),
185 Position(Position),
186}
187
188#[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 async fn book(&self, product: &ProductId, depth: Option<usize>) -> Result<BookSnapshot>;
203
204 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 async fn server_time(&self) -> Result<i64> {
214 Ok(crate::now_ms())
215 }
216
217 async fn subscribe(&self, products: &[ProductId], channels: &[Channel]) -> Result<EventStream<MarketEvent>>;
220}
221
222#[async_trait]
224pub trait Trading: Send + Sync {
225 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 async fn place_order(&self, request: &OrderRequest) -> Result<OrderAck>;
241
242 async fn cancel(&self, order: &OrderRef) -> Result<()>;
243
244 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 async fn subscribe_user(&self) -> Result<EventStream<UserEvent>>;
263}
264
265pub trait Exchange: MarketData + Trading {}
267
268impl<T: MarketData + Trading + ?Sized> Exchange for T {}