IG Markets API Client for Rust
A comprehensive Rust client for interacting with the IG Markets trading API. This library provides a type-safe and ergonomic way to access IG Markets' REST and WebSocket APIs for trading and market data retrieval.
Overview
The IG Markets API Client for Rust is designed to provide a reliable and efficient interface to the IG Markets trading platform. It handles authentication, session management, and all API interactions while providing a clean, idiomatic Rust interface for developers.
Features
- Authentication: Secure authentication with the IG Markets API using OAuth2
- Account Management: Access account information, balances, and activity history
- Market Data: Retrieve market data, prices, instrument details, and historical prices
- Order Management: Create, modify, and close positions and orders with various order types
- Transaction History: Access detailed transaction and activity history
- WebSocket Support: Real-time market data streaming via WebSocket connections
- Fully Documented: Comprehensive documentation for all components and methods
- Error Handling: Robust error handling and reporting with detailed error types
- Type Safety: Strong type checking for API requests and responses
- Async Support: Built with async/await for efficient non-blocking operations
- Configurable: Flexible configuration options for different environments (demo/live)
- Persistence: Optional database integration for storing historical data
Installation
Add this to your Cargo.toml:
[]
= "0.1.3"
= { = "1", = ["full"] } # For async runtime
= "0.15" # For environment variable loading
= "0.1" # For logging
Requirements
- Rust 1.56 or later (for async/await support)
- An IG Markets account (demo or live)
- API credentials from IG Markets
Configuration
Create a .env file in your project root with the following variables:
IG_USERNAME=your_username
IG_PASSWORD=your_password
IG_API_KEY=your_api_key
IG_ACCOUNT_ID=your_account_id
IG_BASE_URL=https://demo-api.ig.com/gateway/deal # Use demo or live as needed
IG_WEBSOCKET_URL=wss://demo-apd.marketdatasystems.com
DATABASE_URL=postgres://user:password@localhost/ig_db # Optional for data persistence
```rust
## Usage Examples
### Complete Example Application
Here's a complete example showing how to set up the client, authenticate, and perform various operations:
```rust,ignore
use ig_client::application::services::account_service::{AccountService, IgAccountService};
use ig_client::application::services::market_service::{IgMarketService, MarketService};
use ig_client::application::services::order_service::{IgOrderService, OrderService};
use ig_client::application::models::order::{CreateOrderRequest, Direction};
use ig_client::config::Config;
use ig_client::session::auth::IgAuth;
use std::sync::Arc;
use dotenv::dotenv;
use tracing::{info, error, Level};
use tracing_subscriber::FmtSubscriber;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Initialize logging
let subscriber = FmtSubscriber::builder()
.with_max_level(Level::INFO)
.finish();
tracing::subscriber::set_global_default(subscriber)?;
// Load environment variables
dotenv().ok();
info!("Environment variables loaded");
// Create configuration
let config = Arc::new(Config::new());
info!("Configuration created");
// Authenticate
let auth = IgAuth::new(config.clone());
let session = auth.authenticate().await?;
info!("Authentication successful");
// Create services
let account_service = IgAccountService::new(config.clone());
let market_service = IgMarketService::new(config.clone());
let order_service = IgOrderService::new(config.clone());
// Get account information
let account_info = account_service.get_accounts(&session).await?;
info!("Account information retrieved: {} accounts", account_info.accounts.len());
// Search for a market
let search_result = market_service.search_markets(&session, "EUR/USD").await?;
info!("Found {} markets matching search", search_result.markets.len());
if let Some(market) = search_result.markets.first() {
info!("Selected market: {} ({})", market.instrument_name, market.epic);
// Get market details
let market_details = market_service.get_market_details(&session, &market.epic).await?;
info!("Market details retrieved: {}", market_details.instrument.name);
// Create and place a demo order (if this is a demo account)
if session.account_type == "DEMO" {
let order = CreateOrderRequest::market(
market.epic.clone(),
Direction::Buy,
0.1, // Small size for demo
None,
None,
);
let order_result = order_service.create_order(&session, &order).await?;
info!("Order placed: deal reference = {}", order_result.deal_reference);
// Get positions
let positions = account_service.get_positions(&session).await?;
info!("Current positions: {}", positions.positions.len());
}
}
info!("Example completed successfully");
Ok(())
}
Authentication
use IgAuth;
use Config;
use Arc;
async
Getting Account Information
use ;
use Arc;
// Create account service
let account_service = new;
// Get account information
let account_info = account_service.get_accounts.await?;
println!;
// Get positions
let positions = account_service.get_positions.await?;
println!;
// Get transaction history
let from_date = now - days;
let to_date = now;
let transactions = account_service.get_transactions.await?;
println!;
Market Data
use ;
// Create market service
let market_service = new;
// Search for markets
let search_result = market_service.search_markets.await?;
println!;
// Get market details
if let Some = search_result.markets.first
Placing and Managing Orders
use ;
use ;
// Create order service
let order_service = new;
// Create a market order
let market_order = market;
// Place the order
let result = order_service.create_order.await?;
println!;
// Create a limit order
let limit_order = CreateOrderRequest ;
let result = order_service.create_order.await?;
println!;
// Close a position
let positions = account_service.get_positions.await?;
if let Some = positions.positions.first
WebSocket Streaming
use ;
use MarketData;
use Arc;
use mpsc;
// Create a channel to receive market updates
let = channel;
// Create a callback function to handle market updates
let callback: MarketListenerCallback = new;
// Create and start the market listener
let listener = new;
listener.connect.await?;
// Subscribe to market updates
let epics = vec!;
listener.subscribe.await?;
// Process market updates
while let Some = rx.recv.await
Documentation
Comprehensive documentation is available for all components of the library. The documentation includes detailed explanations of all modules, structs, and functions, along with examples of how to use them.
API Documentation
You can access the API documentation on docs.rs or generate it locally with:
Architecture
The library is organized into several modules:
- config: Configuration handling and environment variable loading
- session: Authentication and session management
- application: Core business logic and services
- models: Data structures for API requests and responses
- services: Service implementations for different API areas
- transport: HTTP and WebSocket communication with the IG Markets API
- utils: Utility functions for parsing, logging, etc.
- error: Error types and handling
Development
This project includes a comprehensive Makefile with commands for common development tasks.
Building
Testing
Code Quality
Documentation
Code Coverage
Benchmarking
Continuous Integration
Project Structure
├── src/
│ ├── application/ # Core business logic
│ │ ├── models/ # Data models
│ │ │ ├── account.rs # Account-related models
│ │ │ ├── market.rs # Market data models
│ │ │ ├── order.rs # Order models
│ │ │ └── transaction.rs # Transaction models
│ │ └── services/ # Service implementations
│ │ ├── account_service.rs
│ │ ├── market_service.rs
│ │ └── order_service.rs
│ ├── config.rs # Configuration handling
│ ├── error.rs # Error types
│ ├── session/ # Authentication and session
│ │ └── auth.rs # Authentication handler
│ ├── transport/ # API communication
│ │ ├── http.rs # HTTP client
│ │ └── websocket.rs # WebSocket client
│ └── utils/ # Utility functions
├── examples/ # Example applications
├── tests/ # Integration tests
└── Makefile # Development commands
Contributing
Contributions are welcome! Here's how you can contribute:
- Fork the repository
- Create a feature branch:
git checkout -b feature/my-feature - Make your changes and commit them:
git commit -m 'Add some feature' - Run the tests:
make test - Push to the branch:
git push origin feature/my-feature - Submit a pull request
Please make sure your code passes all tests and linting checks before submitting a pull request.
Contribution and Contact
We welcome contributions to this project! If you would like to contribute, please follow these steps:
- Fork the repository.
- Create a new branch for your feature or bug fix.
- Make your changes and ensure that the project still builds and all tests pass.
- Commit your changes and push your branch to your forked repository.
- Submit a pull request to the main repository.
If you have any questions, issues, or would like to provide feedback, please feel free to contact the project maintainer:
Joaquín Béjar García
- Email: jb@taunais.com
- GitHub: joaquinbejar
We appreciate your interest and look forward to your contributions!
✍️ License
Licensed under MIT license
Disclaimer
This software is not officially associated with IG Markets. Trading financial instruments carries risk, and this library is provided as-is without any guarantees. Always test thoroughly with a demo account before using in a live trading environment.