Skip to main content

scope/market/
mod.rs

1//! # Market Module
2//!
3//! Provides peg and order book health analysis for stablecoin markets.
4//! Uses a **data-driven architecture**: exchange behaviour is described by YAML
5//! venue descriptors (see `venues/` directory). A `VenueRegistry` loads all
6//! descriptors and creates generic `ExchangeClient` instances at runtime, so
7//! new venues can be added without code changes.
8//!
9//! ## Supported Venues
10//!
11//! Built-in CEX descriptors: Binance, MEXC, Bitget, Gate.io, Bybit, OKX,
12//! Coinbase, Kraken, HTX, Crypto.com, and Biconomy. DEX data (Ethereum, Solana)
13//! is synthesized from DexScreener liquidity.
14//!
15//! ## Usage
16//!
17//! ```rust,no_run
18//! use scope::market::{VenueRegistry, HealthThresholds, MarketSummary, Pair};
19//!
20//! #[tokio::main]
21//! async fn main() -> scope::Result<()> {
22//!     let registry = VenueRegistry::load()?; // the synced catalog and the user's venues
23//!     let http = scope::http::build(&scope::Config::default())?.client;
24//!     let exchange = registry.create_exchange_client_with_http("binance", http)?;
25//!     let pair = exchange.venue_symbol(&Pair::parse("USDC"));
26//!     let book = exchange.fetch_order_book(&pair).await?;
27//!     let summary = MarketSummary::from_order_book(&book, &HealthThresholds::default(), None);
28//!     print!("{}", summary.format_text(Some("binance")));
29//!     Ok(())
30//! }
31//! ```
32
33// Submodules (split from the original monolithic orderbook.rs)
34pub mod analytics;
35pub mod assets;
36pub mod fetch;
37pub mod health;
38pub mod pair;
39pub mod patterns;
40/// The metric catalog moved to [`crate::metrics`]; this path stays for one
41/// release (#47, Q6).
42#[doc(no_inline)]
43pub use crate::metrics as series;
44pub mod traits;
45pub mod types;
46
47// Data-driven venue system
48pub mod catalog;
49pub mod configurable_client;
50mod default_venue;
51pub mod descriptor;
52pub mod exchange;
53pub mod registry;
54pub mod venue;
55
56/// Test helpers: the repo's venue catalog, as a synced one, and a catalog
57/// venue pointed at a local mock server. Release builds carry no venues.
58#[cfg(any(test, feature = "test-support"))]
59pub mod testing {
60    use super::{ExchangeClient, VenueRegistry};
61
62    /// The venues of the repo's catalog (`crates/scope-core/venues/`), read
63    /// from disk as `scope venues update` would install them.
64    pub fn catalog() -> VenueRegistry {
65        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("venues");
66        VenueRegistry::load_dirs(&dir, &dir.join("no-user-venues")).expect("the repo catalog loads")
67    }
68
69    /// The catalog venue `id`, with its real mapping, sending to `base_url`
70    /// (a mockito server) instead of the live API.
71    pub fn venue_at(id: &str, base_url: &str) -> ExchangeClient {
72        let mut desc = catalog()
73            .get(id)
74            .unwrap_or_else(|| panic!("no catalog venue {id}"))
75            .clone();
76        desc.base_url = base_url.to_string();
77        ExchangeClient::from_descriptor_with_http(&desc, crate::http::test_transport())
78    }
79}
80
81// Backward-compatible re-export shim (allows `use crate::market::OrderBook` etc.)
82mod orderbook;
83
84pub use configurable_client::ConfigurableExchangeClient;
85pub use default_venue::DEFAULT_VENUE;
86pub use descriptor::VenueDescriptor;
87pub use exchange::ExchangeClient;
88#[allow(deprecated)]
89pub use fetch::{
90    DexAnalyticsSource, fetch_book_and_volume, fetch_pattern_trades, fetch_summary,
91    fetch_summary_with_trades, fetch_token_summary, fetch_token_summary_by_name,
92    fetch_token_summary_by_name_with_http, most_liquid,
93};
94pub use orderbook::{
95    BookSide, BookSource, Candle, ExecutionEstimate, ExecutionSide, HealthCheck, HealthOverrides,
96    HealthThresholds, MarketSnapshot, MarketSummary, OhlcClient, OrderBook, OrderBookClient,
97    OrderBookLevel, Ticker, TickerClient, Trade, TradeHistoryClient, TradeSide,
98    order_book_from_analytics,
99};
100pub use pair::{DEFAULT_PAIR, Pair};
101pub use registry::VenueRegistry;
102pub use venue::{DexVenue, MarketVenue, VENUE_HELP, VenueKind, VenueListing};