digdigdig3 0.1.12

Unified async Rust API for 44 exchange connectors — crypto, stocks, forex. REST + WebSocket.
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
//! # OANDA HTTP Streaming
//!
//! HTTP streaming implementation for OANDA pricing and transaction streams.
//!
//! IMPORTANT: OANDA uses HTTP streaming (NOT WebSocket)
//! - Uses chunked transfer encoding
//! - Newline-delimited JSON messages
//! - Heartbeats every 5 seconds

use reqwest::Client;
use serde_json::Value;

use crate::core::{ExchangeError, ExchangeResult};

use super::auth::OandaAuth;
use super::endpoints::OandaUrls;

// ═══════════════════════════════════════════════════════════════════════════════
// STREAMING MESSAGE TYPES
// ═══════════════════════════════════════════════════════════════════════════════

/// Streaming message types
#[derive(Debug, Clone)]
pub enum StreamMessage {
    /// Price update
    Price(PriceUpdate),
    /// Heartbeat
    Heartbeat { time: String },
    /// Transaction update
    Transaction(Value),
}

/// Price update from streaming endpoint
#[derive(Debug, Clone)]
pub struct PriceUpdate {
    pub instrument: String,
    pub time: String,
    pub tradeable: bool,
    pub bid: f64,
    pub ask: f64,
    pub closeout_bid: f64,
    pub closeout_ask: f64,
}

// ═══════════════════════════════════════════════════════════════════════════════
// PRICING STREAM
// ═══════════════════════════════════════════════════════════════════════════════

/// HTTP streaming client for OANDA pricing stream
pub struct PricingStream {
    auth: OandaAuth,
    urls: OandaUrls,
    account_id: String,
    instruments: Vec<String>,
    /// Byte buffer for partial lines received from the chunk stream
    line_buf: Vec<u8>,
    /// Pending complete lines waiting to be returned as messages
    pending_lines: std::collections::VecDeque<String>,
    /// Active HTTP response stream
    response: Option<reqwest::Response>,
}

impl PricingStream {
    /// Create new pricing stream
    pub fn new(
        auth: OandaAuth,
        urls: OandaUrls,
        account_id: String,
        instruments: Vec<String>,
    ) -> Self {
        Self {
            auth,
            urls,
            account_id,
            instruments,
            line_buf: Vec::new(),
            pending_lines: std::collections::VecDeque::new(),
            response: None,
        }
    }

    /// Connect to pricing stream
    ///
    /// Issues GET `{stream_url}/v3/accounts/{account_id}/pricing/stream?instruments=...`
    /// with `Authorization: Bearer {token}` and keeps the response alive for streaming.
    pub async fn connect(&mut self) -> ExchangeResult<()> {
        let instruments_param = self.instruments.join(",");
        let url = format!(
            "{}/v3/accounts/{}/pricing/stream?instruments={}",
            self.urls.stream_url,
            self.account_id,
            instruments_param
        );

        let client = Client::new();
        let response = client
            .get(&url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth.token()),
            )
            .header("Accept-Datetime-Format", "RFC3339")
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!("Failed to connect to pricing stream: {}", e)))?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            return Err(ExchangeError::Http(format!(
                "Pricing stream HTTP {}: {}",
                status, body
            )));
        }

        self.line_buf.clear();
        self.pending_lines.clear();
        self.response = Some(response);
        Ok(())
    }

    /// Get next message from stream
    ///
    /// Reads the next complete newline-delimited JSON line from the HTTP chunked response
    /// and parses it into a [`StreamMessage`].
    pub async fn next_message(&mut self) -> ExchangeResult<StreamMessage> {
        loop {
            // Return any already-buffered complete lines first
            if let Some(line) = self.pending_lines.pop_front() {
                if !line.trim().is_empty() {
                    return parse_message(&line);
                }
                continue;
            }

            // Read next chunk from the HTTP body
            let response = self.response.as_mut().ok_or_else(|| {
                ExchangeError::Network("Not connected — call connect() first".to_string())
            })?;

            let chunk = response.chunk().await
                .map_err(|e| ExchangeError::Network(format!("Stream read error: {}", e)))?;

            match chunk {
                None => {
                    return Err(ExchangeError::Network("Pricing stream closed by server".to_string()));
                }
                Some(bytes) => {
                    // Accumulate bytes into line buffer and split on newlines
                    for b in bytes.iter().copied() {
                        if b == b'\n' {
                            let line = String::from_utf8_lossy(&self.line_buf).into_owned();
                            self.line_buf.clear();
                            if !line.trim().is_empty() {
                                self.pending_lines.push_back(line);
                            }
                        } else {
                            self.line_buf.push(b);
                        }
                    }
                }
            }
        }
    }

    /// Close the stream
    pub async fn close(&mut self) -> ExchangeResult<()> {
        self.response = None;
        self.line_buf.clear();
        self.pending_lines.clear();
        Ok(())
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TRANSACTION STREAM
// ═══════════════════════════════════════════════════════════════════════════════

/// HTTP streaming client for OANDA transaction stream
pub struct TransactionStream {
    auth: OandaAuth,
    urls: OandaUrls,
    account_id: String,
    /// Byte buffer for partial lines
    line_buf: Vec<u8>,
    /// Pending complete lines
    pending_lines: std::collections::VecDeque<String>,
    /// Active HTTP response stream
    response: Option<reqwest::Response>,
}

impl TransactionStream {
    /// Create new transaction stream
    pub fn new(
        auth: OandaAuth,
        urls: OandaUrls,
        account_id: String,
    ) -> Self {
        Self {
            auth,
            urls,
            account_id,
            line_buf: Vec::new(),
            pending_lines: std::collections::VecDeque::new(),
            response: None,
        }
    }

    /// Connect to transaction stream
    ///
    /// Issues GET `{stream_url}/v3/accounts/{account_id}/transactions/stream`
    /// with `Authorization: Bearer {token}`.
    pub async fn connect(&mut self) -> ExchangeResult<()> {
        let url = format!(
            "{}/v3/accounts/{}/transactions/stream",
            self.urls.stream_url,
            self.account_id,
        );

        let client = Client::new();
        let response = client
            .get(&url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth.token()),
            )
            .header("Accept-Datetime-Format", "RFC3339")
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!("Failed to connect to transaction stream: {}", e)))?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            return Err(ExchangeError::Api {
                code: status.as_u16() as i32,
                message: format!("Transaction stream HTTP {}: {}", status, body),
            });
        }

        self.line_buf.clear();
        self.pending_lines.clear();
        self.response = Some(response);
        Ok(())
    }

    /// Get next message from stream
    ///
    /// Reads the next complete newline-delimited JSON line and parses it into a [`StreamMessage`].
    pub async fn next_message(&mut self) -> ExchangeResult<StreamMessage> {
        loop {
            if let Some(line) = self.pending_lines.pop_front() {
                if !line.trim().is_empty() {
                    return parse_message(&line);
                }
                continue;
            }

            let response = self.response.as_mut().ok_or_else(|| {
                ExchangeError::Network("Not connected — call connect() first".to_string())
            })?;

            let chunk = response.chunk().await
                .map_err(|e| ExchangeError::Network(format!("Stream read error: {}", e)))?;

            match chunk {
                None => {
                    return Err(ExchangeError::Network("Transaction stream closed by server".to_string()));
                }
                Some(bytes) => {
                    for &b in bytes.iter() {
                        if b == b'\n' {
                            let line = String::from_utf8_lossy(&self.line_buf).into_owned();
                            self.line_buf.clear();
                            if !line.trim().is_empty() {
                                self.pending_lines.push_back(line);
                            }
                        } else {
                            self.line_buf.push(b);
                        }
                    }
                }
            }
        }
    }

    /// Close the stream
    pub async fn close(&mut self) -> ExchangeResult<()> {
        self.response = None;
        self.line_buf.clear();
        self.pending_lines.clear();
        Ok(())
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// HELPERS
// ═══════════════════════════════════════════════════════════════════════════════

/// Parse a newline-delimited streaming message line into a [`StreamMessage`]
pub fn parse_message(line: &str) -> ExchangeResult<StreamMessage> {
    let value: Value = serde_json::from_str(line)
        .map_err(|e| ExchangeError::Parse(format!("Failed to parse JSON: {}", e)))?;

    let msg_type = value.get("type")
        .and_then(|t| t.as_str())
        .ok_or_else(|| ExchangeError::Parse("Missing 'type' field".to_string()))?;

    match msg_type {
        "PRICE" => {
            let instrument = value.get("instrument")
                .and_then(|i| i.as_str())
                .ok_or_else(|| ExchangeError::Parse("Missing 'instrument'".to_string()))?
                .to_string();

            let time = value.get("time")
                .and_then(|t| t.as_str())
                .unwrap_or("")
                .to_string();

            let tradeable = value.get("tradeable")
                .and_then(|t| t.as_bool())
                .unwrap_or(false);

            // Get best bid/ask
            let bid = value.get("bids")
                .and_then(|b| b.as_array())
                .and_then(|arr| arr.first())
                .and_then(|b| b.get("price"))
                .and_then(|p| p.as_str())
                .and_then(|s| s.parse().ok())
                .unwrap_or(0.0);

            let ask = value.get("asks")
                .and_then(|a| a.as_array())
                .and_then(|arr| arr.first())
                .and_then(|a| a.get("price"))
                .and_then(|p| p.as_str())
                .and_then(|s| s.parse().ok())
                .unwrap_or(0.0);

            let closeout_bid = value.get("closeoutBid")
                .and_then(|c| c.as_str())
                .and_then(|s| s.parse().ok())
                .unwrap_or(bid);

            let closeout_ask = value.get("closeoutAsk")
                .and_then(|c| c.as_str())
                .and_then(|s| s.parse().ok())
                .unwrap_or(ask);

            Ok(StreamMessage::Price(PriceUpdate {
                instrument,
                time,
                tradeable,
                bid,
                ask,
                closeout_bid,
                closeout_ask,
            }))
        }
        "HEARTBEAT" => {
            let time = value.get("time")
                .and_then(|t| t.as_str())
                .unwrap_or("")
                .to_string();

            Ok(StreamMessage::Heartbeat { time })
        }
        _ => {
            // Transaction or other message type
            Ok(StreamMessage::Transaction(value))
        }
    }
}

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

    #[test]
    fn test_parse_price_message() {
        let json_str = r#"{
            "type": "PRICE",
            "time": "2026-01-26T12:34:56.789123456Z",
            "instrument": "EUR_USD",
            "tradeable": true,
            "bids": [{"price": "1.12157", "liquidity": 10000000}],
            "asks": [{"price": "1.12170", "liquidity": 10000000}],
            "closeoutBid": "1.12153",
            "closeoutAsk": "1.12174"
        }"#;

        let msg = parse_message(json_str).unwrap();
        match msg {
            StreamMessage::Price(price) => {
                assert_eq!(price.instrument, "EUR_USD");
                assert!(price.tradeable);
                assert!((price.bid - 1.12157).abs() < 0.00001);
                assert!((price.ask - 1.12170).abs() < 0.00001);
            }
            _ => panic!("Expected Price message"),
        }
    }

    #[test]
    fn test_parse_heartbeat_message() {
        let json_str = r#"{
            "type": "HEARTBEAT",
            "time": "2026-01-26T12:35:01.123456789Z"
        }"#;

        let msg = parse_message(json_str).unwrap();
        match msg {
            StreamMessage::Heartbeat { time } => {
                assert_eq!(time, "2026-01-26T12:35:01.123456789Z");
            }
            _ => panic!("Expected Heartbeat message"),
        }
    }
}