Daniel López Azaña

Theme

Social Media

IG.com Rust Client - Open Source SDK for Algorithmic Trading

Professional Rust SDK for IG.com REST and Streaming APIs. First complete Rust client library enabling integration with algorithmic trading platforms, account management, order execution, and real-time market data. Published on crates.io as open-source contribution.

Available on:crates.iocrates.ioGitHub

When developing algorithmic trading systems in Rust for a financial sector client, I encountered a fundamental gap: no Rust client library existed for IG.com, one of the leading brokers in CFDs, options, and futures with global presence. Rather than implementing a proprietary closed solution, I developed a complete Rust client SDK and released it as open-source software to benefit the entire community of developers interested in quantitative finance and algorithmic trading.

IG.com Rust client SDK on crates.io

The Challenge: Professional Integration with IG.com from Rust

What is IG.com?

IG.com logoIG Group - Global leader in online trading since 1974

IG.com (IG Group) is a global online trading broker founded in 1974, with over 300,000 active clients and regulation in multiple jurisdictions (FCA, ASIC, MAS, among others). It provides access to more than 17,000 global markets:

Financial Products:

  • CFDs (Contracts for Difference) on indices, shares, commodities, cryptocurrencies
  • Options and barrier options
  • Futures
  • Forex with competitive spreads
  • Turbos and warrants

Primary Use Cases:

  • Algorithmic trading - automated execution of quantitative strategies
  • Portfolio management - programmatic position administration
  • Market analysis - access to historical and real-time data
  • Backtesting - strategy validation with real data
  • High-frequency trading - rapid order execution

IG.com API:

  • Complete REST API for account management, orders, and queries
  • Streaming API based on Lightstreamer for real-time market data
  • Comprehensive technical documentation with examples in multiple languages
  • Sandbox environment for testing before live trading

The Gap in the Rust Ecosystem

IG.com provides official client libraries and examples for:

  • ✅ Java
  • ✅ C# (.NET)
  • ✅ Python
  • ✅ JavaScript/TypeScript
  • Rust - NONE

The Problem: Rust is consolidating as the preferred language for high-performance trading systems due to:

  • Performance comparable to C/C++ without sacrificing safety
  • No garbage collector (no unpredictable pauses)
  • Safe concurrency without race conditions
  • Zero-cost abstractions
  • Modern ecosystem with excellent tooling

However, without a Rust client for IG.com, developers had to choose between:

  1. Use another language for IG integration (adding stack complexity)
  2. Implement a client from scratch (expensive, consuming weeks of development)
  3. Switch brokers (losing IG.com advantages)
  4. Abandon Rust for this project (losing its benefits)

No option was acceptable for a professional system requiring Rust’s guarantees and IG.com’s robustness.

The Solution: A Complete Rust SDK

I developed ig_trading_api, a complete Rust SDK implementing both IG.com’s REST API and Streaming API. The library provides a type-safe, asynchronous interface that feels natural to Rust developers while maintaining full compatibility with IG’s platform.

Architecture and Design Decisions

Core Technologies:

ComponentTechnologyPurpose
Async RuntimeTokioNon-blocking I/O and concurrent handling
HTTP ClientreqwestREST API communication
Streaminglightstreamer-clientReal-time market data
Serializationserde/serde_jsonType-safe data handling
Configurationserde_yamlCredentials and configuration management
ValidationregexFormat and pattern validation

Key Technical Decisions

1. Modular Architecture

The SDK is organized in clearly separated modules:

Code Structure:

ig_trading_api/
├── rest_client.rs    # Main REST client
├── rest_api.rs       # REST API endpoints
├── rest_models.rs    # Type-safe data models
├── streaming_api.rs  # Real-time streaming API
├── common.rs         # Shared utilities
└── rest_regex.rs     # Pattern validation

Benefits:

  • Clear separation of concerns
  • Facilitates maintenance and extensions
  • Allows selective use of functionality
  • Independent module testing

2. Type-Safe REST API Management

All IG.com endpoints are modeled with Rust types that guarantee compile-time correctness:

// Data models with automatic validation
#[derive(Debug, Serialize, Deserialize)]
pub struct AccountInfo {
    pub account_id: String,
    pub account_name: String,
    pub balance: Balance,
    pub currency: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Position {
    pub deal_id: String,
    pub epic: String,
    pub direction: Direction,
    pub size: f64,
    pub level: f64,
}

Advantages:

  • Compile-time error prevention
  • Complete IDE autocompletion
  • Safe refactoring
  • Automatic inline documentation

3. Authentication and Session Management

Robust authentication system with automatic token handling:

pub struct IGRestClient {
    config: Config,
    client: reqwest::Client,
    auth_headers: Option<AuthHeaders>,
}

impl IGRestClient {
    pub async fn authenticate(&mut self) -> Result<(), IGError> {
        // Authentication with API key and credentials
        // Automatic CST and X-SECURITY-TOKEN header management
        // Automatic session renewal if expired
    }
}

Features:

  • Automatic login with credentials from YAML file
  • Transparent renewal of expired tokens
  • Multiple account handling (live/demo)
  • Secure secrets management

Implemented Functionality

1. Complete REST API

Account Management:

  • Retrieve account information
  • Query balances and margins
  • List available accounts
  • Switch between accounts (live/demo)

Order and Position Management:

  • Create new positions (BUY/SELL)
  • Modify existing positions
  • Partial or full position closure
  • Configure stops and limits
  • Query open positions
  • Trading history

Market Data:

  • Search instruments by name
  • Complete instrument details (epics, spreads, schedules)
  • Real-time prices via polling
  • Historical data (OHLC candles)
  • Market information (open/closed, restrictions)

Pending Orders:

  • Create limit orders
  • Configure stop orders
  • Modify existing orders
  • Cancel orders
  • Query active orders

2. Real-Time Streaming API

Complete integration with Lightstreamer for live data:

Price Streaming:

  • Subscribe to real-time bid/ask prices
  • Continuous updates for multiple instruments
  • Minimal latency (millisecond updates)
  • Automatic reconnection handling

Account Streaming:

  • Monitor balance changes
  • Real-time P&L notifications
  • Margin call alerts
  • Executed order events
// Streaming subscription example
pub async fn subscribe_to_market(
    &self,
    epic: &str,
) -> Result<(), StreamingError> {
    let subscription = create_price_subscription(epic);
    self.lightstreamer_client
        .subscribe(subscription)
        .await?;
    Ok(())
}

3. Flexible Configuration

YAML file-based configuration system:

ig_api:
  base_url: "https://demo-api.ig.com/gateway/deal"
  api_key: "your-api-key"
  username: "your-username"
  password: "your-password"
  account_id: "your-account"
  
streaming:
  adapter_set: "DEFAULT"
  lightstreamer_endpoint: "https://demo-apd.marketdatasys.com"

Benefits:

  • Separation of code and configuration
  • Multiple environments (demo/live)
  • Secure credential management
  • Easy CI/CD configuration

4. Production-Ready Features

Robust SecuritySecure credential and session token management.
High PerformanceAsynchronous architecture for concurrent operations.
Type-Safe APIAll endpoints modeled with safe Rust types.
Comprehensive DocumentationUsage examples and exhaustive documentation.

Real-World Application: Algorithmic Trading System

This SDK was developed as part of a professional algorithmic trading system that required:

System Requirements:

  • Automated execution of complex quantitative strategies
  • Continuous monitoring of multiple financial instruments
  • Minimal latency in order execution
  • Real-time risk management
  • High reliability and fault recovery
  • Comprehensive logging for auditing

Results: The IG.com Rust client successfully powers automated trading operations in production, enabling:

  • Multi-instrument strategy execution
  • Automatic dynamic stop management
  • Position rebalancing based on quantitative signals
  • Real-time P&L monitoring
  • 24/7 operation with minimal supervision

Open Source Contribution

Why Open Source?

Although developed for a confidential financial sector client, I made the strategic decision to release this library as open-source software for fundamental reasons:

1. Benefit for Rust Fintech Community

  • Fills a critical void for Rust trading system developers
  • Facilitates Rust adoption in quantitative finance
  • Reduces barriers to entry for new projects
  • Avoids duplication of efforts between teams

2. Quality Through Collaboration

  • Community code review detects bugs and improves quality
  • Contributions from other developers enrich functionality
  • Broader testing in diverse scenarios
  • Continuous improvement based on real feedback

3. Rust Ecosystem Advancement

  • Demonstrates Rust viability for professional finance
  • Establishes patterns and best practices for financial APIs
  • Attracts talent and projects to Rust ecosystem
  • Fosters collaboration between sectors (finance + open source)

4. Transparency and Trust

  • Open code allows complete auditing
  • Community can verify security
  • No “black boxes” in critical financial code

Publication and Availability

Published on crates.io:

  • Package: ig_trading_api
  • Installation: cargo add ig_trading_api
  • Documentation: Included in GitHub repository

ig_trading_api package page on crates.io

Open Source Repository:

Community Adoption:

The library has been adopted by Rust community developers interested in algorithmic trading and quantitative finance:

ig_trading_api package statistics on crates.io

Basic Usage Example

Here’s an example demonstrating the library’s main capabilities:

use ig_trading_api::rest_client::IGRestClient;
use ig_trading_api::rest_models::{Direction, OrderType};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create client and authenticate
    let mut client = IGRestClient::new("config.yaml")?;
    client.authenticate().await?;
    
    // Get account information
    let account = client.get_account_info().await?;
    println!("Balance: {} {}", account.balance.available, account.currency);
    
    // Search for an instrument
    let instruments = client.search_markets("EUR/USD").await?;
    let epic = &instruments[0].epic;
    
    // Open position
    let position = client.create_position(
        epic,
        Direction::Buy,
        1.0,  // size
        OrderType::Market,
        None, // stop loss
        None, // take profit
    ).await?;
    
    println!("Position opened: {}", position.deal_id);
    
    // Query open positions
    let positions = client.get_positions().await?;
    for pos in positions {
        println!("Epic: {}, P&L: {}", pos.epic, pos.profit);
    }
    
    Ok(())
}

Key Features Demonstrated:

  • Simple authentication
  • Intuitive, expressive API
  • Error handling with Result
  • Full async/await support
  • Type safety in all operations

Technical Achievements

First and only Rust client library for the complete IG.com API.
Enabled Rust adoption for algorithmic trading with IG.com.
Implements both REST API and Streaming API with full support.
Production-tested in real algorithmic trading systems with real capital.
Released as open-source contribution to the Rust fintech community.

Future Development

The library provides a solid foundation with opportunities for improvement:

Current Status (v0.2.x):

  • Complete REST API implementation
  • Functional Streaming API with Lightstreamer
  • Authentication and session management
  • CRUD operations on positions and orders
  • Verified production stability

Potential Future Enhancements:

  • Expanded endpoint coverage
  • Improved error handling and retry logic
  • Performance optimizations for HFT
  • Support for more specialized order types
  • More comprehensive automated testing
  • Algorithmic strategy examples
  • Integration with backtesting frameworks

Community contributions are welcome for any improvement or extension.

Conclusion

The IG.com Rust Client represents a strategic contribution to the Rust financial ecosystem, enabling developers to build professional algorithmic trading systems with one of the industry’s most respected brokers. By releasing this library as open-source software, I’ve helped bridge the gap between Rust’s capabilities and established trading platforms.

This project demonstrates:

  • Technical depth in complex financial APIs and async Rust
  • Strategic vision in identifying and addressing ecosystem gaps
  • Community commitment through open-source contribution
  • Real experience in production financial systems with real capital

The library is actively maintained and ready for any project requiring IG.com integration from Rust, whether for algorithmic trading, backtesting, quantitative analysis, or portfolio management.


Need trading systems development or quantitative finance expertise?

For projects requiring:

  • Algorithmic trading systems in Rust or Python.
  • Broker and financial platform integration.
  • Quantitative strategy development and backtesting.
  • High-performance, low-latency financial APIs.

I bring deep expertise in financial systems development, high-performance architectures, and quantitative finance. Available for consulting and development on fintech and trading projects.

Get in touch →

Daniel López Azaña

About the author

Daniel López Azaña

Tech entrepreneur and cloud architect with over 20 years of experience transforming infrastructures and automating processes.

Specialist in AI/LLM integration, Rust and Python development, and AWS & GCP architecture. Restless mind, idea generator, and passionate about technological innovation and AI.

Comments

Be the first to comment

Submit comment

Have a Similar Project in Mind?

Let's discuss how I can help you achieve your goals

Start a Conversation