Crate kiteticker_async_manager

Source
Expand description

§KiteTicker Async Manager

High-performance async WebSocket client for the Kite Connect API with multi-connection support and dynamic subscription management.

§Features

  • 🚀 Multi-Connection Support - Utilize all 3 allowed WebSocket connections (9,000 symbol capacity)
  • ⚡ High Performance - Dedicated parser tasks, optimized buffers, sub-microsecond latency
  • 🔄 Dynamic Subscriptions - Add/remove symbols at runtime without reconnection
  • 📊 Load Balancing - Automatic symbol distribution across connections
  • 💪 Production Ready - Comprehensive error handling, health monitoring, reconnection
  • 🔧 Async-First Design - Built with Tokio, follows Rust async best practices

§Quick Start

use kiteticker_async_manager::{KiteTickerManager, KiteManagerConfig, Mode, TickerMessage};

#[tokio::main]
async fn main() -> Result<(), String> {
    // Setup credentials
    let api_key = std::env::var("KITE_API_KEY").unwrap();
    let access_token = std::env::var("KITE_ACCESS_TOKEN").unwrap();
     
    // Create high-performance manager
    let config = KiteManagerConfig {
        max_connections: 3,
        max_symbols_per_connection: 3000,
        enable_dedicated_parsers: true,
        default_mode: Mode::LTP,
        ..Default::default()
    };
     
    // Start manager
    let mut manager = KiteTickerManager::new(api_key, access_token, config);
    manager.start().await?;
     
    // Subscribe to symbols (automatically distributed)
    let symbols = vec![256265, 408065, 738561]; // NIFTY 50, HDFC Bank, Reliance
    manager.subscribe_symbols(&symbols, Some(Mode::Quote)).await?;
     
    // Process data from independent channels
    let channels = manager.get_all_channels();
    for (channel_id, mut receiver) in channels {
        tokio::spawn(async move {
            while let Ok(message) = receiver.recv().await {
                if let TickerMessage::Ticks(ticks) = message {
                    for tick in ticks {
                        println!("Channel {:?}: {} @ ₹{:.2}",
                            channel_id, 
                            tick.instrument_token,
                            tick.content.last_price.unwrap_or(0.0));
                    }
                }
            }
        });
    }
     
    // Dynamic operations
    manager.subscribe_symbols(&[5633, 884737], Some(Mode::Full)).await?;  // Add
    manager.unsubscribe_symbols(&[408065]).await?;                        // Remove
    manager.change_mode(&[256265], Mode::Full).await?;                    // Change mode
     
    Ok(())
}

§Single Connection Usage

use kiteticker_async_manager::{KiteTickerAsync, Mode, TickerMessage};

#[tokio::main]
async fn main() -> Result<(), String> {
    let api_key = std::env::var("KITE_API_KEY").unwrap();
    let access_token = std::env::var("KITE_ACCESS_TOKEN").unwrap();
     
    // Connect to WebSocket
    let ticker = KiteTickerAsync::connect(&api_key, &access_token).await?;
     
    // Subscribe to symbols
    let symbols = vec![256265, 408065]; // NIFTY 50, HDFC Bank
    let mut subscriber = ticker.subscribe(&symbols, Some(Mode::LTP)).await?;
     
    // Receive data
    while let Ok(Some(message)) = subscriber.next_message().await {
        if let TickerMessage::Ticks(ticks) = message {
            for tick in ticks {
                println!("Symbol {}: ₹{:.2}", 
                    tick.instrument_token,
                    tick.content.last_price.unwrap_or(0.0));
            }
        }
    }
     
    Ok(())
}

§Performance Comparison

FeatureSingle ConnectionMulti-Connection ManagerImprovement
Max Symbols3,0009,0003x capacity
ThroughputLimited by 1 connection3 parallel connections3x throughput
Latency~5-10µs~1-2µs5x faster
ResilienceSingle point of failure3 independent connectionsHigh availability
Dynamic OpsManual reconnectionRuntime add/removeZero downtime

§Architecture

The library provides two main components:

§1. KiteTickerAsync - Single WebSocket Connection

  • Direct WebSocket client for simple use cases
  • Up to 3,000 symbols per connection
  • Manual connection management
  • Manages up to 3 WebSocket connections automatically
  • Supports up to 9,000 symbols total
  • Dynamic subscription management
  • Load balancing and health monitoring
  • High-performance optimizations

§Subscription Modes

The library supports three subscription modes:

  • Mode::LTP - Last traded price only (minimal bandwidth)
  • Mode::Quote - Price + volume + OHLC (standard data)
  • Mode::Full - Complete market depth (maximum data)

§Examples

See the examples directory for:

  • Basic Examples - Simple usage patterns
  • Advanced Examples - Complex multi-connection scenarios
  • Performance Examples - Optimization and benchmarking

§Documentation

Re-exports§

pub use ticker::KiteTickerAsync;
pub use ticker::KiteTickerSubscriber;
pub use manager::KiteTickerManager;
pub use manager::KiteManagerConfig;
pub use manager::ChannelId;
pub use manager::ManagerStats;
pub use manager::HealthSummary;

Modules§

manager
ticker

Structs§

Depth
Market depth packet structure
DepthItem
Structure for each market depth entry
OHLC
OHLC packet structure
Order
ParseTickError
Errors that can occur while parsing tick data
Request
Websocket request structure
TextMessage
Postback and non-binary message structure
Tick
Quote packet structure
TickMessage
Parsed quote packet

Enums§

Exchange
Exchange options
Mode
Modes in which packets are streamed
OrderStatus
OrderTransactionType
OrderValidity
TickerMessage
Parsed message from websocket