ig_trading_api 0.3.0

A Rust client for the REST and Streaming APIs from IG.com.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
<div align="center">
  <img src="assets/logo-ig.png" alt="IG Logo" width="200"/>
  
  <h1>IG Trading API</h1>
  <p><strong>A Rust client for the REST and Streaming APIs from IG.com</strong></p>

  [![Crates.io](https://img.shields.io/crates/v/ig_trading_api.svg)](https://crates.io/crates/ig_trading_api)
  [![Documentation](https://img.shields.io/badge/docs-latest-blue.svg)](https://github.com/daniloaz/ig-trading-api#readme)
  [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
  [![Rust](https://img.shields.io/badge/rust-%23000000.svg?style=flat&logo=rust&logoColor=white)](https://www.rust-lang.org/)
  [![Build Status](https://img.shields.io/github/actions/workflow/status/daniloaz/ig-trading-api/rust.yml?branch=main)](https://github.com/daniloaz/ig-trading-api/actions)
  [![GitHub stars](https://img.shields.io/github/stars/daniloaz/ig-trading-api.svg?style=social&label=Star)](https://github.com/daniloaz/ig-trading-api)
</div>

---

## ๐Ÿ“‹ Table of Contents

- [About]#about
- [Features]#features
- [Prerequisites]#prerequisites
- [Installation]#installation
- [Configuration]#configuration
- [Usage]#usage
  - [REST API]#rest-api-example
  - [Streaming API]#streaming-api-example
- [API Coverage]#api-coverage
- [Testing]#testing
- [Project Structure]#project-structure
- [Contributing]#contributing
- [License]#license
- [Acknowledgments]#acknowledgments
- [Contact]#contact

---

## ๐ŸŽฏ About

**IG Trading API** is a comprehensive Rust client library that provides seamless integration with [IG.com](https://www.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]https://www.rust-lang.org/tools/install
- **An IG Trading Account** - [Sign up at IG.com]https://www.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`

---

## ๐Ÿ“ฆ Installation

Add the following to your `Cargo.toml`:

```toml
[dependencies]
ig_trading_api = "0.2.3"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
```

Or use Cargo to add it directly:

```bash
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`:

```bash
cp .env.example .env
```

Edit `.env` with your actual IG credentials:

```bash
# 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:

```yaml
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 `.env` file** to version control (already in `.gitignore`)
- โœ… Keep sensitive credentials in `.env` only
- โœ… Use `.env.example` as 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

```rust
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

```rust
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`](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

```bash
cargo test
```

### Run Specific Tests

```bash
# 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

```bash
RUST_LOG=debug cargo test -- --nocapture
```

**Note**: 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

1. **Report Bugs**: Open an issue describing the bug with steps to reproduce
2. **Suggest Features**: Open an issue with your feature request
3. **Submit Pull Requests**: Fork the repo, create a feature branch, and submit a PR
4. **Improve Documentation**: Help us improve our documentation
5. **Write Tests**: Add more test coverage

### Development Setup

1. Fork and clone the repository:
```bash
git clone https://github.com/your-username/ig-trading-api.git
cd ig-trading-api
```

2. Create a feature branch:
```bash
git checkout -b feature/your-feature-name
```

3. Make your changes and ensure tests pass:
```bash
cargo test
cargo fmt
cargo clippy
```

4. Commit your changes:
```bash
git commit -m "Add: your feature description"
```

5. Push to your fork and submit a pull request

### Code Style

- Follow Rust's official style guide
- Run `cargo fmt` before committing
- Ensure `cargo clippy` passes 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](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]https://www.daniloaz.com/en/
- ๐Ÿ“ง Email: daniloaz@gmail.com
- ๐Ÿ’ผ GitHub: [@daniloaz]https://github.com/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**

---

<div align="center">
  <p>Made with โค๏ธ and Rust</p>
  <p>
    <a href="https://github.com/daniloaz/ig-trading-api/issues">Report Bug</a>
    ยท
    <a href="https://github.com/daniloaz/ig-trading-api/issues">Request Feature</a>
  </p>
  
  <p>โญ Star this repo if you find it useful!</p>
</div>