ccxt_core/
lib.rs

1//! CCXT Core Library
2//!
3//! This is the core library for CCXT Rust implementation, providing fundamental
4//! data structures, error types, and traits for cryptocurrency exchange integration.
5//!
6//! # Features
7//!
8//! - **Type Safety**: Leverages Rust's type system for compile-time guarantees
9//! - **Precision**: Uses `rust_decimal::Decimal` for accurate financial calculations
10//! - **Async/Await**: Built on tokio for high-performance async operations
11//! - **Error Handling**: Comprehensive error types with `thiserror`
12//!
13//! # Example
14//!
15//! ```rust,no_run
16//! use ccxt_core::prelude::*;
17//!
18//! # async fn example() -> Result<()> {
19//! // Create a market
20//! let market = Market::new_spot(
21//!     "btc/usdt".to_string(),
22//!     "BTC/USDT".to_string(),
23//!     "BTC".to_string(),
24//!     "USDT".to_string(),
25//! );
26//!
27//! // Create an order
28//! let order = Order::new(
29//!     "12345".to_string(),
30//!     "BTC/USDT".to_string(),
31//!     OrderType::Limit,
32//!     OrderSide::Buy,
33//!     rust_decimal_macros::dec!(0.1),
34//!     Some(rust_decimal_macros::dec!(50000.0)),
35//!     OrderStatus::Open,
36//! );
37//! # Ok(())
38//! # }
39//! ```
40
41#![warn(missing_docs)]
42#![warn(clippy::all)]
43#![warn(clippy::pedantic)]
44// =============================================================================
45// Global Clippy Lint Suppressions
46// =============================================================================
47// These lints are suppressed globally because they apply broadly across the
48// codebase and would require excessive local annotations.
49//
50// Justified Global Suppressions (per Requirement 3.4):
51// - module_name_repetitions: Common pattern in Rust libraries (e.g., OrderType in order module)
52// - missing_errors_doc: Too verbose to document every Result-returning function
53// - missing_panics_doc: Too verbose to document every potential panic
54// - must_use_candidate: Not all return values need #[must_use]
55//
56// Practical Global Suppressions:
57// - doc_markdown: Technical terms in docs don't need backticks (e.g., OHLCV, HMAC)
58// - similar_names: Trading terminology requires similar names (bid/ask, buy/sell)
59// - cast_sign_loss: Common in timestamp operations (i64 <-> u64)
60// - cast_possible_wrap: Common in timestamp/numeric operations
61// - struct_excessive_bools: Config structs legitimately have many boolean flags
62// - too_many_lines: Some complex parsing/validation functions are unavoidable
63// - return_self_not_must_use: Builder pattern methods return Self without must_use
64// - unreadable_literal: Timestamps are more readable without separators (1704110400000)
65// =============================================================================
66#![allow(clippy::module_name_repetitions)]
67#![allow(clippy::missing_errors_doc)]
68#![allow(clippy::missing_panics_doc)]
69#![allow(clippy::must_use_candidate)]
70#![allow(clippy::doc_markdown)]
71#![allow(clippy::similar_names)]
72#![allow(clippy::cast_sign_loss)]
73#![allow(clippy::cast_possible_wrap)]
74#![allow(clippy::struct_excessive_bools)]
75#![allow(clippy::too_many_lines)]
76#![allow(clippy::return_self_not_must_use)]
77#![allow(clippy::unreadable_literal)]
78
79// Re-exports of external dependencies
80pub use rust_decimal;
81pub use serde;
82pub use serde_json;
83
84// Core modules
85pub mod auth;
86pub mod base_exchange;
87pub mod capability;
88pub mod circuit_breaker;
89pub mod config;
90pub mod credentials;
91pub mod error;
92pub mod exchange;
93pub mod http_client;
94pub mod logging;
95pub mod parser_utils;
96pub mod precision;
97pub mod rate_limiter;
98pub mod retry_strategy;
99pub mod signed_request;
100pub mod symbol;
101pub mod time;
102/// Exchange trait hierarchy for modular capability composition
103pub mod traits;
104pub mod types;
105pub mod ws_client;
106pub mod ws_exchange;
107
108// Test utilities (available in dev-dependencies context)
109#[cfg(any(test, feature = "test-utils", debug_assertions))]
110pub mod test_config;
111
112// Note: Macros from test_config are automatically exported to crate root via #[macro_export]
113// No explicit pub use required here
114
115// Re-exports of core types for convenience
116pub use base_exchange::{BaseExchange, ExchangeConfig, ExchangeConfigBuilder, MarketCache};
117pub use circuit_breaker::{
118    CircuitBreaker, CircuitBreakerConfig, CircuitBreakerEvent, CircuitState,
119};
120pub use credentials::{SecretBytes, SecretString};
121// Re-export unified Exchange trait from exchange module
122pub use exchange::{ArcExchange, BoxedExchange, Exchange, ExchangeExt};
123// Re-export capabilities from capability module (new bitflags-based implementation)
124pub use capability::{
125    Capabilities, Capability, ExchangeCapabilities, ExchangeCapabilitiesBuilder, TraitCategory,
126};
127// Re-export WebSocket exchange trait
128pub use error::{
129    ContextExt, Error, ExchangeErrorDetails, NetworkError, OrderError, ParseError, Result,
130};
131pub use ws_exchange::{FullExchange, MessageStream, WsExchange};
132// Re-export deprecated ErrorContext for backwards compatibility
133#[allow(deprecated)]
134pub use error::ErrorContext;
135pub use types::{
136    Amount, Balance, BalanceEntry, Cost, Currency, CurrencyNetwork, DefaultSubType, DefaultType,
137    DefaultTypeError, EndpointType, Fee, Market, MarketLimits, MarketPrecision, MarketType, MinMax,
138    Ohlcv, Order, OrderBook, OrderBookEntry, OrderBookSide, OrderSide, OrderStatus, OrderType,
139    PrecisionMode, Price, TakerOrMaker, Ticker, TickerParams, TickerParamsBuilder, Timeframe,
140    Trade, TradingLimits, resolve_market_type,
141};
142// Re-export symbol types for unified symbol format
143pub use symbol::{SymbolError, SymbolFormatter, SymbolParser};
144pub use types::symbol::{ContractType, ExpiryDate, ParsedSymbol, SymbolMarketType};
145pub use ws_client::{
146    BackoffConfig, BackoffStrategy, DEFAULT_MAX_SUBSCRIPTIONS, DEFAULT_SHUTDOWN_TIMEOUT,
147    Subscription, SubscriptionManager, WsClient, WsConfig, WsConnectionState, WsError, WsErrorKind,
148    WsEvent, WsMessage, WsStats, WsStatsSnapshot,
149};
150// Re-export CancellationToken for convenient access
151pub use tokio_util::sync::CancellationToken;
152
153/// Prelude module for convenient imports
154///
155/// Import everything you need with:
156/// ```rust
157/// use ccxt_core::prelude::*;
158/// ```
159pub mod prelude {
160    pub use crate::auth::{
161        DigestFormat, HashAlgorithm, base64_to_base64url, base64url_decode, eddsa_sign, hash,
162        hmac_sign, jwt_sign,
163    };
164    pub use crate::base_exchange::{
165        BaseExchange, ExchangeConfig, ExchangeConfigBuilder, MarketCache,
166    };
167    pub use crate::circuit_breaker::{CircuitBreaker, CircuitBreakerConfig, CircuitState};
168    pub use crate::error::{ContextExt, Error, Result};
169    // Re-export unified Exchange trait and capabilities
170    pub use crate::exchange::{
171        ArcExchange, BoxedExchange, Exchange, ExchangeCapabilities, ExchangeExt,
172    };
173    // Re-export WebSocket exchange trait
174    pub use crate::ws_exchange::{FullExchange, MessageStream, WsExchange};
175    // Re-export deprecated ErrorContext for backwards compatibility
176    #[allow(deprecated)]
177    pub use crate::error::ErrorContext;
178    pub use crate::http_client::{HttpClient, HttpConfig};
179    pub use crate::logging::{LogConfig, LogFormat, LogLevel, init_logging, try_init_logging};
180    pub use crate::precision::{
181        CountingMode, PaddingMode, RoundingMode, decimal_to_precision, number_to_string,
182        precision_from_string,
183    };
184    pub use crate::rate_limiter::{MultiTierRateLimiter, RateLimiter, RateLimiterConfig};
185    pub use crate::retry_strategy::{RetryConfig, RetryStrategy, RetryStrategyType};
186    pub use crate::time::{
187        iso8601, microseconds, milliseconds, parse_date, parse_iso8601, seconds, ymd, ymdhms,
188        yymmdd, yyyymmdd,
189    };
190    pub use crate::types::{
191        Amount, Balance, BalanceEntry, Currency, DefaultSubType, DefaultType, DefaultTypeError,
192        EndpointType, Fee, Market, MarketLimits, MarketPrecision, MarketType, Ohlcv, Order,
193        OrderBook, OrderBookEntry, OrderBookSide, OrderSide, OrderStatus, OrderType, PrecisionMode,
194        Price, Symbol, TakerOrMaker, Ticker, TickerParams, TickerParamsBuilder, Timeframe,
195        Timestamp, Trade, TradingLimits, resolve_market_type,
196    };
197    // Symbol types for unified symbol format
198    pub use crate::symbol::{SymbolError, SymbolFormatter, SymbolParser};
199    pub use crate::types::symbol::{ContractType, ExpiryDate, ParsedSymbol, SymbolMarketType};
200    pub use crate::ws_client::{
201        BackoffConfig, BackoffStrategy, DEFAULT_MAX_SUBSCRIPTIONS, DEFAULT_SHUTDOWN_TIMEOUT,
202        Subscription, SubscriptionManager, WsClient, WsConfig, WsConnectionState, WsError,
203        WsErrorKind, WsEvent, WsMessage, WsStats, WsStatsSnapshot,
204    };
205    // Re-export CancellationToken for convenient access
206    pub use rust_decimal::Decimal;
207    pub use serde::{Deserialize, Serialize};
208    pub use tokio_util::sync::CancellationToken;
209}
210
211/// Library version
212pub const VERSION: &str = env!("CARGO_PKG_VERSION");
213
214/// Library name
215pub const NAME: &str = env!("CARGO_PKG_NAME");
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220
221    #[test]
222    fn test_version() {
223        assert!(!VERSION.is_empty());
224        assert_eq!(NAME, "ccxt-core");
225    }
226}