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 including session refresh and account switching
- Account Management: Access account information, balances, preferences, 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
- Working Orders: Create, update, and manage working orders with support for limit and stop orders
- Watchlists: Full CRUD operations for watchlists including adding/removing instruments
- Client Sentiment: Access client sentiment data for single or multiple markets
- Indicative Costs: Retrieve indicative costs and charges for opening, closing, or editing positions
- Transaction History: Access detailed transaction and activity history
- WebSocket Support: Real-time market data streaming via WebSocket connections
- Advanced Rate Limiting: Sophisticated rate limiting with automatic backoff, concurrent request management, and explicit rate limit error handling
- 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
- Concurrency Management: Built-in semaphores and thread-safe primitives for handling concurrent API requests
- Configurable: Flexible configuration options for different environments (demo/live)
- Persistence: Optional database integration for storing historical data
- Database Support: Integration with SQLx for storing and retrieving transaction data
- Serialization Utilities: Custom serialization helpers for handling IG Markets API responses
Installation
Add this to your Cargo.toml:
[]
= "0.11.1"
= { = "1", = ["full"] } # For async runtime
= "0.15" # For environment variable loading
= "0.1" # For logging
= { = "0.8", = ["runtime-tokio", "postgres"] } # Optional for database support
Requirements
- Rust 1.56 or later (for async/await support)
- An IG Markets account (demo or live)
- API credentials from IG Markets
- PostgreSQL database (optional, for data persistence)
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_TIMEOUT=30 # HTTP request timeout in seconds
IG_WS_URL=wss://demo-apd.marketdatasystems.com # WebSocket URL
IG_WS_RECONNECT=5 # WebSocket reconnect interval in seconds
DATABASE_URL=postgres://user:password@localhost/ig_db # Optional for data persistence
IG_DB_MAX_CONN=5 # Maximum database connections
TX_LOOP_INTERVAL_HOURS=1 # Transaction loop interval in hours
TX_PAGE_SIZE=20 # Transaction page size
TX_DAYS_BACK=7 # Number of days to look back for transactions
Usage Examples
Complete Example Application
Here's a complete example showing how to set up the client, authenticate, and perform various operations:
use ;
use ;
use ;
use ;
use Config;
use ;
use Arc;
use dotenv;
use ;
use FmtSubscriber;
async
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?;
info!;
// Get positions
let positions = account_service.get_positions.await?;
info!;
// Get transaction history
let from_date = now - days;
let to_date = now;
let transactions = account_service.get_transactions.await?;
info!;
Market Data
use ;
// Create market service
let market_service = new;
// Search for markets
let search_result = market_service.search_markets.await?;
info!;
// 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?;
info!;
// Create a limit order
let limit_order = CreateOrderRequest ;
let result = order_service.create_order.await?;
info!;
// 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
Available Services
The library provides the following service traits for interacting with the IG Markets API:
AccountService
get_accounts()- Get all accounts for the authenticated userget_positions()- Get all open positionsget_working_orders()- Get all working ordersget_activity(from, to)- Get account activity for a date rangeget_activity_by_period(period_ms)- Get activity for a period in millisecondsget_transactions(from, to)- Get transaction historyget_preferences()- Get account preferencesupdate_preferences(trailing_stops_enabled)- Update account preferences
MarketService
search_markets(term)- Search for markets by keywordget_market_details(epic)- Get detailed market informationget_multiple_market_details(epics)- Get details for multiple marketsget_historical_prices(epic, resolution, num_points)- Get historical price dataget_historical_prices_by_date_range(epic, resolution, start, end)- Get prices for date rangeget_market_navigation()- Get market navigation hierarchyget_categories()- Get market categoriesget_instruments_by_category(category)- Get instruments in a category
OrderService
create_order(request)- Create a new market orderget_order_confirmation(deal_reference)- Get order confirmationupdate_position(deal_id, update)- Update an existing positionclose_position(request)- Close a positionget_position(deal_id)- Get a single position by deal IDcreate_working_order(request)- Create a working orderupdate_working_order(deal_id, update)- Update an existing working orderdelete_working_order(deal_id)- Delete a working order
WatchlistService (New in 0.11.1)
get_watchlists()- Get all watchlistscreate_watchlist(name, epics)- Create a new watchlistget_watchlist(id)- Get watchlist marketsdelete_watchlist(id)- Delete a watchlistadd_to_watchlist(id, epic)- Add instrument to watchlistremove_from_watchlist(id, epic)- Remove instrument from watchlist
SentimentService (New in 0.11.1)
get_client_sentiment(market_ids)- Get sentiment for multiple marketsget_client_sentiment_by_market(market_id)- Get sentiment for a single marketget_related_sentiment(market_id)- Get sentiment for related markets
CostsService (New in 0.11.1)
get_indicative_costs_open(request)- Get costs for opening a positionget_indicative_costs_close(request)- Get costs for closing a positionget_indicative_costs_edit(request)- Get costs for editing a positionget_costs_history(from, to)- Get historical costsget_durable_medium(quote_reference)- Get durable medium document
OperationsService (New in 0.11.1)
get_client_apps()- Get API application detailsdisable_client_app()- Disable current API key
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
Rate Limiting
The library includes a sophisticated rate limiting system to comply with IG Markets API restrictions:
- Multiple Rate Limit Types: Different limits for trading, non-trading, and historical data requests
- Thread-Safe Implementation: Uses
tokio::sync::Mutexfor safe concurrent access - Automatic Backoff: Dynamically calculates wait times based on request history
- Explicit Rate Limit Handling: Detects and handles rate limit errors from the API
- Global Semaphore: Limits concurrent API requests to prevent overwhelming the API
- Configurable Safety Margins: Adjustable safety margins to stay below API limits
- Rate Limit Error Recovery: Automatic cooldown and recovery when rate limits are exceeded
Example of configuring rate limits:
// Create a configuration with custom rate limit settings
let config = new;
// The rate limiter will automatically be used by all services
let http_client = new;
let auth = new;
// When rate limits are exceeded, the system will automatically:
// 1. Detect the rate limit error from the API
// 2. Enforce a mandatory cooldown period
// 3. Gradually resume requests with appropriate delays
Continuous Integration
Project Structure
├── src/
│ ├── application/ # Core business logic
│ │ ├── interfaces/ # Service trait interfaces
│ │ │ ├── account.rs # Account service trait
│ │ │ ├── costs.rs # Costs service trait (v0.11.1)
│ │ │ ├── market.rs # Market service trait
│ │ │ ├── operations.rs # Operations service trait (v0.11.1)
│ │ │ ├── order.rs # Order service trait
│ │ │ ├── sentiment.rs # Sentiment service trait (v0.11.1)
│ │ │ └── watchlist.rs # Watchlist service trait (v0.11.1)
│ │ ├── auth.rs # Authentication handler
│ │ ├── client.rs # Main API client
│ │ └── config.rs # Configuration handling
│ ├── model/ # Data models
│ │ ├── requests.rs # API request models
│ │ ├── responses.rs # API response models
│ │ └── streaming.rs # Streaming data models
│ ├── presentation/ # Presentation layer
│ │ ├── account.rs # Account presentation
│ │ ├── market.rs # Market presentation
│ │ └── order.rs # Order presentation
│ ├── storage/ # Data persistence
│ │ └── config.rs # Database configuration
│ ├── constants.rs # Global constants
│ ├── error.rs # Error types
│ └── utils/ # Utility functions
│ ├── parsing.rs # Parsing utilities
│ └── retry.rs # Retry utilities
├── examples/ # Example applications
│ ├── chart/ # Chart examples
│ ├── costs/ # Costs examples (v0.11.1)
│ ├── market/ # Market examples
│ ├── orders/ # Order examples
│ ├── positions/ # Position examples
│ ├── sentiment/ # Sentiment examples (v0.11.1)
│ ├── streaming/ # Streaming examples
│ ├── watchlist/ # Watchlist examples (v0.11.1)
│ └── other/ # Other examples
├── tests/ # Tests
│ ├── integration/ # Integration tests
│ └── unit/ # Unit 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.
What's New in 0.11.1
This release adds comprehensive API coverage with the following new services:
New Services
- WatchlistService - Full CRUD operations for watchlists
get_watchlists(),create_watchlist(),get_watchlist(),delete_watchlist()add_to_watchlist(),remove_from_watchlist()
- SentimentService - Client sentiment data
get_client_sentiment(),get_client_sentiment_by_market(),get_related_sentiment()
- CostsService - Indicative costs and charges
get_indicative_costs_open(),get_indicative_costs_close(),get_indicative_costs_edit()get_costs_history(),get_durable_medium()
- OperationsService - API application management
get_client_apps(),disable_client_app()
Extended Services
- AccountService - Added
get_preferences(),update_preferences(),get_activity_by_period() - OrderService - Added
get_position(),update_working_order()
New Examples
examples/watchlist/- Watchlist management examplesexamples/sentiment/- Client sentiment examplesexamples/costs/- Indicative costs examples- Additional examples in
positions/,orders/, andother/
Contribution
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.
Contact Information
If you have any questions, issues, or would like to provide feedback, please feel free to contact the project maintainer:
- Author: Joaquín Béjar García
- Email: jb@taunais.com
- Telegram: @joaquin_bejar
- Repository: https://github.com/joaquinbejar/ig-client
- Documentation: https://docs.rs/ig-client
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.