binary-option-tools-core 0.1.3

The core of the `binary-options-tools` crate and the python library `BinaryOptionsToolsV2`.
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
538
539
540
541
542
543
544
545
546
547
use std::{
    collections::HashMap,
    time::{Duration, Instant},
};

use chrono::{DateTime, Utc};
use tracing::{debug, info, warn};
use uuid::Uuid;

use crate::{
    contstants::TIMOUT_TIME,
    error::{BinaryOptionsResult, BinaryOptionsToolsError},
    general::{client::WebSocketClient, types::Data},
    pocketoption::{
        parser::basic::LoadHistoryPeriod,
        types::order::SuccessCloseOrder,
        validators::{candle_validator, order_result_validator},
        ws::ssid::Ssid,
    },
};

use super::{
    error::PocketOptionError,
    parser::message::WebSocketMessage,
    types::{
        base::ChangeSymbol,
        callback::PocketCallback,
        data_v2::PocketData,
        info::MessageInfo,
        order::{Action, Deal, OpenOrder},
        update::{DataCandle, UpdateBalance},
    },
    validators::{history_validator, order_validator},
    ws::{connect::PocketConnect, listener::Handler, stream::StreamAsset},
};

/// Class to connect automatically to Pocket Option's quick trade passing a valid SSID
pub type PocketOption =
    WebSocketClient<WebSocketMessage, Handler, PocketConnect, Ssid, PocketData, PocketCallback>;

impl PocketOption {
    pub async fn new(ssid: impl ToString) -> BinaryOptionsResult<Self> {
        let ssid = Ssid::parse(ssid)?;
        let data = Data::new(PocketData::default());
        let handler = Handler::new(ssid.clone());
        let timeout = Duration::from_millis(500);
        let callback = PocketCallback;
        let client = WebSocketClient::init(
            ssid,
            PocketConnect {},
            data,
            handler,
            timeout,
            Some(callback),
        )
        .await?;
        // println!("Initialized!");
        Ok(client)
    }

    pub async fn trade(
        &self,
        asset: impl ToString,
        action: Action,
        amount: f64,
        time: u32,
    ) -> BinaryOptionsResult<(Uuid, Deal)> {
        let order = OpenOrder::new(
            amount,
            asset.to_string(),
            action,
            time,
            self.credentials.demo() as u32,
        )?;
        let request_id = order.request_id;
        let res = self
            .send_message_with_timout(
                Duration::from_secs(TIMOUT_TIME),
                "Trade",
                WebSocketMessage::OpenOrder(order),
                MessageInfo::SuccessopenOrder,
                order_validator(request_id),
            )
            .await?;
        if let WebSocketMessage::SuccessopenOrder(order) = res {
            debug!("Successfully opened buy trade!");
            return Ok((order.id, order));
        }
        Err(PocketOptionError::UnexpectedIncorrectWebSocketMessage(res.info()).into())
    }

    pub async fn buy(
        &self,
        asset: impl ToString,
        amount: f64,
        time: u32,
    ) -> BinaryOptionsResult<(Uuid, Deal)> {
        info!(target: "Buy", "Placing a buy trade for asset '{}', with amount '{}' and time '{}'", asset.to_string(), amount, time);
        self.trade(asset, Action::Call, amount, time).await
    }

    pub async fn sell(
        &self,
        asset: impl ToString,
        amount: f64,
        time: u32,
    ) -> BinaryOptionsResult<(Uuid, Deal)> {
        info!(target: "Sell", "Placing a sell trade for asset '{}', with amount '{}' and time '{}'", asset.to_string(), amount, time);
        self.trade(asset, Action::Put, amount, time).await
    }

    pub async fn get_deal_end_time(&self, id: Uuid) -> Option<DateTime<Utc>> {
        if let Some(trade) = self
            .data
            .get_opened_deals()
            .await
            .iter()
            .find(|d| *d == &id)
        {
            return Some(trade.close_timestamp - Duration::from_secs(2 * 3600)); // Pocket Option server seems 2 hours advanced
        }

        if let Some(trade) = self
            .data
            .get_opened_deals()
            .await
            .iter()
            .find(|d| *d == &id)
        {
            return Some(trade.close_timestamp - Duration::from_secs(2 * 3600)); // Pocket Option server seems 2 hours advanced
        }
        None
    }

    pub async fn check_results(&self, trade_id: Uuid) -> BinaryOptionsResult<Deal> {
        // TODO: Add verification so it doesn't try to wait if no trade has been made with that id

        info!(target: "CheckResults", "Checking results for trade of id {}", trade_id);
        if let Some(trade) = self
            .data
            .get_closed_deals()
            .await
            .iter()
            .find(|d| d.id == trade_id)
        {
            return Ok(trade.clone());
        }
        debug!("Trade result not found in closed deals list, waiting for closing order to check.");
        if let Some(timestamp) = self.get_deal_end_time(trade_id).await {
            let exp = timestamp
                .signed_duration_since(Utc::now()) // TODO: Change this since the current time depends on the timezone.
                .to_std()?;
            debug!(target: "CheckResult", "Expiration time in {exp:?} seconds.");
            let start = Instant::now();
            // println!("Expiration time in {exp:?} seconds.");
            let res: WebSocketMessage = match self
                .send_message_with_timeout_and_retry(
                    exp + Duration::from_secs(TIMOUT_TIME),
                    "CheckResult",
                    WebSocketMessage::None,
                    MessageInfo::SuccesscloseOrder,
                    order_result_validator(trade_id),
                )
                .await
            {
                Ok(msg) => msg,
                Err(e) => {
                    info!(target: "CheckResults", "Time elapsed, {:?}, checking closed deals one last time.", start.elapsed());
                    if let Some(deal) = self
                        .get_closed_deals()
                        .await
                        .iter()
                        .find(|d| d.id == trade_id)
                    {
                        WebSocketMessage::SuccesscloseOrder(SuccessCloseOrder {
                            profit: 0.0,
                            deals: vec![deal.to_owned()],
                        })
                    } else {
                        return Err(e);
                    }
                }
            };

            if let WebSocketMessage::SuccesscloseOrder(order) = res {
                return order
                    .deals
                    .iter()
                    .find(|d| d.id == trade_id)
                    .cloned()
                    .ok_or(
                        PocketOptionError::UnreachableError("Error finding correct trade".into())
                            .into(),
                    );
            }
            return Err(PocketOptionError::UnexpectedIncorrectWebSocketMessage(res.info()).into());
        }
        warn!("No opened trade with the given uuid please check if you are passing the correct id");
        Err(BinaryOptionsToolsError::Unallowed("Couldn't check result for a deal that is not in the list of opened trades nor closed trades.".into()))
    }

    pub async fn get_candles(
        &self,
        asset: impl ToString,
        period: i64,
        offset: i64,
    ) -> BinaryOptionsResult<Vec<DataCandle>> {
        info!(target: "GetCandles", "Retrieving candles for asset '{}' with period of '{}' and offset of '{}'", asset.to_string(), period, offset);
        let time = self.data.get_server_time().await.div_euclid(period) * period;
        if time == 0 {
            return Err(BinaryOptionsToolsError::GeneralParsingError(
                "Server time is invalid.".to_string(),
            ));
        }
        let request = LoadHistoryPeriod::new(asset.to_string(), time, period, offset)?;
        let index = request.index;
        debug!(
            "Sent get candles message, message: {:?}",
            WebSocketMessage::GetCandles(request).to_string()
        );
        let request = LoadHistoryPeriod::new(asset.to_string(), time, period, offset)?;
        let res = self
            .send_message_with_timeout_and_retry(
                Duration::from_secs(TIMOUT_TIME),
                "GetCandles",
                WebSocketMessage::GetCandles(request),
                MessageInfo::LoadHistoryPeriod,
                candle_validator(index),
            )
            .await?;
        if let WebSocketMessage::LoadHistoryPeriod(history) = res {
            return Ok(history.candle_data());
        }
        Err(PocketOptionError::UnexpectedIncorrectWebSocketMessage(res.info()).into())
    }

    pub async fn history(
        &self,
        asset: impl ToString,
        period: i64,
    ) -> BinaryOptionsResult<Vec<DataCandle>> {
        info!(target: "History", "Retrieving candles for asset '{}' with period of '{}'", asset.to_string(), period);

        let request = ChangeSymbol::new(asset.to_string(), period);
        let res = self
            .send_message_with_timeout_and_retry(
                Duration::from_secs(TIMOUT_TIME),
                "History",
                WebSocketMessage::ChangeSymbol(request),
                MessageInfo::UpdateHistoryNew,
                history_validator(asset.to_string(), period),
            )
            .await?;
        if let WebSocketMessage::UpdateHistoryNew(history) = res {
            return Ok(history.candle_data());
        }
        Err(PocketOptionError::UnexpectedIncorrectWebSocketMessage(res.info()).into())
    }

    pub async fn get_closed_deals(&self) -> Vec<Deal> {
        info!(target: "GetClosedDeals", "Retrieving list of closed deals");
        self.data.get_closed_deals().await
    }

    pub async fn clear_closed_deals(&self) {
        info!(target: "ClearClosedDeals", "Clearing list of closed deals");
        self.data.clean_closed_deals().await
    }

    pub async fn get_opened_deals(&self) -> Vec<Deal> {
        info!(target: "GetOpenDeals", "Retrieving list of open deals");
        self.data.get_opened_deals().await
    }

    pub async fn get_balance(&self) -> UpdateBalance {
        info!(target: "GetBalance", "Retrieving account balance");
        self.data.get_balance().await
    }

    pub async fn get_payout(&self) -> HashMap<String, i32> {
        info!(target: "GetPayout", "Retrieving payout for all the assets");
        self.data.get_full_payout().await
    }

    pub async fn subscribe_symbol(&self, asset: impl ToString) -> BinaryOptionsResult<StreamAsset> {
        info!(target: "SubscribeSymbol", "Subscribing to asset '{}'", asset.to_string());
        let _ = self.history(asset.to_string(), 1).await?;
        debug!("Created StreamAsset instance.");
        Ok(self.data.add_stream(asset.to_string()).await)
    }

    pub async fn subscribe_symbol_chuncked(
        &self,
        asset: impl ToString,
        chunck_size: impl Into<usize>,
    ) -> BinaryOptionsResult<StreamAsset> {
        info!(target: "SubscribeSymbolChuncked", "Subscribing to asset '{}'", asset.to_string());
        let _ = self.history(asset.to_string(), 1).await?;
        debug!("Created StreamAsset instance.");
        Ok(self
            .data
            .add_stream_chuncked(asset.to_string(), chunck_size.into())
            .await)
    }

    pub fn kill(self) {
        drop(self)
    }
}

#[cfg(test)]
mod tests {
    use std::time::Instant;

    use futures_util::{
        future::{try_join3, try_join_all},
        StreamExt,
    };
    use rand::{random, seq::SliceRandom, thread_rng};
    use tokio::{task::JoinHandle, time::sleep};

    use crate::utils::{time::timeout, tracing::start_tracing};

    use super::*;

    #[tokio::test]
    #[should_panic(expected = "MaxDemoTrades")]
    async fn test_pocket_option() {
        // start_tracing()?;
        let ssid = r#"42["auth",{"session":"looc69ct294h546o368s0lct7d","isDemo":1,"uid":87742848,"platform":2}]	"#;
        let api = PocketOption::new(ssid).await.unwrap();
        // let mut loops = 0;
        // while loops < 100 {
        //     loops += 1;
        //     sleep(Duration::from_millis(100)).await;
        // }
        for i in 0..100 {
            let now = Instant::now();
            let _ = api.buy("EURUSD_otc", 1.0, 60).await.expect("MaxDemoTrades");
            println!("Loop n°{i}, Elapsed time: {:.8?} ms", now.elapsed());
        }
    }

    #[tokio::test]
    async fn test_subscribe_symbol_v2() -> anyhow::Result<()> {
        start_tracing(true)?;
        fn to_future(stream: StreamAsset, id: i32) -> JoinHandle<anyhow::Result<()>> {
            tokio::spawn(async move {
                while let Some(item) = stream.to_stream().next().await {
                    info!("StreamAsset n°{}, price: {}", id, item?.close);
                }
                Ok(())
            })
        }
        // start_tracing()?;
        let ssid = r#"42["auth",{"session":"looc69ct294h546o368s0lct7d","isDemo":1,"uid":87742848,"platform":2}]	"#;
        let client = PocketOption::new(ssid).await?;
        let stream_asset1 = client.subscribe_symbol("EURUSD_otc").await?;
        let stream_asset2 = client.subscribe_symbol("#FB_otc").await?;
        let stream_asset3 = client.subscribe_symbol("YERUSD_otc").await?;

        let f1 = to_future(stream_asset1, 1);
        let f2 = to_future(stream_asset2, 2);
        let f3 = to_future(stream_asset3, 3);
        let _ = try_join3(f1, f2, f3).await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_get_payout() -> anyhow::Result<()> {
        let ssid = r#"42["auth",{"session":"looc69ct294h546o368s0lct7d","isDemo":1,"uid":87742848,"platform":2}]	"#;
        let api = PocketOption::new(ssid).await?;
        tokio::time::sleep(Duration::from_secs(5)).await;
        dbg!(api.get_payout().await);
        Ok(())
    }

    #[tokio::test]
    async fn test_check_win_v1() -> anyhow::Result<()> {
        start_tracing(true)?;
        let ssid = r#"42["auth",{"session":"t0mc6nefcv7ncr21g4fmtioidb","isDemo":1,"uid":90000798,"platform":2}]	"#;
        let client = PocketOption::new(ssid).await.unwrap();
        let mut test = 0;
        let mut checks = Vec::new();
        while test < 1000 {
            test += 1;
            if test % 100 == 0 {
                let res = client.sell("EURUSD_otc", 1.0, 15).await?;
                dbg!("Trade id: {}", res.0);
                let m_client = client.clone();
                let res: tokio::task::JoinHandle<Result<(), BinaryOptionsToolsError>> =
                    tokio::spawn(async move {
                        let result = m_client.check_results(res.0).await?;
                        dbg!("Trade result: {}", result.profit);
                        Ok(())
                    });
                checks.push(res);
            } else if test % 100 == 50 {
                let res = &client.buy("#AAPL_otc", 1.0, 5).await?;
                dbg!(res);
            }
            sleep(Duration::from_millis(100)).await;
        }
        try_join_all(checks).await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_check_win_v2() -> anyhow::Result<()> {
        start_tracing(true)?;
        let ssid = r#"42["auth",{"session":"t0mc6nefcv7ncr21g4fmtioidb","isDemo":1,"uid":90000798,"platform":2}]	"#;
        let client = PocketOption::new(ssid).await.unwrap();
        let times = [5, 15, 30, 60, 300];
        for time in times {
            info!("Checkind for an expiration of '{time}' seconds!");
            let res: Result<(), BinaryOptionsToolsError> =
                tokio::time::timeout(Duration::from_secs(time as u64 + 30), async {
                    let (id1, _) = client.buy("EURUSD_otc", 1.5, time).await?;
                    let (id2, _) = client.sell("EURUSD_otc", 4.2, time).await?;
                    let r1 = client.check_results(id1).await?;
                    let r2 = client.check_results(id2).await?;
                    assert_eq!(r1.id, id1);
                    assert_eq!(r2.id, id2);
                    Ok(())
                })
                .await?;
            res?;
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_check_win_v3() -> anyhow::Result<()> {
        let ssid = r#"42["auth",{"session":"t0mc6nefcv7ncr21g4fmtioidb","isDemo":1,"uid":90000798,"platform":2}]	"#;
        let client = PocketOption::new(ssid).await.unwrap();
        let times = [5, 15, 30, 60, 300];
        let assets = ["#AAPL_otc", "#MSFT_otc", "EURUSD_otc", "YERUSD_otc"];
        for asset in assets {
            for time in times {
                println!("Checkind for an expiration of '{time}' seconds!");
                let at = tokio::time::Instant::now() + Duration::from_secs(time as u64 + 5);
                let res: Result<Duration, BinaryOptionsToolsError> =
                    tokio::time::timeout_at(at, async {
                        let start = tokio::time::Instant::now();
                        let (id1, _) = client.buy(asset, 1.5, time).await?;
                        let (id2, _) = client.sell(asset, 4.2, time).await?;
                        let r1 = client.check_results(id1).await?;
                        let r2 = client.check_results(id2).await?;
                        assert_eq!(r1.id, id1);
                        assert_eq!(r2.id, id2);
                        let elapsed = start.elapsed();
                        Ok(elapsed)
                    })
                    .await?;
                let duration = res?;
                println!(
                    "Test passed for expiration of '{time}' seconds in '{:#?}'!",
                    duration
                );
            }
        }

        Ok(())
    }

    #[tokio::test]
    #[should_panic(expected = "CheckResults")]
    async fn test_timeout() {
        let ssid = r#"42["auth",{"session":"t0mc6nefcv7ncr21g4fmtioidb","isDemo":1,"uid":90000798,"platform":2}]	"#;
        let client = PocketOption::new(ssid).await.unwrap();
        let (id, _) = client.buy("EURUSD_otc", 1.5, 60).await.unwrap();
        dbg!(&id);
        let check = client.check_results(id);
        let res = timeout(Duration::from_secs(30), check, "CheckResults".into())
            .await
            .expect("CheckResults");
        dbg!(res);
    }

    #[tokio::test]
    async fn test_buy_check() -> anyhow::Result<()> {
        start_tracing(false)?;
        let ssid = r#"42["auth",{"session":"t0mc6nefcv7ncr21g4fmtioidb","isDemo":1,"uid":90000798,"platform":2}]	"#;
        let client = PocketOption::new(ssid).await.unwrap();
        let time_frames = [5, 15, 30, 60, 300];
        let assets = ["EURUSD_otc"];
        let mut rng = thread_rng();
        loop {
            let amount = (random::<f64>() * 10.0).max(1.0);
            let asset = assets.choose(&mut rng).ok_or(anyhow::anyhow!("Error"))?;
            let timeframe = time_frames
                .choose(&mut rng)
                .ok_or(anyhow::anyhow!("Error"))?;
            let direction = if random() { Action::Call } else { Action::Put };
            println!("Placing '{direction:?}' trade on asset '{asset}', amount '{amount}' usd and expiration of '{timeframe}'s.");
            let (id, _) = client
                .trade(asset, direction, amount, timeframe.to_owned())
                .await?;
            match client.check_results(id).await {
                Ok(res) => println!("Result for trade: {}", res.profit),
                Err(e) => eprintln!("Error, {e}\nTime: {}", Utc::now()),
            }
        }
    }

    #[tokio::test]
    async fn test_server_time() -> anyhow::Result<()> {
        // start_tracing(true)?;
        // start_tracing()?;
        let ssid = r#"42["auth",{"session":"looc69ct294h546o368s0lct7d","isDemo":1,"uid":87742848,"platform":2}]	"#;
        let client = PocketOption::new(ssid).await?;
        let stream = client.subscribe_symbol("EURUSD_otc").await?;
        while let Some(item) = stream.to_stream().next().await {
            let time = item?.time;
            let now_test = Utc::now() + Duration::from_secs(2 * 3600);
            let dif = time - now_test;
            println!("Difference: {:?}", dif);
        }
        Ok(())
    }

    #[tokio::test]
    async fn test_get_candles() -> anyhow::Result<()> {
        let ssid = r#"42["auth",{"session":"t0mc6nefcv7ncr21g4fmtioidb","isDemo":1,"uid":90000798,"platform":2}]	"#;
        // time: 1733040000, offset: 540000, period: 3600
        let client = PocketOption::new(ssid).await.unwrap();
        for i in 0..1000 {
            let candles = client.get_candles("EURUSD_otc", 60, 6000).await?;
            println!("Candles n°{} len: {}, ", i + 1, candles.len());
        }
        Ok(())
    }

    #[tokio::test]
    async fn test_history() -> anyhow::Result<()> {
        let ssid = r#"42["auth",{"session":"t0mc6nefcv7ncr21g4fmtioidb","isDemo":1,"uid":90000798,"platform":2}]	"#;
        // time: 1733040000, offset: 540000, period: 3600
        let client = PocketOption::new(ssid).await.unwrap();
        for i in 0..1000 {
            let candles = client.history("EURUSD_otc", 6000).await?;
            println!("Candles n°{} len: {}, ", i + 1, candles.len());
        }
        Ok(())
    }

}