Expand description
§dhan-rs
An unofficial Rust client library for the DhanHQ Broker API v2.
§⚠️ AI-Generated Code Disclaimer
This entire crate was generated by AI. While it compiles and follows the DhanHQ API v2 specification, it has not been extensively tested against the live API. Before using this in production or with real money, please:
- Review the source code thoroughly
- Write your own integration tests
- Validate all order placement, modification, and cancellation flows
- Verify WebSocket market feed parsing against real data
The authors accept no responsibility for financial losses incurred through the use of this library.
§Overview
dhan-rs provides a broad, strongly-typed async Rust client for documented
DhanHQ v2 REST endpoints and WebSocket protocols. Dhan’s HTML and linked
OpenAPI sources contain conflicts, and live authenticated compatibility is
not certified:
- 80 REST API methods covering orders, portfolio, Data APIs, Global Stocks, instruments, historical data, option chains, funds, and more
- Live Market Feed with a low-level stream and supervised manager
- Live Order Updates with low-level and managed/reconciling APIs
- Separate 20-level and 200-level Full Market Depth streams
- Rich error handling with
DhanErrorcovering API errors, HTTP errors, JSON deserialization errors, and WebSocket errors
§Quick Start
use dhan_rs::DhanClient;
use dhan_rs::types::orders::PlaceOrderRequest;
use dhan_rs::types::enums::*;
#[tokio::main]
async fn main() -> dhan_rs::Result<()> {
// Create a client with your DhanHQ credentials
let client = DhanClient::new("your-client-id", "your-access-token");
// Place an order
let req = PlaceOrderRequest {
dhan_client_id: "your-client-id".into(),
correlation_id: None,
transaction_type: TransactionType::BUY,
exchange_segment: ExchangeSegment::NSE_EQ,
product_type: ProductType::INTRADAY,
order_type: OrderType::LIMIT,
validity: Validity::DAY,
security_id: "1333".into(),
quantity: 1,
price: Some(1500.0),
disclosed_quantity: None,
trigger_price: None,
after_market_order: None,
amo_time: None,
bo_profit_value: None,
bo_stop_loss_value: None,
};
let response = client.place_order(&req).await?;
println!("Order placed: {:?}", response);
// Fetch holdings
let holdings = client.get_holdings().await?;
println!("Holdings: {} instruments", holdings.len());
Ok(())
}§WebSocket Streaming
§Market Feed (Binary)
use dhan_rs::ws::market_feed::{MarketFeedStream, Instrument};
use dhan_rs::types::enums::FeedRequestCode;
use futures_util::StreamExt;
let mut stream = MarketFeedStream::connect("client-id", "token").await?;
let instruments = vec![Instrument::new("NSE_EQ", "1333")];
stream.subscribe(FeedRequestCode::SubscribeTicker, &instruments).await?;
while let Some(event) = stream.next().await {
println!("{event:?}");
}§Order Updates (JSON)
use dhan_rs::ws::order_update::OrderUpdateStream;
use futures_util::StreamExt;
let mut stream = OrderUpdateStream::connect("client-id", "token").await?;
while let Some(msg) = stream.next().await {
match msg {
Ok(update) => println!("Order update: {:?}", update.Data.Status),
Err(e) => eprintln!("Error: {e}"),
}
}§Module Organization
client— TheDhanClientHTTP client with authenticationerror—DhanErrorenum andResultaliasconstants— Base URLs, WebSocket URLs, rate limit valuestypes— Request/response structs and shared enumsapi— REST endpoint implementations (methods onDhanClient)ws— Standard feed, order updates, and Full Market Depth streaming
§Feature Flags
The optional cli feature enables the ws_check diagnostic binary and its
tracing-subscriber dependency. Library functionality is available by
default.
Re-exports§
pub use client::DhanClient;pub use error::DhanError;pub use error::Result;