trading212 0.2.15

A library for interacting with the Trading212 API
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
#![deny(missing_docs)]
//! A library for interacting with the Trading212 API
//!
//! <p style="background:rgba(255,181,77,0.16);padding:0.75em;">
//! This is very experimental and probably contains bugs and invalid documentation, use with caution
//! </p>
//!
//! # Example
//! ```
//! use trading212::Client;
//!
//! #[tokio::main]
//! async fn main() {
//!    let client = Client::new("token", trading212::Target::Demo).unwrap();
//!    let exchanges = client.get_exchanges().await.unwrap();
//!    println!("{:?}", exchanges);
//! }
//! ```
//!
//! The API is documented [here](https://t212public-api-docs.redoc.ly/)
//! It is bound to change as it is v0 and currently in Beta

#[macro_use]
extern crate serde_derive;
extern crate reqwest;
extern crate serde;
extern crate serde_json;
extern crate url;

use crate::error::Error;
use derivative::Derivative;
use log::{debug, error};
use reqwest::header::HeaderValue;
use reqwest::StatusCode;
use serde::de::DeserializeOwned;
use serde::Serialize;

pub mod error;
pub mod models;

/// The target to use for the API 0
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub enum Target {
    /// The demo account
    Demo,
    /// The live account
    Live,
}

/// The client to use for the API
#[derive(Derivative, Debug, Clone, Serialize, Deserialize)]
#[derivative(PartialEq)]
pub struct Client {
    target: Target,
    token: String,
    #[serde(skip_serializing, skip_deserializing)]
    #[derivative(PartialEq = "ignore")]
    client: reqwest::Client,
    proxy: Option<String>,
}

impl Client {
    /// Create a new client
    /// # Arguments
    /// * `token` - The token to use for authentication
    /// * `target` - The target to use for the API
    /// # Errors
    /// * `Error::Reqwest` - If the reqwest client can't be created
    ///
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    /// }
    /// ```

    pub fn new(token: &str, target: Target) -> Result<Self, Error> {
        const VERSION: &str = env!("CARGO_PKG_VERSION");
        const NAME: &str = env!("CARGO_PKG_NAME");

        let mut headers = reqwest::header::HeaderMap::new();
        if let Ok(value) = HeaderValue::from_str(token) {
            headers.insert(reqwest::header::AUTHORIZATION, value);
        }

        let client = reqwest::ClientBuilder::new()
            .user_agent(format!("{NAME}/{VERSION}"))
            .default_headers(headers);
        match client.build() {
            Ok(c) => Ok(Self {
                target,
                client: c,
                token: token.to_string(),
                proxy: None,
            }),
            Err(e) => Err(e.into()),
        }
    }

    /// Create a new client with a proxy
    /// # Arguments
    /// * `token` - The token to use for authentication
    /// * `target` - The target to use for the API
    /// * `proxy` - The proxy to use
    /// # Errors
    /// * `Error::Reqwest` - If the reqwest client can't be created
    pub fn new_with_proxy(token: &str, target: Target, proxy: &str) -> Result<Self, Error> {
        match Self::new(token, target) {
            Ok(c) => Ok(c.with_proxy(proxy)),
            Err(e) => Err(e),
        }
    }

    /// Add a proxy to the client
    /// # Arguments
    /// * `proxy` - The proxy to use
    /// # Returns
    /// * `Self` - The client with the proxy
    pub fn with_proxy(mut self, proxy: &str) -> Self {
        self.proxy = Some(proxy.to_string());
        self
    }

    async fn api_get<T: DeserializeOwned>(&self, rest_method: &str) -> Result<T, Error> {
        match self
            .client
            .get(format!(
                "{}https://{}.trading212.com/api/v0/{rest_method}",
                match self.proxy {
                    Some(ref p) => {
                        p.clone()
                    }
                    None => {
                        "".to_string()
                    }
                },
                match self.target {
                    Target::Demo => {
                        "demo"
                    }
                    Target::Live => {
                        "live"
                    }
                }
            ))
            .send()
            .await
        {
            Ok(resp) => {
                if resp.status() == StatusCode::UNAUTHORIZED {
                    return Err(Error::Token);
                }
                if resp.status() == StatusCode::FORBIDDEN {
                    return Err(Error::Scope);
                }
                if resp.status() == StatusCode::TOO_MANY_REQUESTS {
                    return Err(Error::Limit);
                }
                if resp.status() == StatusCode::REQUEST_TIMEOUT {
                    return Err(Error::Timeout);
                }
                if resp.status() == StatusCode::INTERNAL_SERVER_ERROR {
                    return Err(Error::InternalServerError(
                        resp.text().await.unwrap_or_default(),
                    ));
                }
                match resp.text().await {
                    Ok(v) => {
                        let de: Result<T, _> = serde_json::from_str(&v);
                        match de {
                            Ok(reply) => Ok(reply),
                            Err(e) => {
                                error!("Couldn't parse reply for {} call: {}", rest_method, e);
                                debug!("Source JSON: {}", v);
                                Err(e.into())
                            }
                        }
                    }
                    Err(e) => Err(e.into()),
                }
            }
            Err(e) => Err(e.into()),
        }
    }

    async fn api_post<T: DeserializeOwned, U: Serialize + ?Sized + Sync>(
        &self,
        rest_method: &str,
        body: &U,
    ) -> Result<T, Error> {
        debug!("Posting json: {:?}", serde_json::to_string(body));
        match self
            .client
            .post(format!(
                "{}https://{}.trading212.com/api/v0/{rest_method}",
                match self.proxy {
                    Some(ref p) => {
                        p.clone()
                    }
                    None => {
                        "".to_string()
                    }
                },
                match self.target {
                    Target::Demo => {
                        "demo"
                    }
                    Target::Live => {
                        "live"
                    }
                }
            ))
            .json(body)
            .send()
            .await
        {
            Ok(resp) => {
                if resp.status() == StatusCode::UNAUTHORIZED {
                    return Err(Error::Token);
                }
                if resp.status() == StatusCode::FORBIDDEN {
                    return Err(Error::Scope);
                }
                if resp.status() == StatusCode::TOO_MANY_REQUESTS {
                    return Err(Error::Limit);
                }
                if resp.status() == StatusCode::BAD_REQUEST {
                    return Err(Error::Malformed);
                }
                if resp.status() == StatusCode::REQUEST_TIMEOUT {
                    return Err(Error::Timeout);
                }
                if resp.status() == StatusCode::INTERNAL_SERVER_ERROR {
                    return Err(Error::InternalServerError(
                        resp.text().await.unwrap_or_default(),
                    ));
                }
                match resp.text().await {
                    Ok(v) => {
                        let de: Result<T, _> = serde_json::from_str(&v);
                        match de {
                            Ok(reply) => Ok(reply),
                            Err(e) => {
                                error!("Couldn't parse reply for {} call: {}", rest_method, e);
                                debug!("Source JSON: {}", v);
                                Err(e.into())
                            }
                        }
                    }
                    Err(e) => Err(e.into()),
                }
            }
            Err(e) => Err(e.into()),
        }
    }

    async fn api_delete(&self, rest_method: &str) -> Result<String, Error> {
        match self
            .client
            .delete(format!(
                "{}https://{}.trading212.com/api/v0/{rest_method}",
                match self.proxy {
                    Some(ref p) => {
                        p.clone()
                    }
                    None => {
                        "".to_string()
                    }
                },
                match self.target {
                    Target::Demo => {
                        "demo"
                    }
                    Target::Live => {
                        "live"
                    }
                }
            ))
            .send()
            .await
        {
            Ok(resp) => {
                if resp.status() == StatusCode::UNAUTHORIZED {
                    return Err(Error::Token);
                }
                if resp.status() == StatusCode::FORBIDDEN {
                    return Err(Error::Scope);
                }
                if resp.status() == StatusCode::TOO_MANY_REQUESTS {
                    return Err(Error::Limit);
                }
                if resp.status() == StatusCode::REQUEST_TIMEOUT {
                    return Err(Error::Timeout);
                }
                if resp.status() == StatusCode::INTERNAL_SERVER_ERROR {
                    return Err(Error::InternalServerError(
                        resp.text().await.unwrap_or_default(),
                    ));
                }
                match resp.text().await {
                    Ok(v) => Ok(v),
                    Err(e) => Err(e.into()),
                }
            }
            Err(e) => Err(e.into()),
        }
    }

    /// Fetch all exchanges and their corresponding working schedules that your account has access to
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( metadata ) missing for API key
    /// * `Error::Limit` - Too many requests 1 / 30s
    /// * `Error::Timeout` - Request timed out
    ///
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    ///    let exchanges = client.get_exchanges().await.unwrap();
    ///    println!("{:?}", exchanges);
    /// }
    /// ```
    pub async fn get_exchanges(&self) -> Result<Vec<models::exchange::Exchange>, Error> {
        self.api_get("equity/metadata/exchanges").await
    }

    /// Fetch all instruments that your account has access to
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( metadata ) missing for API key
    /// * `Error::Limit` - Too many requests 1 / 50s
    /// * `Error::Timeout` - Request timed out
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    ///    let instruments = client.get_instruments().await.unwrap();
    ///    println!("{:?}", instruments);
    /// }
    /// ```
    pub async fn get_instruments(
        &self,
    ) -> Result<Vec<models::tradeable_instrument::TradeableInstrument>, Error> {
        self.api_get("equity/metadata/instruments").await
    }

    /// Fetches all pies for the account
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( pies:read ) missing for API key
    /// * `Error::Limit` - Too many requests 1 / 30s
    /// * `Error::Timeout` - Request timed out
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    ///    let pies = client.get_all_pies().await.unwrap();
    ///    println!("{:?}", pies);
    /// }
    /// ```
    pub async fn get_all_pies(
        &self,
    ) -> Result<Vec<models::account_bucket_result_response::AccountBucketResultResponse>, Error>
    {
        self.api_get("equity/pies").await
    }

    /// Fetches a pie for the account with detailed information
    /// # Arguments
    /// * `pie_id` - The id of the pie to fetch
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( pies:read ) missing for API key
    /// * `Error::Limit` - Too many requests 1 / 5s
    /// * `Error::Timeout` - Request timed out
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    ///    let pie = client.get_pie(123456).await.unwrap();
    ///    println!("{:?}", pie);
    /// }
    /// ```
    pub async fn get_pie(
        &self,
        pie_id: i64,
    ) -> Result<models::account_bucket_instruments_detailed_response::AccountBucketInstrumentsDetailedResponse, Error>{
        self.api_get(format!("equity/pies/{pie_id}").as_str()).await
    }

    /// Creates a pie for the account by given params
    /// # Arguments
    /// * `pie` - The pie to create
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( pies:write ) missing for API key
    /// * `Error::Limit` - Too many requests 1 / 5s
    /// * `Error::Timeout` - Request timed out
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    ///    let pie = client.create_pie(trading212::models::pie_request::PieRequest::new()).await.unwrap();
    ///    println!("{:?}", pie);
    /// }
    /// ```
    pub async fn create_pie(
        &self,
        pie: models::pie_request::PieRequest,
    ) -> Result<models::account_bucket_instruments_detailed_response::AccountBucketInstrumentsDetailedResponse, Error>{
        self.api_post("equity/pies".to_string().as_str(), &pie)
            .await
    }

    /// Deletes a pie by given id
    /// # Arguments
    /// * `pie_id` - The id of the pie to delete
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( pies:write ) missing for API key
    /// * `Error::Limit` - Too many requests 1 / 5s
    /// * `Error::Timeout` - Request timed out
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    ///    client.delete_pie(123456).await.unwrap();
    /// }
    /// ```
    pub async fn delete_pie(&self, pie_id: i64) -> Result<String, Error> {
        self.api_delete(format!("equity/pies/{pie_id}").as_str())
            .await
    }

    /// Updates a pie for the account by given params
    /// # Arguments
    /// * `pie_id` - The id of the pie to update
    /// * `pie` - The pie to update
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( pies:write ) missing for API key
    /// * `Error::Limit` - Too many requests 1 / 5s
    /// * `Error::Timeout` - Request timed out
    /// # Example
    /// ```
    /// use trading212::Client;
    /// use trading212::models::pie_request::PieRequest;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    ///    let pie = client.update_pie(123456, PieRequest::new()).await.unwrap();
    ///    println!("{:?}", pie);
    /// }
    /// ```
    pub async fn update_pie(
        &self,
        pie_id: i64,
        pie: models::pie_request::PieRequest,
    ) -> Result<models::account_bucket_instruments_detailed_response::AccountBucketInstrumentsDetailedResponse, Error>{
        self.api_post(format!("equity/pies/{pie_id}").as_str(), &pie)
            .await
    }

    /// Fetches all orders for the account
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( orders:read ) missing for API key
    /// * `Error::Limit` - Too many requests 1 / 5s
    /// * `Error::Timeout` - Request timed out
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    ///    let orders = client.get_all_orders().await.unwrap();
    ///    println!("{:?}", orders);
    /// }
    /// ```
    pub async fn get_all_orders(&self) -> Result<Vec<models::order::Order>, Error> {
        self.api_get("equity/orders").await
    }

    /// Fetches an order for the account
    /// # Arguments
    /// * `order_id` - The id of the order to fetch
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( orders:read ) missing for API key
    /// * `Error::Limit` - Too many requests 1 / 1s
    /// * `Error::Timeout` - Request timed out
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    ///    let order = client.get_order(123456).await.unwrap();
    ///    println!("{:?}", order);
    /// }
    /// ```
    pub async fn get_order(&self, order_id: i64) -> Result<models::order::Order, Error> {
        self.api_get(format!("equity/orders/{order_id}").as_str())
            .await
    }

    /// Places a limit order for the account
    /// # Arguments
    /// * `order` - The order to place
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( orders:execute ) missing for API key
    /// * `Error::Limit` - Too many requests 1 / 2s
    /// * `Error::Timeout` - Request timed out
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    ///    let order = client.place_limit_order(trading212::models::limit_request::LimitRequest::new()).await.unwrap();
    ///    println!("{:?}", order);
    /// }
    /// ```
    pub async fn place_limit_order(
        &self,
        order: models::limit_request::LimitRequest,
    ) -> Result<models::order::Order, Error> {
        self.api_post("equity/orders/limit".to_string().as_str(), &order)
            .await
    }

    /// Places a market order for the account
    /// # Arguments
    /// * `order` - The order to place
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( orders:execute ) missing for API key
    /// * `Error::Limit` - Too many requests 1 / 1s
    /// * `Error::Timeout` - Request timed out
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    ///    let order = client.place_market_order(trading212::models::market_request::MarketRequest::new()).await.unwrap();
    ///    println!("{:?}", order);
    /// }
    /// ```
    pub async fn place_market_order(
        &self,
        order: models::market_request::MarketRequest,
    ) -> Result<models::order::Order, Error> {
        self.api_post("equity/orders/market".to_string().as_str(), &order)
            .await
    }

    /// Places a stop order for the account
    /// # Arguments
    /// * `order` - The order to place
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( orders:execute ) missing for API key
    /// * `Error::Limit` - Too many requests 1 / 2s
    /// * `Error::Timeout` - Request timed out
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    ///    let order = client.place_stop_order(trading212::models::stop_request::StopRequest::new()).await.unwrap();
    ///    println!("{:?}", order);
    /// }
    /// ```
    pub async fn place_stop_order(
        &self,
        order: models::stop_request::StopRequest,
    ) -> Result<models::order::Order, Error> {
        self.api_post("equity/orders/stop".to_string().as_str(), &order)
            .await
    }

    /// Places a stop limit order for the account
    /// # Arguments
    /// * `order` - The order to place
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( orders:execute ) missing for API key
    /// * `Error::Limit` - Too many requests 1 / 2s
    /// * `Error::Timeout` - Request timed out
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    ///    let order = client.place_stop_limit_order(trading212::models::stop_limit_request::StopLimitRequest::new()).await.unwrap();
    ///    println!("{:?}", order);
    /// }
    /// ```
    pub async fn place_stop_limit_order(
        &self,
        order: models::stop_limit_request::StopLimitRequest,
    ) -> Result<models::order::Order, Error> {
        self.api_post("equity/orders/stop_limit".to_string().as_str(), &order)
            .await
    }

    /// Cancels an order for the account
    /// # Arguments
    /// * `order_id` - The id of the order to cancel
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( orders:execute ) missing for API key
    /// * `Error::Limit` - Too many requests 1 / 1s
    /// * `Error::Timeout` - Request timed out
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    ///    client.cancel_order(123456).await.unwrap();
    /// }
    /// ```
    pub async fn cancel_order(&self, order_id: i64) -> Result<String, Error> {
        self.api_delete(format!("equity/orders/{order_id}").as_str())
            .await
    }

    /// Get account cash
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( account ) missing for API key
    /// * `Error::Limit` - Too many requests 1 / 2s
    /// * `Error::Timeout` - Request timed out
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    ///    let cash = client.get_account_cash().await.unwrap();
    ///    println!("{:?}", cash);
    /// }
    /// ```
    pub async fn get_account_cash(&self) -> Result<models::cash::Cash, Error> {
        self.api_get("equity/account/cash").await
    }

    /// Get account metadata
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( account ) missing for API key
    /// * `Error::Limit` - Too many requests 1 / 30s
    /// * `Error::Timeout` - Request timed out
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    ///    let metadata = client.get_account_metadata().await.unwrap();
    ///    println!("{:?}", metadata);
    /// }
    /// ```
    pub async fn get_account_metadata(&self) -> Result<models::account::Account, Error> {
        self.api_get("equity/account/info").await
    }

    /// Get all open positions
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( portfolio ) missing for API key
    /// * `Error::Limit` - Too many requests 1 / 5s
    /// * `Error::Timeout` - Request timed out
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    ///    let positions = client.get_all_open_positions().await.unwrap();
    ///    println!("{:?}", positions);
    /// }
    /// ```
    pub async fn get_all_open_positions(&self) -> Result<Vec<models::position::Position>, Error> {
        self.api_get("equity/portfolio").await
    }

    /// Get a position by id
    /// # Arguments
    /// * `position_id` - The id of the position to fetch
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( portfolio ) missing for API key
    /// * `Error::Limit` - Too many requests 1 / 1s
    /// * `Error::Timeout` - Request timed out
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    ///    let position = client.get_position(123456).await.unwrap();
    ///    println!("{:?}", position);
    /// }
    /// ```
    pub async fn get_position(
        &self,
        position_id: i64,
    ) -> Result<models::position::Position, Error> {
        self.api_get(format!("equity/portfolio/{position_id}").as_str())
            .await
    }

    /// Get order history
    /// # Arguments
    /// * `limit` - The number of orders to fetch
    /// * `cursor` - The cursor to use for pagination
    /// * `ticker` - The ticker to filter by
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( history:orders ) missing for API key
    /// * `Error::Limit` - Too many requests 6 / 1m0s
    /// * `Error::Timeout` - Request timed out
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    ///    let orders = client.get_historical_orders(None, None, None).await.unwrap();
    ///    println!("{:?}", orders);
    /// }
    /// ```
    pub async fn get_historical_orders(
        &self,
        limit: Option<i32>,
        cursor: Option<i64>,
        ticker: Option<String>,
    ) -> Result<models::paginated_response_historical_order::PaginatedResponseHistoricalOrder, Error>
    {
        let mut path = "equity/history/orders".to_string();
        if limit.is_some() || cursor.is_some() || ticker.is_some() {
            path.push('?');
        }
        if let Some(limit) = limit {
            path.push_str(format!("limit={limit}",).as_str());
        }
        if let Some(cursor) = cursor {
            path.push_str(format!("&cursor={cursor}",).as_str());
        }
        if let Some(ticker) = ticker {
            path.push_str(format!("&ticker={ticker}",).as_str());
        }
        self.api_get(&path).await
    }

    /// Get dividend history
    /// # Arguments
    /// * `limit` - The number of dividends to fetch
    /// * `cursor` - The cursor to use for pagination
    /// * `ticker` - The ticker to filter by
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( history:dividends ) missing for API key
    /// * `Error::Limit` - Too many requests 6 / 1m0s
    /// * `Error::Timeout` - Request timed out
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Demo).unwrap();
    ///    let dividends = client.get_paid_dividends(None, None, None).await.unwrap();
    ///    println!("{:?}", dividends);
    /// }
    /// ```
    pub async fn get_paid_dividends(
        &self,
        limit: Option<i32>,
        cursor: Option<i64>,
        ticker: Option<String>,
    ) -> Result<
        models::paginated_response_history_dividend_item::PaginatedResponseHistoryDividendItem,
        Error,
    > {
        let mut path = "history/dividends".to_string();
        if limit.is_some() || cursor.is_some() || ticker.is_some() {
            path.push('?');
        }
        if let Some(limit) = limit {
            path.push_str(format!("limit={limit}",).as_str());
        }
        if let Some(cursor) = cursor {
            path.push_str(format!("&cursor={cursor}",).as_str());
        }
        if let Some(ticker) = ticker {
            path.push_str(format!("&ticker={ticker}",).as_str());
        }
        self.api_get(&path).await
    }

    /// Get list of all exports
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Missing Permissions
    /// * `Error::Limit` - Too many requests 1 / 1m0s
    /// * `Error::Timeout` - Request timed out
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Live).unwrap();
    ///    let exports = client.export_list().await.unwrap();
    ///    println!("{:?}", exports);
    /// }
    /// ```
    pub async fn export_list(&self) -> Result<Vec<models::report_response::ReportResponse>, Error> {
        self.api_get("history/exports").await
    }

    /// Initiate CSV export
    /// # Arguments
    /// * `data` - The data to export
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Missing Permissions
    /// * `Error::Limit` - Too many requests 1 / 30s
    /// * `Error::Timeout` - Request timed out
    /// * `Error::Malformed` - Malformed request
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Live).unwrap();
    ///    let exports = client.export_csv(trading212::models::public_report_request::PublicReportRequest::new()).await.unwrap();
    ///    println!("{:?}", exports);
    /// }
    /// ```
    pub async fn export_csv(
        &self,
        data: models::public_report_request::PublicReportRequest,
    ) -> Result<models::enqueued_report_response::EnqueuedReportResponse, Error> {
        self.api_post("history/exports", &data).await
    }

    /// Fetch superficial information about movements to and from your account
    /// # Arguments
    /// * `limit` - The number of transactions to fetch
    /// * `cursor` - The cursor to use for pagination
    /// * `time` - The of the cursor to use for pagination
    /// # Errors
    /// * `Error::Token` - Bad API key
    /// * `Error::Scope` - Scope( history:transactions ) missing for API key
    /// * `Error::Limit` - Too many requests 6 / 1m0s
    /// * `Error::Timeout` - Request timed out
    /// * `Error::Malformed` - Malformed request
    /// # Example
    /// ```
    /// use trading212::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("token", trading212::Target::Live).unwrap();
    ///    let transactions = client.transaction_list(None, None, None).await.unwrap();
    ///    println!("{:?}", transactions);
    /// }
    /// ```
    pub async fn transaction_list(
        &self,
        limit: Option<i32>,
        cursor: Option<String>,
        time: Option<String>,
    ) -> Result<models::paginated_response_history_transaction_item::PaginatedResponseHistoryTransactionItem, Error>{
        let mut path = "history/transactions".to_string();
        if limit.is_some() || cursor.is_some() {
            path.push('?');
        }
        if let Some(limit) = limit {
            path.push_str(format!("limit={limit}").as_str());
        }
        if let Some(cursor) = cursor {
            path.push_str(format!("&cursor={cursor}").as_str());
        }
        if let Some(time) = time {
            path.push_str(format!("&time={time}").as_str());
        }
        self.api_get(&path).await
    }
}