| Crates.io | kiteconnect-async-wasm |
| lib.rs | kiteconnect-async-wasm |
| version | 1.0.10 |
| created_at | 2025-06-15 06:30:12.681055+00 |
| updated_at | 2025-08-15 13:41:37.577135+00 |
| description | Modern async Rust client for KiteConnect REST APIs with WASM support. Clean, well-documented, and focused on REST-only operations. |
| homepage | https://github.com/SPRAGE/kiteconnect-async-wasm |
| repository | https://github.com/SPRAGE/kiteconnect-async-wasm |
| max_upload_size | |
| id | 1713008 |
| size | 1,021,707 |
โ ๏ธ 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.
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.
Candle deserialization with support for multiple API response formatsHistoricalDataRequest struct with NaiveDateTime precisionThe v1.0.6 release focuses on making historical data fetching production-ready and robust:
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:
calculate_order_margins / _typed (POST /margins/orders)calculate_basket_margins / _typed (POST /margins/basket)calculate_order_charges / _typed (POST /charges/orders)examples/margin_calculation_example.rs[dependencies]
kiteconnect-async-wasm = "1.0.9"
# For WASM targets
# kiteconnect-async-wasm = "1.0.9", features = ["wasm"] }
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(())
}
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(())
}
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(())
}
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\"");
cargo run --example connect_sample
cargo run --example historical_data_typed_example
cargo run --example endpoint_management_demo
โ Comprehensive serializer structs for all KiteConnect data structures
/src/models/)JsonValue + new strongly-typed APIsโ Advanced reconnection mechanism with intelligent retry logic
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:
This software is released into the public domain under The Unlicense. See the LICENSE file for details.
No warranties provided - This software is provided "as is" without warranty of any kind.
// 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!)
// All typed methods automatically retry with exponential backoff
let holdings = client.holdings_typed().await?; // Retries on network errors
use tokio::try_join;
// Fetch multiple endpoints concurrently
let (holdings, positions, orders) = try_join!(
client.holdings_typed(),
client.positions_typed(),
client.orders_typed()
)?;
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);
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))
}
| Module | Legacy Methods | Typed Methods | Status |
|---|---|---|---|
| Authentication | โ | โ | Complete |
| Portfolio | โ | โ | Complete |
| Orders | โ | โ | Complete |
| Market Data | โ | โ | Complete |
| Mutual Funds | โ | โ | Complete |
Portfolio APIs:
holdings() / holdings_typed() - Get stock holdingspositions() / positions_typed() - Get trading positionsauctions() / auctions_typed() - Get auction instrumentsOrder Management:
orders() / orders_typed() - Get all ordersplace_order() / place_order_typed() - Place new ordersmodify_order() / modify_order_typed() - Modify existing orderscancel_order() - Cancel orderstrades() / trades_typed() - Get trade historyMarket Data:
instruments() - Get instrument master (cached)quote() / quote_typed() - Get real-time quotesohlc() / ohlc_typed() - Get OHLC dataltp() / ltp_typed() - Get last traded pricehistorical_data() / historical_data_typed() - Get historical candlesMutual Funds:
mf_orders() / mf_orders_typed() - Get MF ordersplace_mf_order() / place_mf_order_typed() - Place MF ordersmf_sips() / mf_sips_typed() - Get SIP detailsplace_mf_sip() / place_mf_sip_typed() - Create SIPsmf_holdings() / mf_holdings_typed() - Get MF holdingsAll existing code continues to work without changes! For new projects, use the typed APIs:
// 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 for detailed migration instructions.
v1.0.0 provides comprehensive error types:
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),
}
Check out the examples directory:
# 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
git checkout -b feature/amazing-feature)git commit -m 'Add amazing feature')git push origin feature/amazing-feature)This repository uses automated releases:
./scripts/bump-version.sh [patch|minor|major|VERSION] to create release branchesmain, GitHub Actions automatically:
AUTOMATED_RELEASES.md for detailed workflow information# Example: Bump to next patch version
./scripts/bump-version.sh patch
# Example: Bump to specific version
./scripts/bump-version.sh 1.0.4
This project is released under the Unlicense - see the LICENSE file for details.
This is an unofficial library. Use at your own risk. Not affiliated with Zerodha or KiteConnect.
Built with โค๏ธ in Rust for the trading community