ig_trading_api 0.2.1

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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
use crate::common::*;
use crate::rest_models::{
    AuthenticationPostRequest, AuthenticationPostResponseV3, ValidateRequest, ValidateResponse,
};
use reqwest::header::{HeaderMap, HeaderValue};
use reqwest::StatusCode;
use serde::Serialize;
use serde_json::{json, Value};
use std::error::Error;

/// Default session version if not explicitly set.
const DEFAULT_SESSION_VERSION: usize = 2;
/// Default auto-login behavior if not explicitly set.
const DEFAULT_AUTO_LOGIN: bool = true;

/// Struct to represent the REST API client.
#[derive(Clone, Debug)]
pub struct RestClient {
    /// The API authentication headers.
    pub auth_headers: Option<HeaderMap>,
    /// Automatically log in to the API on instantiation and when the session expires.
    pub auto_login: bool,
    /// The API base URL based on the account type.
    pub base_url: String,
    /// The reqwest client instance.
    pub client: reqwest::Client,
    /// Common headers used for all requests.
    pub common_headers: HeaderMap,
    /// The API configuration.
    pub config: ApiConfig,
    /// The Lightstreamer endpoint to use for streaming data from the selected execution environment.
    pub lightstreamer_endpoint: String,
    /// The refresh token to use for refreshing the session when session_version is 3.
    pub refresh_token: Option<String>,
    /// Session version.
    pub session_version: usize,
}

/// Implementation for the RestClient struct.
impl RestClient {
    /// Send a DELETE request to the API.
    pub async fn delete(
        &self,
        method: String,
        api_version: Option<usize>,
        body: &Option<impl Serialize + ValidateRequest>,
    ) -> Result<(HeaderMap, Value), Box<dyn Error>> {
        // Default API version is 1.
        let version = api_version.unwrap_or(1).to_string();
        // Validate the body.
        if let Some(body) = body {
            body.validate()?;
        }
        // Convert the body to a serde_json::Value.
        let body = serde_json::to_value(body)?;

        let response = self
            .client
            .post(&format!("{}/{}", &self.base_url, method))
            .json(&body)
            .headers(self.auth_headers.clone().unwrap_or(HeaderMap::new()))
            .headers(self.common_headers.clone())
            .header("Version", version)
            .header("_method", "DELETE".to_string())
            .send()
            .await?;

        // Check the response status code.
        match response.status() {
            // If the status code is 204 No Content, return success.
            StatusCode::NO_CONTENT => Ok((response.headers().clone(), json!({}))),
            // If the status code is 200 OK, return success and response body.
            StatusCode::OK => Ok((response.headers().clone(), response.json().await?)),
            // If the status code is other, return an error.
            _ => Err(Box::new(ApiError {
                message: format!(
                    "DELETE operation using method '{}' failed with status code: {:?} - {:?}",
                    method,
                    response.status(),
                    response.text().await?
                ),
            })),
        }
    }

    /// Create a new RestClient instance.
    pub async fn new(config: ApiConfig) -> Result<Self, Box<dyn Error>> {
        // Determine the API base URL based on the account type.
        let base_url = match config.execution_environment {
            ExecutionEnvironment::Demo => config.base_url_demo.clone(),
            ExecutionEnvironment::Live => config.base_url_live.clone(),
        };

        // Default session version is DEFAULT_SESSION_VERSION.
        let session_version = config.session_version.unwrap_or(DEFAULT_SESSION_VERSION);
        // Default auto_login is DEFAULT_AUTO_LOGIN.
        let auto_login = config.auto_login.unwrap_or(DEFAULT_AUTO_LOGIN);

        // Set the common headers.
        let mut common_headers = HeaderMap::new();
        common_headers.insert("Accept", "application/json; charset=UTF-8".parse()?);
        common_headers.insert("Content-Type", "application/json; charset=UTF-8".parse()?);
        common_headers.insert("X-IG-API-KEY", config.api_key.as_str().parse()?);

        // Create a new RestClient instance.
        let mut rest_client = Self {
            auth_headers: None,
            auto_login,
            base_url,
            client: reqwest::Client::new(),
            common_headers,
            config,
            lightstreamer_endpoint: "".to_string(),
            refresh_token: None,
            session_version,
        };

        // If auto_login is true, then login to the API.
        if auto_login {
            let _ = rest_client.login().await?;
        };

        Ok(rest_client)
    }

    /// Send a GET request to the API.
    pub async fn get(
        &self,
        method: String,
        api_version: Option<usize>,
        params: &Option<impl Serialize + ValidateRequest>,
    ) -> Result<(HeaderMap, Value), Box<dyn Error>> {
        // Default API version is 1.
        let api_version = api_version.unwrap_or(1).to_string();
        // Validate the params.
        if let Some(params) = params {
            params.validate()?;
        }
        // Convert params to a query string.
        let query_string = params_to_query_string(params)?;

        let url = if query_string.is_empty() {
            format!("{}/{}", &self.base_url, method)
        } else {
            format!("{}/{}?{}", &self.base_url, method, query_string)
        };

        let response = self
            .client
            .get(&url)
            .headers(self.auth_headers.clone().unwrap_or(HeaderMap::new()))
            .headers(self.common_headers.clone())
            .header("Version", api_version)
            .send()
            .await?;

        // Check the response status code.
        match response.status() {
            // If the status code is 200 OK, return the JSON body.
            StatusCode::OK => Ok((response.headers().clone(), response.json().await?)),
            // If the status code is not 200 OK, return an error.
            _ => Err(Box::new(ApiError {
                message: format!(
                    "GET operation to url '{}' and query_string '{}' failed with status code: {:?} - {:?}",
                    url,
                    query_string,
                    response.status(),
                    response.text().await?
                ),
            })),
        }
    }

    /// Log in to the REST API.
    pub async fn login(&mut self) -> Result<Value, Box<dyn Error>> {
        match self.session_version {
            1 | 2 => Ok(self.login_v2().await?),
            3 => Ok(self.login_v3().await?),
            _ => Err(Box::new(ApiError {
                message: format!("Invalid session version: {}", self.session_version),
            })),
        }
    }

    /// Log in to the REST API using session version 2.
    pub async fn login_v2(&mut self) -> Result<Value, Box<dyn Error>> {
        // Create the login request body.
        let login_request_body = AuthenticationPostRequest {
            identifier: self.config.username.clone(),
            password: self.config.password.clone(),
        };

        // Validate the login request body.
        login_request_body.validate()?;

        // Send the login request.
        let response = self
            .client
            .post(&format!("{}/session", &self.base_url))
            .json(&login_request_body)
            .headers(self.common_headers.clone())
            .header("Version", "2")
            .send()
            .await?;

        // Check the response status code.
        match response.status() {
            // If the status code is 200 OK, return the JSON body plus headers.
            StatusCode::OK => {
                // Get cst and x-security-token headers from the login response.
                let mut auth_headers = HeaderMap::new();
                if let Some(cst_header) = response.headers().get("cst") {
                    auth_headers.insert("cst", HeaderValue::from_str(cst_header.to_str()?)?);
                }
                if let Some(security_token_header) = response.headers().get("x-security-token") {
                    auth_headers.insert(
                        "x-security-token",
                        HeaderValue::from_str(security_token_header.to_str()?).unwrap(),
                    );
                }

                // If any of the auth_headers doesn't exist, return an error.
                if auth_headers.get("cst").is_none()
                    || auth_headers.get("x-security-token").is_none()
                {
                    return Err(Box::new(ApiError {
                        message:
                            "Any of the cst / x-security-token headers not found in login response."
                                .to_string(),
                    }));
                }

                self.auth_headers = Some(auth_headers);

                // Deserialize the response body to a serde_json::Value.
                let response_json: Value = response.json().await?;

                // Get the lightstreamer endpoint from the login response.
                self.lightstreamer_endpoint = match response_json.get("lightstreamerEndpoint") {
                    Some(endpoint) => match endpoint.as_str() {
                        Some(s) => s.to_string(),
                        None => {
                            return Err(Box::new(ApiError {
                                message: "Lightstreamer endpoint is not a string.".to_string(),
                            }))
                        }
                    },
                    None => {
                        return Err(Box::new(ApiError {
                            message: "Lightstreamer endpoint not found in login response.".to_string(),
                        }))
                    }
                };

                Ok(response_json)
            }
            // If the status code is not 200 OK, return an error.
            _ => Err(Box::new(ApiError {
                message: format!(
                    "Login failed with status code: {:?} - {:?}",
                    response.status(),
                    response.text().await?
                ),
            })),
        }
    }

    /// Log in to the REST API using session version 2.
    pub async fn login_v3(&mut self) -> Result<Value, Box<dyn Error>> {
        // Create the login request body.
        let login_request_body = AuthenticationPostRequest {
            identifier: self.config.username.clone(),
            password: self.config.password.clone(),
        };

        // Validate the login request body.
        login_request_body.validate()?;

        // Send the login request.
        let response = self
            .client
            .post(&format!("{}/session", &self.base_url))
            .json(&login_request_body)
            .headers(self.common_headers.clone())
            .header("Version", "3")
            .send()
            .await?;

        // Check the response status code.
        match response.status() {
            // If the status code is 200 OK, return the JSON body plus headers.
            StatusCode::OK => {
                // Deserialize the response body to a LoginResponseV3.
                let response_body = response.json().await?;
                let login_response = AuthenticationPostResponseV3::from_value(&response_body)?;

                // Get access_token from the login response and set it as the Bearer token in Authorization header.
                let mut auth_headers = HeaderMap::new();
                auth_headers.insert(
                    "Authorization",
                    HeaderValue::from_str(&format!(
                        "Bearer {}",
                        login_response.oauth_token.access_token
                    ))?,
                );

                let account_number = match self.config.execution_environment {
                    ExecutionEnvironment::Demo => self.config.account_number_demo.clone(),
                    ExecutionEnvironment::Live => self.config.account_number_live.clone(),
                };

                auth_headers.insert("IG-ACCOUNT-ID", HeaderValue::from_str(&account_number)?);

                self.auth_headers = Some(auth_headers);

                self.refresh_token = Some(login_response.oauth_token.refresh_token);

                self.lightstreamer_endpoint = login_response.lightstreamer_endpoint;

                Ok(response_body)
            }
            // If the status code is not 200 OK, return an error.
            _ => Err(Box::new(ApiError {
                message: format!(
                    "Login failed with status code: {:?} - {:?}",
                    response.status(),
                    response.text().await?,
                ),
            })),
        }
    }

    /// Send a POST request to the REST API.
    pub async fn post(
        &self,
        method: String,
        api_version: Option<usize>,
        body: &(impl Serialize + ValidateRequest),
    ) -> Result<(HeaderMap, Value), Box<dyn Error>> {
        // Default API version is 1.
        let version = api_version.unwrap_or(1).to_string();
        // Validate the body.
        body.validate()?;
        // Convert the body to a serde_json::Value.
        let body = serde_json::to_value(body)?;

        let response = self
            .client
            .post(&format!("{}/{}", &self.base_url, method))
            .json(&body)
            .headers(self.auth_headers.clone().unwrap_or(HeaderMap::new()))
            .headers(self.common_headers.clone())
            .header("Version", version.clone())
            .send()
            .await?;

        // Check the response status code.
        match response.status() {
            // If the status code is 200 OK, return the JSON body.
            StatusCode::OK => Ok((response.headers().clone(), response.json().await?)),
            // If the status code is not 200 OK, return an error.
            _ => Err(Box::new(ApiError {
                message: format!(
                    "POST operation using method '{}', version '{}' and body '{:?}' failed with status code: {:?} - {:?}",
                    method,
                    version,
                    body,
                    response.status(),
                    response.text().await?
                ),
            })),
        }
    }

    /// Send a PUT request to the REST API.
    pub async fn put(
        &self,
        method: String,
        version: Option<usize>,
        body: &(impl Serialize + ValidateRequest),
    ) -> Result<(HeaderMap, Value), Box<dyn Error>> {
        // Default API version is 1.
        let version = version.unwrap_or(1).to_string();
        // Validate the body.
        body.validate()?;

        // Send the PUT request.
        let response = self
            .client
            .put(&format!("{}/{}", &self.base_url, method))
            .json(&body)
            .headers(self.auth_headers.clone().unwrap_or(HeaderMap::new()))
            .headers(self.common_headers.clone())
            .header("Version", version.clone())
            .send()
            .await?;

        // Check the response status code.
        match response.status() {
            // If the status code is 200 OK, return the JSON body.
            StatusCode::OK => Ok((response.headers().clone(), response.json().await?)),
            // If the status code is not 200 OK, return an error.
            _ => Err(Box::new(ApiError {
                message: format!(
                    "PUT operation using method '{}', version '{}' and body '{:?}' failed with status code: {:?} - {:?}",
                    method,
                    version,
                    serde_json::to_string(&body)?,
                    response.status(),
                    response.text().await?
                ),
            })),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::common::{ApiConfig, ExecutionEnvironment};

    #[tokio::test]
    async fn new_rest_client_works() {
        // Create a mock API configuration
        let config = ApiConfig {
            account_number_demo: "test_account_number_demo".to_string(),
            account_number_live: "test_account_number_live".to_string(),
            account_number_test: None,
            api_key: "test_api_key".to_string(),
            auto_login: Some(false),
            execution_environment: ExecutionEnvironment::Demo,
            base_url_demo: "https://demo.example.com".to_string(),
            base_url_live: "https://live.example.com".to_string(),
            session_version: Some(2),
            streaming_api_max_connection_attempts: None,
            password: "test_password".to_string(),
            username: "test_username".to_string(),
        };

        // Call the `new` function with the mock configuration
        let rest_client = RestClient::new(config).await.unwrap();

        // Make assertions about the returned `RestClient` object
        assert_eq!(rest_client.auth_headers, None);
        assert_eq!(rest_client.auto_login, false);
        assert_eq!(rest_client.base_url, "https://demo.example.com");
        assert_eq!(
            rest_client.common_headers.get("X-IG-API-KEY").unwrap(),
            "test_api_key"
        );
        assert_eq!(
            rest_client.config.account_number_demo,
            "test_account_number_demo"
        );
        assert_eq!(
            rest_client.config.account_number_live,
            "test_account_number_live"
        );
        assert_eq!(rest_client.config.account_number_test, None);
        assert_eq!(rest_client.config.api_key, "test_api_key");
        assert_eq!(rest_client.config.auto_login, Some(false));
        assert_eq!(
            rest_client.config.execution_environment,
            ExecutionEnvironment::Demo
        );
        assert_eq!(rest_client.config.base_url_demo, "https://demo.example.com");
        assert_eq!(rest_client.config.base_url_live, "https://live.example.com");
        assert_eq!(rest_client.config.session_version, Some(2));
        assert_eq!(rest_client.config.password, "test_password");
        assert_eq!(rest_client.config.username, "test_username");
        assert_eq!(rest_client.session_version, 2);
    }
}