kiteconnect_async_wasm/lib.rs
1//! # kiteconnect-async-wasm v1.0.3
2//!
3//! A modern, async Rust implementation of the Zerodha KiteConnect API with dual API support,
4//! enhanced error handling, and full WASM compatibility. This library provides comprehensive
5//! access to KiteConnect's REST APIs for trading, portfolio management, and market data.
6//!
7//! ## โจ Features v1.0.3
8//!
9//! - **๐ Enhanced Historical Data API**: New `HistoricalDataRequest` struct with `NaiveDateTime` precision
10//! - **๐ Dual Serde Support**: Flexible Interval enum accepting both strings and integers
11//! - **๐ฆ Organized Enum System**: Modular enum structure for better maintainability
12//! - **๐ฏ Dual API Support**: Legacy JSON + new strongly-typed APIs with automatic retry logic
13//! - **๐ WASM Compatible**: Run in browsers with WebAssembly support
14//! - **๐ Cross-Platform**: Native (Linux, macOS, Windows) and Web targets
15//! - **๐ฆ Modern Dependencies**: Updated to latest Rust ecosystem libraries
16//! - **๐งช Well Tested**: Comprehensive test coverage (30 unit + 11 integration + 58 doc tests)
17//! - **โก High Performance**: Efficient HTTP client with connection pooling and caching
18//! - **๐ก๏ธ Type Safe**: Enhanced type system with better error handling patterns
19//! - **๐ Professional Quality**: Clippy-optimized and consistently formatted code
20//!
21//! ## ๐ฏ Quick Start
22//!
23//! Add to your `Cargo.toml`:
24//!
25//! ```toml
26//! # For native applications (default)
27//! [dependencies]
28//! kiteconnect-async-wasm = "1.0.3"
29//!
30//! # For WASM/browser applications
31//! [dependencies]
32//! kiteconnect-async-wasm = { version = "1.0.3", features = ["wasm"] }
33//!
34//! # For development with debugging
35//! [dependencies]
36//! kiteconnect-async-wasm = { version = "1.0.3", features = ["native", "debug"] }
37//! ```
38//!
39//! ## ๐ Basic Usage
40//!
41//! ### Legacy API (Backward Compatible)
42//! ```rust,no_run
43//! use kiteconnect_async_wasm::connect::KiteConnect;
44//!
45//! #[tokio::main]
46//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
47//! let client = KiteConnect::new("api_key", "access_token");
48//!
49//! // Legacy API - returns JsonValue (still works)
50//! let holdings = client.holdings().await?;
51//! println!("Holdings: {:?}", holdings);
52//!
53//! Ok(())
54//! }
55//! ```
56//!
57//! ### Enhanced Typed API (Recommended for v1.0.3)
58//! ```rust,no_run
59//! use kiteconnect_async_wasm::connect::KiteConnect;
60//! use kiteconnect_async_wasm::models::prelude::*;
61//!
62//! #[tokio::main]
63//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
64//! let client = KiteConnect::new("api_key", "access_token");
65//!
66//! // New typed API with enhanced error handling
67//! let holdings: Vec<Holding> = client.holdings_typed().await?;
68//! let positions: Vec<Position> = client.positions_typed().await?;
69//!
70//! println!("Found {} holdings and {} positions", holdings.len(), positions.len());
71//!
72//! Ok(())
73//! }
74//! ```
75//!
76//! ### Enhanced Historical Data API (v1.0.3)
77//! ```rust,no_run
78//! use kiteconnect_async_wasm::connect::KiteConnect;
79//! use kiteconnect_async_wasm::models::market_data::HistoricalDataRequest;
80//! use kiteconnect_async_wasm::models::common::Interval;
81//! use chrono::NaiveDateTime;
82//!
83//! #[tokio::main]
84//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
85//! let client = KiteConnect::new("api_key", "access_token");
86//!
87//! // New structured approach with precise datetime handling
88//! let request = HistoricalDataRequest::new(
89//! 738561, // RELIANCE instrument token
90//! NaiveDateTime::parse_from_str("2023-11-01 09:15:00", "%Y-%m-%d %H:%M:%S")?,
91//! NaiveDateTime::parse_from_str("2023-11-30 15:30:00", "%Y-%m-%d %H:%M:%S")?,
92//! Interval::Day,
93//! ).continuous(false).with_oi(true);
94//!
95//! let historical_data = client.historical_data_typed(request).await?;
96//! println!("Received {} candles", historical_data.candles.len());
97//!
98//! Ok(())
99//! }
100//! ```
101//!
102//! ## ๐ง Feature Flags
103//!
104//! This crate supports multiple feature flags for platform-specific functionality:
105//!
106//! - **`native`** (default): Enables native platform support with tokio and full CSV parsing
107//! - Includes: `tokio`, `sha2`, `csv` dependencies
108//! - Best for: Desktop applications, servers, CLI tools
109//!
110//! - **`wasm`**: Enables WebAssembly support with browser APIs
111//! - Includes: `wasm-bindgen`, `web-sys`, `js-sys`, `gloo-utils` dependencies
112//! - Features: Browser-compatible operations with Web APIs
113//! - Best for: Browser applications, web workers
114//!
115//! - **`debug`**: Enables additional logging and debugging features
116//! - Includes: Enhanced `log` output and debugging utilities
117//! - Best for: Development and troubleshooting
118//!
119//! ## Basic Usage
120//!
121//! ```rust,no_run
122//! use kiteconnect_async_wasm::connect::KiteConnect;
123//! use serde_json::Value as JsonValue;
124//!
125//! #[tokio::main]
126//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
127//! // Initialize KiteConnect client
128//! let mut kiteconnect = KiteConnect::new("<YOUR-API-KEY>", "");
129//!
130//! // Step 1: Get login URL
131//! let login_url = kiteconnect.login_url();
132//! println!("Login URL: {}", login_url);
133//!
134//! // Step 2: After user login, generate session with request token
135//! let session_response = kiteconnect
136//! .generate_session("<REQUEST-TOKEN>", "<API-SECRET>")
137//! .await?;
138//! println!("Session: {:?}", session_response);
139//!
140//! // Step 3: Use the API (access token is automatically set)
141//! let holdings: JsonValue = kiteconnect.holdings().await?;
142//! println!("Holdings: {:?}", holdings);
143//!
144//! Ok(())
145//! }
146//! ```
147//!
148//! ## Available APIs
149//!
150//! The library provides access to all KiteConnect REST APIs:
151//!
152//! ### Authentication
153//! - `login_url()` - Generate login URL
154//! - `generate_session()` - Create session with request token
155//! - `invalidate_session()` - Logout user
156//!
157//! ### Portfolio
158//! - `holdings()` - Get user holdings
159//! - `positions()` - Get user positions
160//! - `margins()` - Get account margins
161//!
162//! ### Orders
163//! - `orders()` - Get all orders
164//! - `order_trades()` - Get trades for specific order
165//! - `trades()` - Get all trades
166//!
167//! ### Market Data
168//! - `instruments()` - Get instrument list
169//! - `trigger_range()` - Get trigger range for instruments
170//!
171//! ### Mutual Funds
172//! - `mf_orders()` - Get mutual fund orders
173//! - `mf_instruments()` - Get mutual fund instruments
174//!
175//! ## Error Handling
176//!
177//! The library uses `anyhow::Result` for comprehensive error handling:
178//!
179//! ```rust,no_run
180//! # use kiteconnect_async_wasm::connect::KiteConnect;
181//! # #[tokio::main]
182//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
183//! # let kiteconnect = KiteConnect::new("", "");
184//! match kiteconnect.holdings().await {
185//! Ok(holdings) => println!("Holdings: {:?}", holdings),
186//! Err(e) => eprintln!("Error fetching holdings: {}", e),
187//! }
188//! # Ok(())
189//! # }
190//! ```
191//!
192//! ## Platform-Specific Features
193//!
194//! ### Native (Tokio)
195//! - Full CSV parsing for instruments
196//! - Complete async/await support
197//! - High-performance HTTP client
198//!
199//! ### WASM (Browser)
200//! - All APIs supported with full CSV parsing
201//! - CSV parsing using csv-core for browser compatibility
202//! - Returns structured JSON data (same as native)
203//! - Compatible with web frameworks
204//!
205//! ## Examples
206//!
207//! See the `examples/` directory for comprehensive usage examples:
208//! - `connect_sample.rs` - Basic API usage
209//! - `async_connect_example.rs` - Advanced async patterns
210//!
211//! ## Thread Safety
212//!
213//! The `KiteConnect` struct is `Clone + Send + Sync`, making it safe to use across
214//! multiple threads and async tasks. The underlying HTTP client uses connection
215//! pooling for optimal performance.
216//!
217//! ```rust,no_run
218//! # use kiteconnect_async_wasm::connect::KiteConnect;
219//! # #[tokio::main]
220//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
221//! let kiteconnect = KiteConnect::new("<API-KEY>", "<ACCESS-TOKEN>");
222//!
223//! // Clone for use in different tasks
224//! let kc1 = kiteconnect.clone();
225//! let kc2 = kiteconnect.clone();
226//!
227//! // Use in concurrent tasks
228//! let (holdings, positions) = tokio::try_join!(
229//! kc1.holdings(),
230//! kc2.positions()
231//! )?;
232//! # Ok(())
233//! # }
234//! ```
235//!
236#[cfg(test)]
237extern crate mockito;
238
239pub mod connect;
240pub mod models;