- About
- Features
- Prerequisites
- Installation
- Configuration
- Usage
- API Coverage
- Testing
- Project Structure
- Contributing
- License
- Acknowledgments
- Contact
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.
- π¦ 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
- 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
- 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
- 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
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:
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-threadThis 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
Copy the .env.example file to .env:
cp .env.example .envEdit .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 productionThe 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- β
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
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(())
}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.
| 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 | β |
| Feature | Status |
|---|---|
| Market Data Subscription | β |
| Account Updates | β |
| Trade Confirmations | β |
| Automatic Reconnection | β |
| Signal Handling | β |
The project includes comprehensive integration tests for both REST and Streaming APIs.
cargo test# REST API tests only
cargo test --test rest_api_integration_tests
# Streaming API tests only
cargo test --test streaming_api_integration_testsRUST_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.
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
Contributions are welcome! Here's how you can help:
- 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
- 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
- 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
This project is licensed under the GNU General Public License v3.0 - see the LICENSE file for details.
- β 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
- 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
Daniel LΓ³pez AzaΓ±a
- π Website: www.daniloaz.com
- π§ Email: daniloaz@gmail.com
- πΌ GitHub: @daniloaz
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
