kiteconnect-async-wasm 1.0.8

Modern async Rust client for KiteConnect REST APIs with WASM support. Clean, well-documented, and focused on REST-only operations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
# KiteConnect Async WASM v1.0.6

> โš ๏ธ **IMPORTANT DISCLAIMER** โš ๏ธ
> 
> **๐Ÿค– AI-GENERATED CODE - USE AT YOUR OWN RISK**
> 
> This entire codebase has been generated using artificial intelligence and automated tools. While comprehensive testing has been performed, users should:
> - **Thoroughly test** all functionality in their specific use cases
> - **Review and validate** code before production use
> - **Use at their own risk** and responsibility
> - **Not rely on this** for critical financial operations without extensive validation
> 
> The maintainers provide no warranties or guarantees regarding the correctness, reliability, or suitability of this AI-generated code.

[![Crates.io](https://img.shields.io/crates/v/kiteconnect-async-wasm.svg)](https://crates.io/crates/kiteconnect-async-wasm)
[![Documentation](https://docs.rs/kiteconnect-async-wasm/badge.svg)](https://docs.rs/kiteconnect-async-wasm)
[![License: Unlicense](https://img.shields.io/badge/license-Unlicense-blue.svg)](http://unlicense.org/)

**Modern async Rust client for KiteConnect REST APIs with dual API support, enhanced error handling, and WASM compatibility**

A production-ready, high-performance Rust library for KiteConnect API integration featuring both legacy and strongly-typed APIs.

## ๐Ÿš€ Features v1.0.6

- โœ… **Robust Historical Data API** - Enhanced `Candle` deserialization with support for multiple API response formats
- โœ… **Environment Variable Integration** - All examples use secure environment variables for API credentials  
- โœ… **Enhanced Error Handling** - Improved handling of missing metadata and OI fields
- โœ… **Timezone-Aware Parsing** - Support for +0530 timezone and various date formats
- โœ… **Production-Ready Examples** - Tested examples that work with real KiteConnect API
- โœ… **Enhanced Historical Data API** - New `HistoricalDataRequest` struct with `NaiveDateTime` precision
- โœ… **Dual Serde Support** - Flexible Interval enum accepting both strings and integers
- โœ… **Organized Enum System** - Modular enum structure for better maintainability
- โœ… **Dual API Support** - Legacy JSON + new strongly-typed APIs
- โœ… **Automatic Retry Logic** with exponential backoff
- โœ… **Response Caching** for performance optimization
- โœ… **Full WASM Compatibility** for web applications  
- โœ… **Thread-Safe Design** with connection pooling
- โœ… **Comprehensive Documentation** with migration guide
- โœ… **Backward Compatibility** - all existing code continues to work
- โœ… **Professional Code Quality** - Clippy optimized and formatted

## ๐Ÿ†• What's New in v1.0.6

### ๐Ÿ”ง Enhanced Historical Data Reliability

The v1.0.6 release focuses on making historical data fetching **production-ready** and **robust**:

```rust
use kiteconnect_async_wasm::connect::KiteConnect;
use kiteconnect_async_wasm::models::market_data::HistoricalDataRequest;
use kiteconnect_async_wasm::models::common::Interval;
use chrono::NaiveDateTime;
use std::env;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // ๐Ÿ”’ Secure: Use environment variables
    let api_key = env::var("KITE_API_KEY")?;
    let access_token = env::var("KITE_ACCESS_TOKEN")?;
    let client = KiteConnect::new(&api_key, &access_token);

    // ๐Ÿ“Š Robust: Handles various API response formats
    let request = HistoricalDataRequest::new(
        256265, // Instrument token
        NaiveDateTime::parse_from_str("2024-12-20 09:00:00", "%Y-%m-%d %H:%M:%S")?,
        NaiveDateTime::parse_from_str("2024-12-20 16:00:00", "%Y-%m-%d %H:%M:%S")?,
        Interval::FiveMinute,
    );

    // โœ… Works reliably with real KiteConnect API
    let data = client.historical_data_typed(request).await?;
    println!("Fetched {} candles successfully!", data.candles.len());
    
    Ok(())
}
```

**Key Improvements:**
- โœ… **Custom Candle Deserializer** - Handles both array and object formats from KiteConnect API
- โœ… **Metadata Synthesis** - Generates metadata when API doesn't provide it  
- โœ… **Timezone Support** - Proper parsing of +0530 timezone and various date formats
- โœ… **Missing Field Handling** - Graceful handling when Open Interest (OI) data is unavailable
- โœ… **Environment Variables** - All examples use secure credential management
- โœ… **Real API Testing** - Examples tested with actual KiteConnect API responses

## ๐ŸŽฏ Quick Start

### Installation

```toml
[dependencies]
kiteconnect-async-wasm = "1.0.8"

# For WASM targets
# kiteconnect-async-wasm = "1.0.8", features = ["wasm"] }
```

### Basic Usage (Legacy API - Backward Compatible)

```rust
use kiteconnect_async_wasm::connect::KiteConnect;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = KiteConnect::new("your_api_key", "");

    // Step 1: Get login URL and complete authentication
    println!("Login URL: {}", client.login_url());
    
    // Step 2: After authentication, generate session
    let session = client.generate_session("request_token", "api_secret").await?;
    println!("Session: {:?}", session);
    
    // Step 3: Use APIs (existing code works as before)
    let holdings = client.holdings().await?;
    println!("Holdings: {:?}", holdings);
    
    Ok(())
}
```

### New Typed API (Recommended for v1.0.2)

```rust
use kiteconnect_async_wasm::connect::KiteConnect;
use kiteconnect_async_wasm::models::prelude::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = KiteConnect::new("api_key", "access_token");
    
    // Strongly-typed responses with automatic retry and error handling
    let holdings: Vec<Holding> = client.holdings_typed().await?;
    let positions: Vec<Position> = client.positions_typed().await?;
    
    // Enhanced error handling
    match client.orders_typed().await {
        Ok(orders) => {
            println!("Found {} orders", orders.len());
            for order in orders {
                println!("Order {}: {} {} @ โ‚น{}", 
                    order.order_id, 
                    order.transaction_type, 
                    order.trading_symbol, 
                    order.price.unwrap_or(0.0)
                );
            }
        }
        Err(KiteError::Authentication(msg)) => {
            eprintln!("Authentication failed: {}", msg);
        }
        Err(KiteError::Api { status, message, .. }) => {
            eprintln!("API error {}: {}", status, message);
        }
        Err(e) => eprintln!("Other error: {}", e),
    }
    
    Ok(())
}
```

### Enhanced Historical Data API (v1.0.3)

```rust
use kiteconnect_async_wasm::connect::KiteConnect;
use kiteconnect_async_wasm::models::market_data::HistoricalDataRequest;
use kiteconnect_async_wasm::models::common::Interval;
use chrono::NaiveDateTime;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = KiteConnect::new("api_key", "access_token");
    
    // New structured approach with precise datetime handling
    let request = HistoricalDataRequest::new(
        738561,  // RELIANCE instrument token
        NaiveDateTime::parse_from_str("2023-11-01 09:15:00", "%Y-%m-%d %H:%M:%S")?,
        NaiveDateTime::parse_from_str("2023-11-30 15:30:00", "%Y-%m-%d %H:%M:%S")?,
        Interval::Day,
    ).continuous(false).with_oi(true);
    
    let historical_data = client.historical_data_typed(request).await?;
    
    println!("Received {} candles", historical_data.candles.len());
    for candle in &historical_data.candles {
        println!("Date: {}, OHLC: {}/{}/{}/{}, Volume: {}", 
            candle.date, candle.open, candle.high, candle.low, candle.close, candle.volume);
    }
    
    Ok(())
}
```

### Flexible Interval Usage (v1.0.3)

```rust
use kiteconnect_async_wasm::models::common::Interval;

// Accepts both string and integer formats
let from_string: Interval = serde_json::from_str("\"day\"").unwrap();
let from_integer: Interval = serde_json::from_str("0").unwrap();  // 0 = Day

// Always serializes as strings
assert_eq!(serde_json::to_string(&Interval::Day).unwrap(), "\"day\"");
assert_eq!(serde_json::to_string(&Interval::Minute).unwrap(), "\"minute\"");
```

## Running Examples

### KiteConnect REST API sample

```bash
cargo run --example connect_sample
cargo run --example historical_data_typed_example
cargo run --example endpoint_management_demo
```

## โœ… **Completed Features**

- โœ… **Comprehensive serializer structs** for all KiteConnect data structures
  - Full typed models for all API responses (see `/src/models/`)
  - Dual API support: Legacy `JsonValue` + new strongly-typed APIs
  - Type-safe access to holdings, orders, positions, market data, etc.

- โœ… **Advanced reconnection mechanism** with intelligent retry logic
  - Automatic retry with exponential backoff
  - Configurable retry attempts and delays  
  - Built-in rate limiting respecting official API limits
  - Connection pooling and automatic error recovery

## Attribution

**Current Maintainer:** SPRAGE <shauna.pai@gmail.com>

This project was originally created by Joe Paul and other contributors. 
The current version has been significantly rewritten and modernized with:
- Complete async/await implementation
- WASM compatibility
- Enhanced feature flags system
- Comprehensive documentation
- Modern CI/CD pipeline

## License

This software is released into the public domain under The Unlicense. 
See the [LICENSE](LICENSE) file for details.

**No warranties provided** - This software is provided "as is" without warranty of any kind.

## ๐Ÿ“Š Performance Features

### Automatic Caching
```rust
// Instruments data is automatically cached for 1 hour
let instruments1 = client.instruments(None).await?; // API call
let instruments2 = client.instruments(None).await?; // Cached response (fast!)
```

### Intelligent Retry Logic
```rust
// All typed methods automatically retry with exponential backoff
let holdings = client.holdings_typed().await?; // Retries on network errors
```

### Concurrent Operations
```rust
use tokio::try_join;

// Fetch multiple endpoints concurrently
let (holdings, positions, orders) = try_join!(
    client.holdings_typed(),
    client.positions_typed(), 
    client.orders_typed()
)?;
```

## ๐Ÿ”ง Advanced Configuration

```rust
use kiteconnect_async_wasm::connect::{KiteConnect, KiteConnectConfig, RetryConfig, CacheConfig};
use std::time::Duration;

let config = KiteConnectConfig {
    timeout: 60,
    retry_config: RetryConfig {
        max_retries: 5,
        base_delay: Duration::from_millis(200),
        max_delay: Duration::from_secs(10),
        exponential_backoff: true,
    },
    cache_config: Some(CacheConfig {
        enable_instruments_cache: true,
        cache_ttl_minutes: 60,
        max_cache_size: 1000,
    }),
    max_idle_connections: 20,
    idle_timeout: 60,
    ..Default::default()
};

let client = KiteConnect::with_config("api_key", "access_token", config);
```

## ๐ŸŒ WebAssembly Support

```rust
use wasm_bindgen::prelude::*;
use kiteconnect_async_wasm::connect::KiteConnect;

#[wasm_bindgen]
pub async fn get_portfolio_summary() -> Result<String, JsValue> {
    let client = KiteConnect::new("api_key", "access_token");
    
    let holdings = client.holdings_typed().await
        .map_err(|e| JsValue::from_str(&e.to_string()))?;
    
    let total_value: f64 = holdings.iter()
        .map(|h| h.last_price * h.quantity as f64)
        .sum();
        
    Ok(format!("Portfolio value: โ‚น{:.2}", total_value))
}
```

## ๐Ÿ“ˆ API Coverage

### โœ… Complete API Support

| Module | Legacy Methods | Typed Methods | Status |
|--------|---------------|---------------|--------|
| **Authentication** | โœ… | โœ… | Complete |
| **Portfolio** | โœ… | โœ… | Complete |
| **Orders** | โœ… | โœ… | Complete |
| **Market Data** | โœ… | โœ… | Complete |
| **Mutual Funds** | โœ… | โœ… | Complete |

### Key Methods Available

**Portfolio APIs:**
- `holdings()` / `holdings_typed()` - Get stock holdings
- `positions()` / `positions_typed()` - Get trading positions  
- `auctions()` / `auctions_typed()` - Get auction instruments

**Order Management:**
- `orders()` / `orders_typed()` - Get all orders
- `place_order()` / `place_order_typed()` - Place new orders
- `modify_order()` / `modify_order_typed()` - Modify existing orders
- `cancel_order()` - Cancel orders
- `trades()` / `trades_typed()` - Get trade history

**Market Data:**
- `instruments()` - Get instrument master (cached)
- `quote()` / `quote_typed()` - Get real-time quotes
- `ohlc()` / `ohlc_typed()` - Get OHLC data
- `ltp()` / `ltp_typed()` - Get last traded price
- `historical_data()` / `historical_data_typed()` - Get historical candles

**Mutual Funds:**
- `mf_orders()` / `mf_orders_typed()` - Get MF orders
- `place_mf_order()` / `place_mf_order_typed()` - Place MF orders
- `mf_sips()` / `mf_sips_typed()` - Get SIP details
- `place_mf_sip()` / `place_mf_sip_typed()` - Create SIPs
- `mf_holdings()` / `mf_holdings_typed()` - Get MF holdings

## ๐Ÿ”„ Migration from v0.x

All existing code continues to work without changes! For new projects, use the typed APIs:

```rust
// Old way (still works)
let holdings = client.holdings().await?;
let first_isin = holdings["data"][0]["isin"].as_str().unwrap();

// New way (recommended)
let holdings = client.holdings_typed().await?;
let first_isin = &holdings[0].isin; // Type-safe access
```

See [MIGRATION_GUIDE.md](./MIGRATION_GUIDE.md) for detailed migration instructions.

## ๐Ÿ› ๏ธ Error Handling

v1.0.0 provides comprehensive error types:

```rust
use kiteconnect_async_wasm::models::common::KiteError;

match client.place_order_typed(&order_params).await {
    Ok(response) => println!("Order placed: {}", response.order_id),
    Err(KiteError::Authentication(msg)) => {
        // Handle authentication errors
        println!("Please re-authenticate: {}", msg);
    }
    Err(KiteError::Api { status, message, error_type }) => {
        // Handle API errors with context
        println!("API Error {}: {} ({})", status, message, error_type.unwrap_or_default());
    }
    Err(KiteError::Http(reqwest_err)) => {
        // Handle network errors (automatically retried)
        println!("Network error: {}", reqwest_err);
    }
    Err(e) => println!("Other error: {}", e),
}
```

## ๐Ÿ“š Examples

Check out the [examples](./examples/) directory:

- **Basic Usage**: Simple API calls and authentication
- **Portfolio Tracker**: Real-time portfolio monitoring  
- **Order Management**: Placing and managing orders
- **Market Data**: Fetching quotes and historical data
- **WASM Integration**: Using in web applications

## ๐Ÿงช Testing

```bash
# Run all tests
cargo test

# Run with specific features
cargo test --features native
cargo test --features wasm

# Run integration tests (requires network)
cargo test --test integration_tests
```

## ๐Ÿ“‹ Requirements

- **Rust**: 1.70.0 or later
- **Tokio**: For async runtime (native)
- **Valid KiteConnect API credentials**

## ๐Ÿค Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

### Automated Release Process

This repository uses automated releases:

- **Version Management**: Use `./scripts/bump-version.sh [patch|minor|major|VERSION]` to create release branches
- **Automated Publishing**: When PRs are merged to `main`, GitHub Actions automatically:
  - Creates git tags
  - Publishes to crates.io
  - Generates GitHub releases
- **Documentation**: See [`AUTOMATED_RELEASES.md`]AUTOMATED_RELEASES.md for detailed workflow information

```bash
# Example: Bump to next patch version
./scripts/bump-version.sh patch

# Example: Bump to specific version  
./scripts/bump-version.sh 1.0.4
```

## ๐Ÿ“„ License

This project is released under the [Unlicense](http://unlicense.org/) - see the [LICENSE](LICENSE) file for details.

## โš ๏ธ Disclaimer

This is an unofficial library. Use at your own risk. Not affiliated with Zerodha or KiteConnect.

## ๐Ÿ”— Links

- [Official KiteConnect Documentation]https://kite.trade/docs/connect/v3/
- [API Reference]https://docs.rs/kiteconnect-async-wasm
- [Crates.io]https://crates.io/crates/kiteconnect-async-wasm
- [GitHub Repository]https://github.com/SPRAGE/kiteconnect-async-wasm

---

**Built with โค๏ธ in Rust for the trading community**