exchange-rate 0.1.3

The best Exchange Rate search for a given set of Exchanges, Currencies, Exchange Rates and Exchange Rate Requests.
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
//! Exchange Rate Path (ERP) algorithm.
use crate::request::Request;
use crate::response::best_rate_path::BestRatePath;
use crate::response::Response;
use crate::IndexMapTrait;
use floyd_warshall_alg::{FloydWarshall, FloydWarshallResult, FloydWarshallTrait};
use indexmap::map::{Entry, IndexMap};
use indexmap::IndexSet;
use num_traits::Num;
use safe_graph::{Graph, NodeTrait};
use std::clone::Clone;
use std::cmp::Ordering::{Greater, Less};
use std::fmt::{Debug, Display};
use std::ops::AddAssign;
use std::str::FromStr;

/// Exchange Rate Path `Algorithm` structure.
///
/// # `Algorithm<N, E, I>` is parameterized over:
///
/// - Identifier data `N`.
/// - Edge weight `E`.
/// - Index `I` for indexing of nodes `N`.
pub struct Algorithm<N, E, I> {
    graph: Graph<(I, I), E>,
    node_to_index: IndexMap<N, I>,
    index_to_node: IndexMap<I, N>,
    counter: I,
    currency_exchanges: IndexMap<I, IndexSet<I>>,
}

impl<N, E, I> Algorithm<N, E, I>
where
    N: Clone + Display + FromStr + IndexMapTrait + Debug,
    <N as FromStr>::Err: Debug,
    E: Display + FloydWarshallTrait + FromStr + Debug,
    <E as FromStr>::Err: Debug,
    I: NodeTrait + Num + AddAssign,
{
    fn new() -> Self {
        let graph = Graph::<(I, I), E>::new();
        let node_to_index = IndexMap::<N, I>::new();
        let index_to_node = IndexMap::<I, N>::new();
        let counter = I::zero();
        let currency_exchanges = IndexMap::<I, IndexSet<I>>::new();

        Self {
            graph,
            node_to_index,
            index_to_node,
            counter,
            currency_exchanges,
        }
    }

    pub fn process(request: &Request<N, E>) -> Response<N, E> {
        let mut alg = Algorithm::<N, E, I>::new();
        alg.construct_graph(request);
        let result = alg.run_customized_floyd_warshall();
        alg.form_response(request, &result)
    }

    fn construct_graph(&mut self, request: &Request<N, E>) {
        // Process all `PriceUpdates`.
        for (_, price_update) in request.get_price_updates().iter() {
            // Prepare indexes.
            let exchange_index = self.node_to_index(price_update.get_exchange().clone());
            let source_currency_index =
                self.node_to_index(price_update.get_source_currency().clone());
            let destination_currency_index =
                self.node_to_index(price_update.get_destination_currency().clone());

            // Get star and end node.
            let a = (exchange_index, source_currency_index);
            let b = (exchange_index, destination_currency_index);

            // Add forward edge.
            self.graph
                .add_edge(a, b, *price_update.get_forward_factor());
            // Add backward edge.
            self.graph
                .add_edge(b, a, *price_update.get_backward_factor());

            // Collect provided currencies.
            self.collect_currency_exchanges(source_currency_index, exchange_index);
            self.collect_currency_exchanges(destination_currency_index, exchange_index);
        }

        // For each currency add edges, so that each `(exchange, currency)` is connected to every
        // other `(other_exchange, currency)` with an edge weight of 1.0.
        self.add_currency_exchanges_edges();
    }

    fn collect_currency_exchanges(&mut self, currency: I, exchange: I) {
        match self.currency_exchanges.entry(currency) {
            // Return the index for existing entry.
            Entry::Occupied(o) => {
                // Insert the provided exchange.
                o.into_mut().insert(exchange);
            }
            // Insert a new `IndexSet`.
            Entry::Vacant(v) => {
                // Prepare a new `IndexSet` with the provided exchange.
                let mut exchanges = IndexSet::<I>::with_capacity(1);
                exchanges.insert(exchange);

                // Insert the new `IndexSet`.
                v.insert(exchanges);
            }
        }
    }

    fn add_currency_exchanges_edges(&mut self) {
        // Loop through all currencies.
        for (currency, exchanges) in self.currency_exchanges.iter() {
            let exchanges_count = exchanges.len();

            // Loop through exchanges of the current currency.
            for top in 0..exchanges_count {
                // Loop through all exchanges of the current currency following the previous
                // top exchange.
                for below in top + 1..exchanges_count {
                    let a = (*exchanges.get_index(top).unwrap(), *currency);
                    let b = (*exchanges.get_index(below).unwrap(), *currency);

                    // Add forward edge.
                    self.graph.add_edge(a, b, E::one());
                    // Add backward edge.
                    self.graph.add_edge(b, a, E::one());
                }
            }
        }
    }

    /// Get index of the provided node `N`.
    ///
    /// If the `N` is not yet indexed, do so and return the new index.
    fn node_to_index(&mut self, s: N) -> I {
        match self.node_to_index.entry(s.clone()) {
            // Return the index for existing entry.
            Entry::Occupied(o) => *o.get(),
            // Insert with a proper index based on counter.
            Entry::Vacant(v) => {
                // Increase the counter here because new index was requested.
                self.counter += I::one();
                // Use counter as a new index.
                v.insert(self.counter);
                // Update the reverse `IndexMap`.
                self.index_to_node.insert(self.counter, s);
                // Return the index.
                self.counter
            }
        }
    }

    /// Get node `N` for the provided index.
    ///
    /// Return `Option<n>` as it is possible that there's no `N` with the index.
    fn index_to_node(&self, i: &I) -> Option<&N> {
        self.index_to_node.get(i)
    }

    fn run_customized_floyd_warshall(&mut self) -> FloydWarshallResult<(I, I), E> {
        let mul = Box::new(|x: E, y: E| x * y);
        let sharp_greater = Box::new(|x: E, y: E| x.partial_cmp(&y).unwrap_or(Less) == Greater);

        let alg: FloydWarshall<E> = FloydWarshall::new_customized(mul, sharp_greater);
        alg.find_paths(&self.graph)
    }

    fn form_response(
        &mut self,
        request: &Request<N, E>,
        fw_result: &FloydWarshallResult<(I, I), E>,
    ) -> Response<N, E> {
        let mut response = Response::new();

        // Process all `PriceUpdates`.
        for (_, rate_request) in request.get_rate_requests().iter() {
            // Prepare indexes.
            let source_exchange_index =
                self.node_to_index(rate_request.get_source_exchange().clone());
            let source_currency_index =
                self.node_to_index(rate_request.get_source_currency().clone());
            let destination_exchange_index =
                self.node_to_index(rate_request.get_destination_exchange().clone());
            let destination_currency_index =
                self.node_to_index(rate_request.get_destination_currency().clone());

            // Get star and end node.
            let a = (source_exchange_index, source_currency_index);
            let b = (destination_exchange_index, destination_currency_index);

            // Prepare `BestRatePath`.
            let rate_raw = fw_result.get_path_rate(a, b);
            let path = fw_result.collect_path_nodes(a, b);

            // Re-map path from indexes `I` to nodes `N`.
            let path = path
                .into_iter()
                .map(|(a, b)| {
                    (
                        self.index_to_node(&a).unwrap().clone(),
                        self.index_to_node(&b).unwrap().clone(),
                    )
                })
                .collect();

            #[allow(clippy::single_match)]
            match rate_raw {
                Some(&rate) => {
                    let best_rate_path = BestRatePath::<N, E>::new(rate, path);
                    response.add_best_rate_path(best_rate_path);
                }
                None => {
                    // It would be probably good to include information about non-existing
                    // Rate request as a part of `Response` or at least log it.
                }
            }
        }

        response
    }
}

#[cfg(test)]
mod tests {
    use crate::algorithm::Algorithm;
    use crate::request::Request;
    use std::io::BufReader;

    #[test]
    fn new() {
        let _alg = Algorithm::<String, f32, u32>::new();
    }

    #[test]
    fn collect_currency_exchanges() {
        let mut alg = Algorithm::<String, f32, u32>::new();

        alg.collect_currency_exchanges(1, 2);
        alg.collect_currency_exchanges(1, 3);
        alg.collect_currency_exchanges(1, 4);
        alg.collect_currency_exchanges(5, 6);

        // Test currencies existence.
        assert!(alg.currency_exchanges.get(&1).is_some());
        assert!(alg.currency_exchanges.get(&5).is_some());

        // Test currencies non-existence.
        assert!(alg.currency_exchanges.get(&2).is_none());

        // Test exchanges existence.
        assert!(alg.currency_exchanges.get(&1).unwrap().get(&2).is_some());
        assert_eq!(alg.currency_exchanges.get(&1).unwrap().get(&2).unwrap(), &2);
        assert!(alg.currency_exchanges.get(&1).unwrap().get(&3).is_some());
        assert_eq!(alg.currency_exchanges.get(&1).unwrap().get(&3).unwrap(), &3);
        assert!(alg.currency_exchanges.get(&5).unwrap().get(&6).is_some());
        assert_eq!(alg.currency_exchanges.get(&5).unwrap().get(&6).unwrap(), &6);

        // Test exchanges non-existence.
        assert!(alg.currency_exchanges.get(&1).unwrap().get(&7).is_none());
    }

    #[test]
    fn add_currency_exchanges_edges() {
        let mut alg = Algorithm::<String, f32, u32>::new();

        alg.collect_currency_exchanges(1, 2);
        alg.collect_currency_exchanges(1, 3);
        alg.collect_currency_exchanges(1, 4);
        alg.collect_currency_exchanges(5, 6);

        alg.add_currency_exchanges_edges();

        // Test edges existence.
        assert_eq!(alg.graph.edge_weight((2, 1), (3, 1)), Some(&1.0));
        assert_eq!(alg.graph.edge_weight((3, 1), (2, 1)), Some(&1.0));
        assert_eq!(alg.graph.edge_weight((2, 1), (4, 1)), Some(&1.0));
        assert_eq!(alg.graph.edge_weight((4, 1), (2, 1)), Some(&1.0));
        assert_eq!(alg.graph.edge_weight((3, 1), (4, 1)), Some(&1.0));
        assert_eq!(alg.graph.edge_weight((4, 1), (3, 1)), Some(&1.0));

        // Test edges non-existence.
        assert_eq!(alg.graph.contains_edge((2, 1), (6, 1)), false);
        assert_eq!(alg.graph.contains_edge((6, 1), (2, 1)), false);
        assert_eq!(alg.graph.contains_edge((6, 5), (2, 5)), false);
    }

    #[test]
    fn construct_graph() {
        let mut alg = Algorithm::<String, f32, u32>::new();

        let text_input = "2017-11-01T09:42:23+00:00 E1 BTC USD 1000.0 0.0009
2018-11-01T09:42:23+00:00 E1 ETH USD 100.0 0.001
2018-11-01T09:42:23+00:00 E2 ETH USD 100.0 0.001
2018-11-01T09:42:23+00:00 E3 ETH BTC 100.0 0.001"
            .as_bytes();

        // Test creation of Request from multiline text.
        let mut input = BufReader::new(text_input);
        let request = Request::<String, f32>::read_from(&mut input);

        alg.construct_graph(&request);

        // Exchanges.
        let e1 = String::from("E1");
        let e2 = String::from("E2");
        let e3 = String::from("E3");

        // Currencies.
        let btc = String::from("BTC");
        let eth = String::from("ETH");
        let usd = String::from("USD");

        //
        let e1_index = alg.node_to_index(e1.clone());
        let e2_index = alg.node_to_index(e2.clone());
        let e3_index = alg.node_to_index(e3.clone());
        let btc_index = alg.node_to_index(btc.clone());
        let eth_index = alg.node_to_index(eth.clone());
        let usd_index = alg.node_to_index(usd.clone());

        // Test ETH edges existence.
        assert_eq!(
            alg.graph
                .edge_weight((e1_index, eth_index), (e2_index, eth_index)),
            Some(&1.0)
        );
        assert_eq!(
            alg.graph
                .edge_weight((e2_index, eth_index), (e1_index, eth_index)),
            Some(&1.0)
        );
        assert_eq!(
            alg.graph
                .edge_weight((e1_index, eth_index), (e3_index, eth_index)),
            Some(&1.0)
        );
        assert_eq!(
            alg.graph
                .edge_weight((e3_index, eth_index), (e1_index, eth_index)),
            Some(&1.0)
        );
        assert_eq!(
            alg.graph
                .edge_weight((e2_index, eth_index), (e3_index, eth_index)),
            Some(&1.0)
        );
        assert_eq!(
            alg.graph
                .edge_weight((e3_index, eth_index), (e2_index, eth_index)),
            Some(&1.0)
        );

        // Test USF edges existence.
        assert_eq!(
            alg.graph
                .edge_weight((e1_index, usd_index), (e2_index, usd_index)),
            Some(&1.0)
        );
        assert_eq!(
            alg.graph
                .edge_weight((e2_index, usd_index), (e1_index, usd_index)),
            Some(&1.0)
        );

        // Test USD edges non-existence.
        assert_eq!(
            alg.graph
                .contains_edge((e1_index, usd_index), (e3_index, usd_index)),
            false
        );
        assert_eq!(
            alg.graph
                .contains_edge((e3_index, usd_index), (e1_index, usd_index)),
            false
        );
        assert_eq!(
            alg.graph
                .contains_edge((e2_index, usd_index), (e3_index, usd_index)),
            false
        );
        assert_eq!(
            alg.graph
                .contains_edge((e3_index, usd_index), (e2_index, usd_index)),
            false
        );

        // Test BTC edges existence.
        assert_eq!(
            alg.graph
                .edge_weight((e1_index, btc_index), (e3_index, btc_index)),
            Some(&1.0)
        );
        assert_eq!(
            alg.graph
                .edge_weight((e3_index, btc_index), (e1_index, btc_index)),
            Some(&1.0)
        );
    }

    #[test]
    fn run_customized_floyd_warshall() {
        let mut alg = Algorithm::<String, f32, u32>::new();

        let text_input = "2017-11-01T09:42:23+00:00 E1 BTC USD 1000.0 0.0009
2018-11-01T09:42:23+00:00 E1 ETH USD 102.0 0.009
2018-11-01T09:42:23+00:00 E2 ETH USD 100.0 0.0096
2018-11-01T09:42:23+00:00 E3 ETH BTC 0.08 10"
            .as_bytes();

        // Test creation of Request from multiline text.
        let mut input = BufReader::new(text_input);
        let request = Request::<String, f32>::read_from(&mut input);

        alg.construct_graph(&request);
        let result = alg.run_customized_floyd_warshall();

        // Exchanges.
        let e1 = String::from("E1");
        let e2 = String::from("E2");
        let e3 = String::from("E3");

        // Currencies.
        let btc = String::from("BTC");
        let eth = String::from("ETH");
        let usd = String::from("USD");

        //
        let e1_index = alg.node_to_index(e1.clone());
        let e2_index = alg.node_to_index(e2.clone());
        let e3_index = alg.node_to_index(e3.clone());

        let _btc_index = alg.node_to_index(btc.clone());
        let eth_index = alg.node_to_index(eth.clone());
        let usd_index = alg.node_to_index(usd.clone());

        // Test rate and path from `(E1, ETH)` to `(E2, ETH)`.
        assert_eq!(
            result.get_path_rate((e1_index, eth_index), (e2_index, eth_index)),
            Some(&1.0)
        );
        assert_eq!(
            result.collect_path_nodes((e1_index, eth_index), (e2_index, eth_index)),
            vec![(e1_index, eth_index), (e2_index, eth_index)]
        );

        // Test rate and path from `(E1, ETH)` to `(E3, ETH)`.
        assert_eq!(
            result.get_path_rate((e1_index, eth_index), (e3_index, eth_index)),
            Some(&1.0)
        );
        assert_eq!(
            result.collect_path_nodes((e1_index, eth_index), (e3_index, eth_index)),
            vec![(e1_index, eth_index), (e3_index, eth_index)]
        );

        // Test rate and path from `(E2, ETH)` to `(E3, ETH)`.
        assert_eq!(
            result.get_path_rate((e2_index, eth_index), (e3_index, eth_index)),
            Some(&1.0)
        );
        assert_eq!(
            result.collect_path_nodes((e2_index, eth_index), (e3_index, eth_index)),
            vec![(e2_index, eth_index), (e3_index, eth_index)]
        );

        // Test rate and path from `(E2, ETH)` to `(E1, USD)`.
        assert_eq!(
            result.get_path_rate((e2_index, eth_index), (e1_index, usd_index)),
            Some(&102.0)
        );
        assert_eq!(
            result.collect_path_nodes((e2_index, eth_index), (e1_index, usd_index)),
            vec![
                (e2_index, eth_index),
                (e1_index, eth_index),
                (e1_index, usd_index)
            ]
        );
    }

    #[test]
    fn process() {
        let text_input = "2019-01-20T09:42:23+00:00 BitMEX BTC USD 3531.0 0.00026
2019-01-20T09:42:23+00:00 CoinBene BTC USD 3584.69 0.00025
2019-01-20T09:42:23+00:00 EXX BTC USD 3577.07 0.000255
2019-01-20T09:42:23+00:00 Bitfinex BTC USD 3580.60 0.000252
2019-01-20T09:42:23+00:00 OEX BTC USD 3571.26 0.00026

2019-01-20T09:42:23+00:00 Bibox ETH USD 117.36 0.0075
2019-01-20T09:42:23+00:00 Bitfinex ETH USD 117.51 0.0074
2019-01-20T09:42:23+00:00 EXX ETH USD 110.76 0.0076
2019-01-20T09:42:23+00:00 CoinBene ETH USD 117.44 0.0072
2019-01-20T09:42:23+00:00 ZBG ETH USD 117.45 0.0071

EXCHANGE_RATE_REQUEST BitMEX BTC EXX BTC
EXCHANGE_RATE_REQUEST BitMEX BTC EXX ETH
EXCHANGE_RATE_REQUEST CoinBene ETH BiBox USD"
            .as_bytes();

        // Test creation of Request from multiline text.
        let mut input = BufReader::new(text_input);
        let request = Request::<String, f32>::read_from(&mut input);

        let response = Algorithm::<String, f32, u32>::process(&request);

        // Test that all Exchange Rate Responses are present.
        assert_eq!(response.get_best_rate_paths().len(), 3);

        // Test first Exchange Rate Responses.
        assert_eq!(response.get_best_rate_paths()[0].get_rate(), &1.0);
        assert_eq!(
            response.get_best_rate_paths()[0].get_path(),
            &vec![
                ("BITMEX".to_string(), "BTC".to_string()),
                ("EXX".to_string(), "BTC".to_string())
            ]
        );

        // Test first Exchange Rate Responses.
        assert_eq!(response.get_best_rate_paths()[1].get_rate(), &27.243645);
        assert_eq!(
            response.get_best_rate_paths()[1].get_path(),
            &vec![
                ("BITMEX".to_string(), "BTC".to_string()),
                ("COINBENE".to_string(), "BTC".to_string()),
                ("COINBENE".to_string(), "USD".to_string()),
                ("EXX".to_string(), "USD".to_string()),
                ("EXX".to_string(), "ETH".to_string())
            ]
        );

        // &117.51
    }
}