truefix-ig-client 0.1.6

Native, typed IG REST and Lightstreamer trading client for TrueFix.
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
//! Request and response types for the supported IG REST operations.

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum Direction {
    #[serde(rename = "BUY")]
    Buy,
    #[serde(rename = "SELL")]
    Sell,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum OrderType {
    #[serde(rename = "MARKET")]
    Market,
    #[serde(rename = "LIMIT")]
    Limit,
    #[serde(rename = "STOP")]
    Stop,
    #[serde(rename = "QUOTE")]
    Quote,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum TimeInForce {
    #[serde(rename = "GOOD_TILL_CANCELLED")]
    GoodTillCancelled,
    #[serde(rename = "GOOD_TILL_DATE")]
    GoodTillDate,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum MarketStatus {
    #[serde(rename = "TRADEABLE")]
    Tradeable,
    #[serde(rename = "CLOSED")]
    Closed,
    #[serde(rename = "EDITS_ONLY")]
    EditsOnly,
    #[serde(rename = "OFFLINE")]
    Offline,
    #[serde(other)]
    Unknown,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LoginResponse {
    pub current_account_id: Option<String>,
    pub lightstreamer_endpoint: String,
    pub client_id: String,
    pub currency_iso_code: Option<String>,
    pub dealing_enabled: Option<bool>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct V3LoginResponse {
    pub account_id: Option<String>,
    pub current_account_id: Option<String>,
    pub lightstreamer_endpoint: String,
    pub client_id: String,
    pub currency_iso_code: Option<String>,
    pub dealing_enabled: Option<bool>,
    pub oauth_token: Option<OAuthToken>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct OAuthToken {
    #[serde(alias = "accessToken")]
    pub access_token: String,
    #[serde(alias = "refreshToken")]
    pub refresh_token: String,
    #[serde(
        alias = "expiresIn",
        deserialize_with = "deserialize_u64_string_or_number"
    )]
    pub expires_in: u64,
}

fn deserialize_u64_string_or_number<'de, D>(deserializer: D) -> Result<u64, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum Value {
        Number(u64),
        String(String),
    }

    match Value::deserialize(deserializer)? {
        Value::Number(value) => Ok(value),
        Value::String(value) => value.parse().map_err(serde::de::Error::custom),
    }
}

#[derive(Debug, Deserialize)]
pub struct AccountsResponse {
    pub accounts: Vec<Account>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Account {
    pub account_id: String,
    pub account_name: String,
    pub preferred: bool,
    pub balance: Option<AccountBalance>,
    pub currency: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountBalance {
    pub balance: f64,
    pub available: f64,
    pub deposit: f64,
    pub profit_loss: f64,
}

#[derive(Debug, Deserialize)]
pub struct PositionsResponse {
    pub positions: Vec<Position>,
}

#[derive(Debug, Deserialize)]
pub struct Position {
    pub position: PositionDetail,
    pub market: PositionMarket,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PositionDetail {
    pub deal_id: String,
    pub direction: Direction,
    pub currency: String,
    pub size: Option<f64>,
    pub level: Option<f64>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PositionMarket {
    pub epic: String,
    pub instrument_name: String,
    pub bid: Option<f64>,
    pub offer: Option<f64>,
    pub market_status: Option<MarketStatus>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MarketDetails {
    pub instrument: Instrument,
    pub snapshot: MarketSnapshot,
    #[serde(default)]
    pub dealing_rules: Option<DealingRules>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Instrument {
    pub name: String,
    pub epic: String,
    pub instrument_type: Option<String>,
    pub expiry: Option<String>,
    #[serde(default)]
    pub currencies: Vec<InstrumentCurrency>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InstrumentCurrency {
    pub code: String,
    #[serde(default)]
    pub is_default: bool,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DealingRules {
    #[serde(default)]
    pub min_deal_size: Option<RuleValue>,
}

#[derive(Debug, Deserialize)]
pub struct RuleValue {
    pub value: f64,
    #[serde(default)]
    pub unit: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MarketSnapshot {
    pub market_status: MarketStatus,
    pub bid: Option<f64>,
    pub offer: Option<f64>,
    pub high: Option<f64>,
    pub low: Option<f64>,
}

#[derive(Debug, Deserialize)]
pub struct MarketsResponse {
    pub markets: Vec<MarketData>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MarketData {
    pub epic: String,
    pub instrument_name: String,
    #[serde(default)]
    pub instrument_type: Option<String>,
    #[serde(default)]
    pub expiry: Option<String>,
    pub bid: Option<f64>,
    pub offer: Option<f64>,
}

#[derive(Debug, Clone, Default)]
pub struct HistoricalPricesQuery<'a> {
    pub resolution: &'a str,
    pub from: Option<&'a str>,
    pub to: Option<&'a str>,
    pub max: Option<u32>,
}
impl<'a> HistoricalPricesQuery<'a> {
    pub fn new(resolution: &'a str) -> Self {
        Self {
            resolution,
            ..Self::default()
        }
    }
    pub fn from(mut self, value: &'a str) -> Self {
        self.from = Some(value);
        self
    }
    pub fn to(mut self, value: &'a str) -> Self {
        self.to = Some(value);
        self
    }
    pub fn max(mut self, value: u32) -> Self {
        self.max = Some(value);
        self
    }
}

#[derive(Debug, Deserialize)]
pub struct HistoricalPricesResponse {
    pub prices: Vec<HistoricalPrice>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HistoricalPrice {
    pub snapshot_time: Option<String>,
    pub snapshot_time_utc: Option<String>,
    pub open_price: PricePoint,
    pub high_price: PricePoint,
    pub low_price: PricePoint,
    pub close_price: PricePoint,
    #[serde(default)]
    pub last_traded_volume: Option<f64>,
}

#[derive(Debug, Default, Deserialize)]
pub struct PricePoint {
    pub bid: Option<f64>,
    pub ask: Option<f64>,
    pub last_traded: Option<f64>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreatePositionRequest {
    pub currency_code: String,
    pub direction: Direction,
    pub epic: String,
    pub expiry: String,
    pub force_open: bool,
    pub guaranteed_stop: bool,
    pub order_type: OrderType,
    pub size: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub level: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit_level: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_level: Option<f64>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DealReferenceResponse {
    pub deal_reference: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SwitchAccountResponse {
    pub dealing_enabled: bool,
    #[serde(default)]
    pub has_active_demo_accounts: bool,
    #[serde(default)]
    pub has_active_live_accounts: bool,
    #[serde(default)]
    pub trailing_stops_enabled: bool,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkingOrdersResponse {
    #[serde(default)]
    pub working_orders: Vec<WorkingOrder>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkingOrder {
    pub working_order_data: WorkingOrderData,
    pub market_data: MarketData,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkingOrderData {
    pub deal_id: String,
    #[serde(default)]
    pub deal_reference: Option<String>,
    pub direction: Direction,
    pub epic: String,
    pub order_size: f64,
    pub order_level: f64,
    #[serde(rename = "orderType")]
    pub order_type: OrderType,
    pub time_in_force: TimeInForce,
    #[serde(default)]
    pub good_till_date: Option<String>,
    #[serde(default)]
    pub guaranteed_stop: bool,
    #[serde(default)]
    pub stop_level: Option<f64>,
    #[serde(default)]
    pub stop_distance: Option<f64>,
    #[serde(default)]
    pub limit_level: Option<f64>,
    #[serde(default)]
    pub limit_distance: Option<f64>,
    #[serde(default)]
    pub currency_code: Option<String>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateWorkingOrderRequest {
    pub epic: String,
    pub direction: Direction,
    pub size: f64,
    pub level: f64,
    #[serde(rename = "type")]
    pub order_type: OrderType,
    pub time_in_force: TimeInForce,
    pub guaranteed_stop: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_level: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_distance: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit_level: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit_distance: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub good_till_date: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deal_reference: Option<String>,
    pub currency_code: String,
    pub expiry: String,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateWorkingOrderRequest {
    pub level: f64,
    #[serde(rename = "type")]
    pub order_type: OrderType,
    pub time_in_force: TimeInForce,
    pub guaranteed_stop: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub good_till_date: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_level: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_distance: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit_level: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit_distance: Option<f64>,
}

/// Authoritative acknowledgement returned by `GET /confirms/{dealReference}`.
/// Optional fields keep the client forward-compatible with IG's product- and
/// rejection-specific response shapes.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DealConfirmation {
    pub deal_reference: String,
    #[serde(default)]
    pub deal_id: Option<String>,
    pub deal_status: DealStatus,
    #[serde(default)]
    pub reason: Option<String>,
    #[serde(default)]
    pub status: Option<String>,
    #[serde(default)]
    pub level: Option<f64>,
    #[serde(default)]
    pub size: Option<f64>,
}

#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "UPPERCASE")]
pub enum DealStatus {
    Accepted,
    Rejected,
    #[serde(other)]
    Unknown,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn deal_confirmation_accepts_product_specific_optional_fields() {
        let confirmation: DealConfirmation = serde_json::from_value(serde_json::json!({
            "dealReference": "reference-1",
            "dealId": "deal-1",
            "dealStatus": "ACCEPTED",
            "status": "OPEN",
            "level": 123.45,
            "size": 2,
            "epic": "CS.D.AAPL.CFD.IP"
        }))
        .unwrap();
        assert_eq!(confirmation.deal_status, DealStatus::Accepted);
        assert_eq!(confirmation.deal_id.as_deref(), Some("deal-1"));
    }
}