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 config;
89pub mod credentials;
90pub mod error;
91pub mod exchange;
92pub mod http_client;
93pub mod logging;
94pub mod precision;
95pub mod rate_limiter;
96pub mod retry_strategy;
97pub mod symbol;
98pub mod time;
99/// Exchange trait hierarchy for modular capability composition
100pub mod traits;
101pub mod types;
102pub mod ws_client;
103pub mod ws_exchange;
104
105// Test utilities (available in dev-dependencies context)
106#[cfg(any(test, feature = "test-utils", debug_assertions))]
107pub mod test_config;
108
109// Note: Macros from test_config are automatically exported to crate root via #[macro_export]
110// No explicit pub use required here
111
112// Re-exports of core types for convenience
113pub use base_exchange::{BaseExchange, ExchangeConfig, ExchangeConfigBuilder, MarketCache};
114pub use credentials::{SecretBytes, SecretString};
115// Re-export unified Exchange trait from exchange module
116pub use exchange::{ArcExchange, BoxedExchange, Exchange, ExchangeExt};
117// Re-export capabilities from capability module (new bitflags-based implementation)
118pub use capability::{
119    Capabilities, Capability, ExchangeCapabilities, ExchangeCapabilitiesBuilder, TraitCategory,
120};
121// Re-export WebSocket exchange trait
122pub use error::{
123    ContextExt, Error, ExchangeErrorDetails, NetworkError, OrderError, ParseError, Result,
124};
125pub use ws_exchange::{FullExchange, MessageStream, WsExchange};
126// Re-export deprecated ErrorContext for backwards compatibility
127#[allow(deprecated)]
128pub use error::ErrorContext;
129pub use types::{
130    Amount, Balance, BalanceEntry, Cost, Currency, CurrencyNetwork, DefaultSubType, DefaultType,
131    DefaultTypeError, EndpointType, Fee, Market, MarketLimits, MarketPrecision, MarketType, MinMax,
132    Ohlcv, Order, OrderBook, OrderBookEntry, OrderBookSide, OrderSide, OrderStatus, OrderType,
133    PrecisionMode, Price, TakerOrMaker, Ticker, TickerParams, TickerParamsBuilder, Timeframe,
134    Trade, TradingLimits, resolve_market_type,
135};
136// Re-export symbol types for unified symbol format
137pub use symbol::{SymbolError, SymbolFormatter, SymbolParser};
138pub use types::symbol::{ContractType, ExpiryDate, ParsedSymbol, SymbolMarketType};
139pub use ws_client::{
140    BackoffConfig, BackoffStrategy, DEFAULT_MAX_SUBSCRIPTIONS, DEFAULT_SHUTDOWN_TIMEOUT,
141    Subscription, SubscriptionManager, WsClient, WsConfig, WsConnectionState, WsError, WsErrorKind,
142    WsEvent, WsMessage, WsStats, WsStatsSnapshot,
143};
144// Re-export CancellationToken for convenient access
145pub use tokio_util::sync::CancellationToken;
146
147/// Prelude module for convenient imports
148///
149/// Import everything you need with:
150/// ```rust
151/// use ccxt_core::prelude::*;
152/// ```
153pub mod prelude {
154    pub use crate::auth::{
155        DigestFormat, HashAlgorithm, base64_to_base64url, base64url_decode, eddsa_sign, hash,
156        hmac_sign, jwt_sign,
157    };
158    pub use crate::base_exchange::{
159        BaseExchange, ExchangeConfig, ExchangeConfigBuilder, MarketCache,
160    };
161    pub use crate::error::{ContextExt, Error, Result};
162    // Re-export unified Exchange trait and capabilities
163    pub use crate::exchange::{
164        ArcExchange, BoxedExchange, Exchange, ExchangeCapabilities, ExchangeExt,
165    };
166    // Re-export WebSocket exchange trait
167    pub use crate::ws_exchange::{FullExchange, MessageStream, WsExchange};
168    // Re-export deprecated ErrorContext for backwards compatibility
169    #[allow(deprecated)]
170    pub use crate::error::ErrorContext;
171    pub use crate::http_client::{HttpClient, HttpConfig};
172    pub use crate::logging::{LogConfig, LogFormat, LogLevel, init_logging, try_init_logging};
173    pub use crate::precision::{
174        CountingMode, PaddingMode, RoundingMode, decimal_to_precision, number_to_string,
175        precision_from_string,
176    };
177    pub use crate::rate_limiter::{MultiTierRateLimiter, RateLimiter, RateLimiterConfig};
178    pub use crate::retry_strategy::{RetryConfig, RetryStrategy, RetryStrategyType};
179    pub use crate::time::{
180        iso8601, microseconds, milliseconds, parse_date, parse_iso8601, seconds, ymd, ymdhms,
181        yymmdd, yyyymmdd,
182    };
183    pub use crate::types::{
184        Amount, Balance, BalanceEntry, Currency, DefaultSubType, DefaultType, DefaultTypeError,
185        EndpointType, Fee, Market, MarketLimits, MarketPrecision, MarketType, Ohlcv, Order,
186        OrderBook, OrderBookEntry, OrderBookSide, OrderSide, OrderStatus, OrderType, PrecisionMode,
187        Price, Symbol, TakerOrMaker, Ticker, TickerParams, TickerParamsBuilder, Timeframe,
188        Timestamp, Trade, TradingLimits, resolve_market_type,
189    };
190    // Symbol types for unified symbol format
191    pub use crate::symbol::{SymbolError, SymbolFormatter, SymbolParser};
192    pub use crate::types::symbol::{ContractType, ExpiryDate, ParsedSymbol, SymbolMarketType};
193    pub use crate::ws_client::{
194        BackoffConfig, BackoffStrategy, DEFAULT_MAX_SUBSCRIPTIONS, DEFAULT_SHUTDOWN_TIMEOUT,
195        Subscription, SubscriptionManager, WsClient, WsConfig, WsConnectionState, WsError,
196        WsErrorKind, WsEvent, WsMessage, WsStats, WsStatsSnapshot,
197    };
198    // Re-export CancellationToken for convenient access
199    pub use rust_decimal::Decimal;
200    pub use serde::{Deserialize, Serialize};
201    pub use tokio_util::sync::CancellationToken;
202}
203
204/// Library version
205pub const VERSION: &str = env!("CARGO_PKG_VERSION");
206
207/// Library name
208pub const NAME: &str = env!("CARGO_PKG_NAME");
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213
214    #[test]
215    fn test_version() {
216        assert!(!VERSION.is_empty());
217        assert_eq!(NAME, "ccxt-core");
218    }
219}