Skip to main content

Crate dhan_rs

Crate dhan_rs 

Source
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 complete, strongly-typed async Rust client for all DhanHQ v2 REST endpoints and WebSocket streams:

  • 55+ REST API methods covering orders, portfolio, market data, historical data, option chains, funds, statements, and more
  • Live Market Feed via WebSocket with zero-copy binary packet parsing
  • Live Order Updates via WebSocket with JSON message streaming
  • Rich error handling with DhanError covering 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 — The DhanClient HTTP client with authentication
  • errorDhanError enum and Result alias
  • constants — Base URLs, WebSocket URLs, rate limit values
  • types — Request/response structs and shared enums
  • api — REST endpoint implementations (methods on DhanClient)
  • ws — WebSocket streaming (market feed + order updates)

§Feature Flags

This crate currently has no optional feature flags. All functionality is included by default.

Re-exports§

pub use client::DhanClient;
pub use error::DhanError;
pub use error::Result;

Modules§

api
REST API endpoint implementations.
client
Core HTTP client for the DhanHQ REST API v2.
constants
Constants for the DhanHQ API v2.
error
Error types for the dhan-rs crate.
types
Request and response types for the DhanHQ API v2.
ws
WebSocket modules for real-time data streaming.