Skip to main content

weirdnet_exchange/
lib.rs

1//! Exchange-neutral trading types and traits for Weirdnet apps.
2//!
3//! - [`num`]: exact decimal [`Price`] and [`Qty`] (no floats), with increment rounding.
4//! - [`instrument`]: venues, products, markets and instrument kinds (spot, dated futures,
5//!   perpetuals), with order checks against a product's increments and limits.
6//! - [`order`]: sides, order types, time in force, client order ids, requests, and an
7//!   [`Order`] state machine that accounts fills.
8//! - [`account`]: fills, balances, fee tiers, positions (with a [`PositionBook`]) and margin.
9//! - [`market`]: trades, tickers, order book snapshots and deltas (an [`OrderBook`] that
10//!   applies them with gap checks), candles and a [`CandleBuilder`].
11//! - [`exchange`]: the async adapter traits, [`MarketData`] (no credentials) and [`Trading`],
12//!   with [`Capabilities`] and paging; [`Exchange`] is both.
13//! - [`cost`]: a [`CostModel`] for fees, spread and slippage from a live book.
14//! - [`rate`]: a shared token-bucket [`RateLimiter`].
15//! - [`credentials`]: secrets for adapters, typed by environment so a live adapter can only be
16//!   built from [`Live`] credentials.
17//! - [`paper`]: [`Paper`], an in-memory simulated exchange for tests and dry runs.
18//! - Feature `vault`: [`vault::VaultSecret`], credentials from `weirdnet-vault`.
19//! - Feature `service`: [`feeds::MarketHubs`], market data as `weirdnet-service` hub topics.
20//!
21//! This crate has no exchange adapters and makes no network calls. Adapters implement the
22//! traits in their own crates.
23//!
24//! Timestamps are milliseconds since the Unix epoch (UTC). Amounts are [`Decimal`].
25//!
26//! ```
27//! use weirdnet_exchange::*;
28//!
29//! # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(async {
30//! let paper = Paper::default();
31//! let m = paper.market("BTC-USD");
32//! paper.add_product(Product::spot(m.clone(), "BTC", "USD").with_increments(Decimal::new(1, 2), Decimal::new(1, 4)))?;
33//! paper.deposit("USD", Decimal::from(1000));
34//! paper.set_book(BookSnapshot {
35//!     market: m.clone(),
36//!     bids: vec![Level::new(Price::parse("99")?, Qty::parse("1")?)],
37//!     asks: vec![Level::new(Price::parse("101")?, Qty::parse("1")?)],
38//!     sequence: 1,
39//!     at_ms: 0,
40//! })?;
41//!
42//! let x: &dyn Exchange = &paper;
43//! let order = OrderRequest::market(ClientOrderId::generate("demo"), m, Side::Buy, OrderSize::Base(Qty::parse("0.5")?));
44//! let ack = x.place_order(&order).await?;
45//! assert_eq!(ack.status, OrderStatus::Filled);
46//! # Ok::<_, ExchangeError>(())
47//! # }).unwrap();
48//! ```
49
50#![forbid(unsafe_code)]
51
52pub mod account;
53pub mod cost;
54pub mod credentials;
55pub mod error;
56pub mod exchange;
57pub mod instrument;
58pub mod market;
59pub mod num;
60pub mod order;
61pub mod paper;
62pub mod rate;
63
64#[cfg(feature = "service")]
65pub mod feeds;
66#[cfg(feature = "vault")]
67pub mod vault;
68
69pub use account::{Balance, FeeTier, Fill, Liquidity, MarginSummary, Position, PositionBook};
70pub use cost::{BookCostModel, Cost, CostModel};
71pub use credentials::{Credential, EnvKind, Live, SecretSource, StaticSecret, Test};
72pub use error::{ExchangeError, RejectReason, Result};
73pub use exchange::{
74    CandleQuery, Capabilities, Environment, EventStream, Exchange, FillQuery, MarketData, OrderQuery, OrderRef, Page, Preview, Trading, UserEvent,
75};
76pub use instrument::{AccountId, Asset, InstrumentKind, Market, Product, ProductId, ProductStatus, VenueId};
77pub use market::{BookChange, BookDelta, BookSnapshot, Candle, CandleBuilder, Channel, Granularity, Level, MarketEvent, OrderBook, Ticker, Trade};
78pub use num::{Decimal, Price, Qty, Rounding};
79pub use order::{
80    ClientOrderId, Order, OrderAck, OrderEvent, OrderId, OrderRequest, OrderSize, OrderStatus, OrderType, PositionSide, Side, TimeInForce,
81};
82pub use paper::{Paper, PaperOptions};
83pub use rate::{BucketSpec, RateLimiter};
84
85/// Milliseconds since the Unix epoch, from the system clock.
86pub fn now_ms() -> i64 {
87    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or_default()
88}