๐ Table of Contents
- About
- Features
- Prerequisites
- Installation
- Configuration
- Usage
- API Coverage
- Testing
- Project Structure
- Contributing
- License
- Acknowledgments
- Contact
๐ฏ About
IG Trading API is a comprehensive Rust client library that provides seamless integration with IG.com's REST and Streaming APIs. This library enables developers to build robust trading applications, automated trading strategies, and market analysis tools using the safety and performance benefits of Rust.
IG is a leading online trading platform offering CFDs, spread betting, and share dealing services across various markets including forex, indices, commodities, and cryptocurrencies.
Why Choose This Library?
- ๐ฆ Type-Safe: Leverages Rust's strong type system for compile-time API correctness
- โก Async/Await: Built on modern async Rust (Tokio) for high performance
- ๐ Secure: Implements secure authentication, session management, and proper secrets handling
- ๐ก Real-Time: Supports both REST and Lightstreamer-based streaming APIs
- ๐ ๏ธ Well-Tested: Comprehensive integration tests ensure reliability
- ๐ Well-Documented: Clear examples and documentation for all functionality
- ๐ Security First: Follows industry best practices with environment-based secrets management
โจ Features
REST API Support
- Account Management: Retrieve account information, balances, and preferences
- Session Management: Secure authentication and session handling
- Market Data: Access to real-time and historical market data
- Trading Operations: Place, modify, and close positions
- Order Management: Create and manage working orders
- Watchlists: Create and manage custom watchlists
- Price Alerts: Set up and manage price alerts
Streaming API Support
- Real-Time Market Data: Subscribe to live price updates
- Account Updates: Real-time account balance and position changes
- Trade Confirmations: Instant trade execution confirmations
- Connection Management: Automatic reconnection with exponential backoff
- Signal Handling: Graceful shutdown on SIGINT/SIGTERM
Additional Features
- Error Handling: Comprehensive error handling with detailed error messages
- Configuration Management: YAML-based configuration with environment support
- Colored Console Output: Enhanced logging for better development experience
- HTTP/HTTPS Support: Secure communication with IG's servers
- Demo Account Support: Test your strategies on IG's demo environment
๐ง Prerequisites
Before using this library, ensure you have:
- Rust 1.70.0 or higher - Install Rust
- An IG Trading Account - Sign up at IG.com
- API Key - Obtain from your IG account dashboard
- OpenSSL - Required for TLS connections
- Ubuntu/Debian:
sudo apt-get install pkg-config libssl-dev - Fedora:
sudo dnf install pkg-config openssl-devel - macOS:
brew install openssl
- Ubuntu/Debian:
๐ฆ Installation
Add the following to your Cargo.toml:
[dependencies] ig_trading_api = "0.2.3" tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
Or use Cargo to add it directly:
cargo add ig_trading_api cargo add tokio --features macros,rt-multi-thread
โ๏ธ Configuration
This project follows security best practices by separating sensitive credentials from application configuration:
.env- Contains all sensitive data (API keys, passwords, account numbers, URLs)config.yaml- Contains only non-sensitive application behavior settings
Step 1: Set Up Environment Variables
Copy the .env.example file to .env:
Edit .env with your actual IG credentials:
# IG API Credentials IG_API_KEY=your_actual_api_key_here IG_USERNAME=your_username IG_PASSWORD=your_password # Account Numbers IG_ACCOUNT_NUMBER_DEMO=XXXXX IG_ACCOUNT_NUMBER_LIVE=XXXXX # API URLs (default values, change only if needed) IG_BASE_URL_DEMO=https://demo-api.ig.com/gateway/deal IG_BASE_URL_LIVE=https://api.ig.com/gateway/deal # Execution Environment IG_EXECUTION_ENVIRONMENT=DEMO # or LIVE for production
Step 2: Configure Application Behavior (Optional)
The config.yaml file contains non-sensitive settings. You can modify these if needed:
ig_trading_api: # Automatically log in when session expires auto_login: true # Logging mechanism (StdLogs or TracingLogs) logger: "StdLogs" # Session version for API requests session_version: 2 # Max connection retry attempts for streaming streaming_api_max_connection_attempts: 3
๐ Security Best Practices
- โ
NEVER commit your
.envfile to version control (already in.gitignore) - โ
Keep sensitive credentials in
.envonly - โ
Use
.env.exampleas a template (safe to commit) - โ Use different credentials for DEMO and LIVE environments
- โ In production, consider using a secrets management service (AWS Secrets Manager, HashiCorp Vault, etc.)
- โ Rotate your API keys regularly
๐ Usage
REST API Example
use ig_trading_api::common::ApiConfig; use ig_trading_api::rest_api::RestApi; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { // Load configuration from .env and config.yaml // This automatically loads credentials from environment variables let config = ApiConfig::default(); // Or explicitly load from environment and config let config = ApiConfig::from_env_and_config()?; // Create REST API client let api = RestApi::new(config).await?; // Get account information let (headers, accounts) = api.accounts_get().await?; println!("Accounts: {:#?}", accounts); // Get market data let (headers, market_nav) = api.market_navigation_get(None).await?; println!("Market Navigation: {:#?}", market_nav); // Search for markets let (headers, markets) = api.markets_search_get("EUR/USD".to_string()).await?; println!("Search Results: {:#?}", markets); Ok(()) }
Streaming API Example
use ig_trading_api::common::ApiConfig; use ig_trading_api::streaming_api::StreamingApi; use ig_trading_api::rest_api::RestApi; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { // Load configuration from .env and config.yaml let config = ApiConfig::default(); // Create REST API client let rest_api = RestApi::new(config.clone()).await?; // Create streaming API client let mut streaming_api = StreamingApi::new(rest_api).await?; // Subscribe to market data streaming_api.subscribe_to_market("MARKET:CS.D.EURUSD.MINI.IP").await?; // Connect and start receiving updates streaming_api.connect().await; Ok(()) }
For more detailed examples, check the tests directory.
๐ API Coverage
Implemented REST API Endpoints
| Category | Endpoints | Status |
|---|---|---|
| Session | Login, Logout, Refresh Token | โ |
| Accounts | Get Accounts, Preferences | โ |
| Markets | Navigation, Search, Details | โ |
| Positions | Get, Create, Update, Close | โ |
| Orders | Get, Create, Update, Delete | โ |
| Watchlists | Get, Create, Update, Delete | โ |
| Prices | Historical, Real-time | โ |
Implemented Streaming API Features
| Feature | Status |
|---|---|
| Market Data Subscription | โ |
| Account Updates | โ |
| Trade Confirmations | โ |
| Automatic Reconnection | โ |
| Signal Handling | โ |
๐งช Testing
The project includes comprehensive integration tests for both REST and Streaming APIs.
Run All Tests
Run Specific Tests
# REST API tests only cargo test --test rest_api_integration_tests # Streaming API tests only cargo test --test streaming_api_integration_tests
Run with Logging
RUST_LOG=debug cargo test -- --nocaptureNote: Integration tests require valid IG credentials in your .env file. Tests will run against your demo account by default. Make sure your .env file is properly configured before running tests.
๐ Project Structure
ig_trading_api/
โโโ src/
โ โโโ lib.rs # Library entry point
โ โโโ main.rs # Example executable
โ โโโ common.rs # Common types and utilities
โ โโโ rest_api.rs # REST API implementation
โ โโโ rest_client.rs # HTTP client wrapper
โ โโโ rest_models.rs # REST API data models
โ โโโ rest_regex.rs # Regex utilities
โ โโโ streaming_api.rs # Streaming API implementation
โโโ tests/
โ โโโ rest_api_integration_tests.rs
โ โโโ streaming_api_integration_tests.rs
โโโ assets/ # Logo and images
โโโ .env.example # Environment variables template (COPY TO .env)
โโโ .env # Your secrets (NOT in git)
โโโ config.yaml # Non-sensitive app settings
โโโ config.default.yaml # Default configuration template
โโโ Cargo.toml # Project dependencies
โโโ LICENSE # GPL-3.0 license
โโโ README.md # This file
๐ค Contributing
Contributions are welcome! Here's how you can help:
Ways to Contribute
- Report Bugs: Open an issue describing the bug with steps to reproduce
- Suggest Features: Open an issue with your feature request
- Submit Pull Requests: Fork the repo, create a feature branch, and submit a PR
- Improve Documentation: Help us improve our documentation
- Write Tests: Add more test coverage
Development Setup
- Fork and clone the repository:
git clone https://github.com/your-username/ig-trading-api.git
cd ig-trading-api- Create a feature branch:
git checkout -b feature/your-feature-name
- Make your changes and ensure tests pass:
cargo test
cargo fmt
cargo clippy- Commit your changes:
git commit -m "Add: your feature description"- Push to your fork and submit a pull request
Code Style
- Follow Rust's official style guide
- Run
cargo fmtbefore committing - Ensure
cargo clippypasses with no warnings - Write tests for new functionality
- Update documentation as needed
๐ License
This project is licensed under the GNU General Public License v3.0 - see the LICENSE file for details.
What This Means
- โ You can use this software for any purpose
- โ You can modify the software to suit your needs
- โ You can distribute the software to your friends and neighbors
- โ ๏ธ If you distribute modified versions, you must also distribute the source code under GPL-3.0
- โ ๏ธ You must include the original copyright and license notices
For more information about GPL-3.0, visit: https://www.gnu.org/licenses/gpl-3.0.html
๐ Acknowledgments
- IG Group - For providing the comprehensive trading API
- Rust Community - For the amazing ecosystem and tools
- Lightstreamer - For the real-time streaming technology
- All contributors who have helped improve this project
๐ Contact
Daniel Lรณpez Azaรฑa
- ๐ Website: www.daniloaz.com
- ๐ง Email: daniloaz@gmail.com
- ๐ผ GitHub: @daniloaz
โ ๏ธ Disclaimer
This software is provided "as is", without warranty of any kind. Trading financial instruments involves risk, and you should not trade with money you cannot afford to lose. This library is not affiliated with or endorsed by IG Group. Always test your code thoroughly on a demo account before using it in a live trading environment.
USE AT YOUR OWN RISK