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
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
mod auth;
mod error;

pub use crate::auth::AuthenticationInfo;
pub use crate::error::ApiError;
use chrono::{DateTime, Utc};
use http::StatusCode;
use itertools::Itertools;
use reqwest::header::AUTHORIZATION;
use reqwest::{Client, RequestBuilder};
use serde::de::Error as SerdeError;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{json, Number, Value};
use std::cell::RefCell;
use std::error::Error;

type SymbolId = u32;
type OrderId = u32;
type ExecutionId = u32;
type UserId = u32;

/// Version of the API.
const API_VERSION: &str = "v1";

/// Questrade client
pub struct Questrade {
    client: Client,
    auth_info: RefCell<Option<AuthenticationInfo>>,
}

impl Questrade {
    /// Creates a new API instance with the default client.
    pub fn new() -> Self {
        Self::with_client(Client::new())
    }

    /// Creates a new API instance with the specified client
    pub fn with_client(client: Client) -> Self {
        Questrade {
            client,
            auth_info: RefCell::new(None),
        }
    }

    /// Creates a new API instance with the specified auth info.
    pub fn with_authentication_only(auth_info: AuthenticationInfo) -> Self {
        Questrade::with_authentication(auth_info, Client::new())
    }

    /// Creates a new API instance with the specified auth info.
    pub fn with_authentication(auth_info: AuthenticationInfo, client: Client) -> Self {
        Questrade {
            client,
            auth_info: RefCell::new(Some(auth_info)),
        }
    }

    //region authentication

    /// Authenticates using the supplied token.
    pub async fn authenticate(
        &self,
        refresh_token: &str,
        is_demo: bool,
    ) -> Result<(), Box<dyn Error>> {
        self.auth_info.replace(Some(
            AuthenticationInfo::authenticate(refresh_token, is_demo, &self.client).await?,
        ));

        Ok(())
    }

    /// Retrieves the current authentication info (if set).
    pub fn get_auth_info(&self) -> Option<AuthenticationInfo> {
        self.auth_info.borrow().clone()
    }

    /// Obtains an active authentication token or raises an error
    fn get_active_auth(&self) -> Result<AuthenticationInfo, ApiError> {
        self.auth_info
            .borrow()
            .clone()
            .ok_or(ApiError::NotAuthenticatedError(StatusCode::UNAUTHORIZED))
    }

    //endregion

    //region accounts

    /// List all accounts associated with the authenticated user.
    pub async fn accounts(&self) -> Result<Vec<Account>, Box<dyn Error>> {
        #[derive(Serialize, Deserialize)]
        struct AccountsResponse {
            accounts: Vec<Account>,
        }

        let response = self
            .get_request_builder("accounts")?
            .send()
            .await?
            .error_for_status()
            .map_err(|e| wrap_error(e))?
            .json::<AccountsResponse>()
            .await?;

        Ok(response.accounts)
    }

    /// Retrieve account activities, including cash transactions, dividends, trades, etc.
    pub async fn account_activity(
        &self,
        account_number: &str,
        start_time: DateTime<Utc>,
        end_time: DateTime<Utc>,
    ) -> Result<Vec<AccountActivity>, Box<dyn Error>> {
        #[derive(Serialize, Deserialize)]
        struct AccountActivityResponse {
            activities: Vec<AccountActivity>,
        }

        let response = self
            .get_request_builder(format!("accounts/{}/activities", account_number).as_str())?
            .query(&[
                ("startTime", start_time.to_rfc3339()),
                ("endTime", end_time.to_rfc3339()),
            ])
            .send()
            .await?
            .error_for_status()
            .map_err(|e| wrap_error(e))?
            .json::<AccountActivityResponse>()
            .await?;

        Ok(response.activities)
    }

    /// Search for account orders.
    ///
    /// Parameters:
    ///     - `start_time` optional start of time range. Defaults to start of today, 12:00am
    ///     - `end_time` optional end of time range. Defaults to end of today, 11:59pm
    ///     - `state_filter` optionally filters order states
    pub async fn account_orders(
        &self,
        account_number: &str,
        start_time: Option<DateTime<Utc>>,
        end_time: Option<DateTime<Utc>>,
        state: Option<OrderStateFilter>,
    ) -> Result<Vec<AccountOrder>, Box<dyn Error>> {
        #[derive(Debug, Serialize, Deserialize)]
        struct AccountOrdersResponse {
            orders: Vec<AccountOrder>,
        }

        let mut query_params: Vec<(&str, String)> = Vec::new();
        if let Some(start_time) = start_time {
            query_params.push(("startTime", start_time.to_rfc3339()))
        }

        if let Some(end_time) = end_time {
            query_params.push(("endTime", end_time.to_rfc3339()))
        }

        if let Some(state) = state {
            let state = match state {
                OrderStateFilter::All => "All",
                OrderStateFilter::Open => "Open",
                OrderStateFilter::Closed => "Closed",
            };

            query_params.push(("stateFilter", state.to_string()))
        }

        let response = self
            .get_request_builder(format!("accounts/{}/orders", account_number).as_str())?
            .query(query_params.as_slice())
            .send()
            .await?
            .error_for_status()
            .map_err(|e| wrap_error(e))?
            .json::<AccountOrdersResponse>()
            .await?;

        Ok(response.orders)
    }

    /// Retrieve details for an order with a specific id
    pub async fn account_order(
        &self,
        account_number: &str,
        order_id: OrderId,
    ) -> Result<Option<AccountOrder>, Box<dyn Error>> {
        #[derive(Serialize, Deserialize)]
        struct AccountOrdersResponse {
            orders: Vec<AccountOrder>,
        }

        let mut response = self
            .get_request_builder(
                format!("accounts/{}/orders/{}", account_number, order_id).as_str(),
            )?
            .send()
            .await?
            .error_for_status()
            .map_err(|e| wrap_error(e))?
            .json::<AccountOrdersResponse>()
            .await?;

        return Ok(response.orders.pop());
    }

    /// Retrieves executions for a specific account.
    ///
    /// Parameters:
    ///     - `start_time` optional start of time range. Defaults to start of today, 12:00am
    ///     - `end_time` optional end of time range. Defaults to end of today, 11:59pm
    pub async fn account_executions(
        &self,
        account_number: &str,
        start_time: Option<DateTime<Utc>>,
        end_time: Option<DateTime<Utc>>,
    ) -> Result<Vec<AccountExecution>, Box<dyn Error>> {
        #[derive(Serialize, Deserialize)]
        struct AccountExecutionsResponse {
            executions: Vec<AccountExecution>,
        }

        let mut query_params: Vec<(&str, String)> = Vec::new();
        if let Some(start_time) = start_time {
            query_params.push(("startTime", start_time.to_rfc3339()))
        }

        if let Some(end_time) = end_time {
            query_params.push(("endTime", end_time.to_rfc3339()))
        }

        let response = self
            .get_request_builder(format!("accounts/{}/executions", account_number).as_str())?
            .query(query_params.as_slice())
            .send()
            .await?
            .error_for_status()
            .map_err(|e| wrap_error(e))?
            .json::<AccountExecutionsResponse>()
            .await?;

        Ok(response.executions)
    }

    /// Retrieves per-currency and combined balances for a specified account.
    pub async fn account_balance(
        &self,
        account_number: &str,
    ) -> Result<AccountBalances, Box<dyn Error>> {
        let response = self
            .get_request_builder(format!("accounts/{}/balances", account_number).as_str())?
            .send()
            .await?
            .error_for_status()
            .map_err(|e| wrap_error(e))?
            .json::<AccountBalances>()
            .await?;

        Ok(response)
    }

    /// Retrieves positions in a specified account.
    pub async fn account_positions(
        &self,
        account_number: &str,
    ) -> Result<Vec<AccountPosition>, Box<dyn Error>> {
        #[derive(Serialize, Deserialize)]
        struct AccountPositionsResponse {
            positions: Vec<AccountPosition>,
        }

        let response = self
            .get_request_builder(format!("accounts/{}/positions", account_number).as_str())?
            .send()
            .await?
            .error_for_status()
            .map_err(|e| wrap_error(e))?
            .json::<AccountPositionsResponse>()
            .await?;

        Ok(response.positions)
    }

    //endregion

    //region markets

    /// Retrieves a single Level 1 market data quote for one or more symbols.
    ///
    /// IMPORTANT NOTE: Questrade user needs to be subscribed to a real-time data package, to
    /// receive market quotes in real-time, otherwise call to get quote is considered snap quote and
    /// limit per market can be quickly reached. Without real-time data package, once limit is
    /// reached, the response will return delayed data.
    /// (Please check "delay" parameter in response always)
    ///
    pub async fn market_quote(&self, ids: &[SymbolId]) -> Result<Vec<MarketQuote>, Box<dyn Error>> {
        #[derive(Serialize, Deserialize)]
        struct MarketQuoteResponse {
            quotes: Vec<MarketQuote>,
        }

        let ids = ids.iter().map(ToString::to_string).join(",");

        let response = self
            .get_request_builder("markets/quotes")?
            .query(&[("ids", ids)])
            .send()
            .await?
            .error_for_status()
            .map_err(|e| wrap_error(e))?
            .json::<MarketQuoteResponse>()
            .await?;

        Ok(response.quotes)
    }

    //endregion

    //region symbols

    /// Searches for the specified symbol.
    ///
    /// params
    /// * `prefix` Prefix of a symbol or any word in the description.
    /// * `offset` Offset in number of records from the beginning of a result set.
    pub async fn symbol_search(
        &self,
        prefix: &str,
        offset: u32,
    ) -> Result<Vec<SearchEquitySymbol>, Box<dyn Error>> {
        #[derive(Serialize, Deserialize)]
        struct SymbolSearchResponse {
            symbols: Vec<SearchEquitySymbol>,
        }

        let response = self
            .get_request_builder("symbols/search")?
            .query(&[("prefix", prefix), ("offset", &offset.to_string())])
            .send()
            .await?
            .error_for_status()
            .map_err(|e| wrap_error(e))?
            .json::<SymbolSearchResponse>()
            .await?;

        Ok(response.symbols)
    }

    //endregion

    /// Retrieves current server time.
    pub async fn time(&self) -> Result<DateTime<Utc>, Box<dyn Error>> {
        #[derive(Serialize, Deserialize)]
        struct TimeResponse {
            time: DateTime<Utc>,
        }

        let response = self
            .get_request_builder("time")?
            .send()
            .await?
            .error_for_status()
            .map_err(|e| wrap_error(e))?
            .json::<TimeResponse>()
            .await?;

        Ok(response.time)
    }

    /// Get a request builder for a `get` request
    fn get_request_builder(&self, url_suffix: &str) -> Result<RequestBuilder, Box<dyn Error>> {
        let auth_info = self.get_active_auth()?;

        Ok(self
            .client
            .get(&format!(
                "{}/{}/{}",
                auth_info.api_server, API_VERSION, url_suffix
            ))
            .header(AUTHORIZATION, format!("Bearer {}", auth_info.access_token)))
    }
}

fn wrap_error(e: reqwest::Error) -> Box<dyn Error> {
    if e.is_status() {
        let status = e.status().unwrap();

        if status == 401 || status == 403 {
            return Box::new(ApiError::NotAuthenticatedError(status));
        }
    }

    Box::new(e)
}

// region accounts

/// Account record
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub struct Account {
    /// Type of the account. (Eg: Cash / Margin)
    #[serde(rename = "type")]
    pub account_type: AccountType,

    /// Eight-digit account number (e.g., "26598145").
    pub number: String,

    /// Status of the account (e.g., Active)
    pub status: AccountStatus,

    /// Whether this is a primary account for the holder.
    #[serde(rename = "isPrimary")]
    pub is_primary: bool,

    /// Whether this account is one that gets billed for various expenses such as inactivity fees, market data, etc.
    #[serde(rename = "isBilling")]
    pub is_billing: bool,

    /// Type of client holding the account (e.g., "Individual").
    #[serde(rename = "clientAccountType")]
    pub client_account_type: ClientAccountType,
}

/// Type of account.
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub enum AccountType {
    /// Cash account.
    Cash,

    ///Margin account.
    Margin,

    ///Tax Free Savings Account.
    TFSA,

    ///Registered Retirement Savings Plan.
    RRSP,

    ///Spousal RRSP.
    SRRSP,

    ///Locked-In RRSP.
    LRRSP,

    ///Locked-In Retirement Account.
    LIRA,

    ///	Life Income Fund.
    LIF,

    ///Retirement Income Fund.
    RIF,

    ///Spousal RIF.
    SRIF,

    ///Locked-In RIF.
    LRIF,

    ///Registered RIF.
    RRIF,

    ///Prescribed RIF.
    PRIF,

    ///Individual Registered Education Savings Plan.
    RESP,

    ///Family RESP.
    FRESP,
}

/// Status of an account.
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub enum AccountStatus {
    Active,

    #[serde(rename = "Suspended (Closed)")]
    SuspendedClosed,

    #[serde(rename = "Suspended (View Only)")]
    SuspendedViewOnly,

    #[serde(rename = "Liquidate Only")]
    Liquidate,

    Closed,
}

/// Type of client this account is associated with.
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub enum ClientAccountType {
    ///Account held by an individual.
    Individual,

    ///Account held jointly by several individuals (e.g., spouses).
    Joint,

    /// Non-individual account held by an informal trust.
    #[serde(rename = "Informal Trust")]
    InformalTrust,

    ///Non-individual account held by a corporation.
    Corporation,

    ///Non-individual account held by an investment club.
    #[serde(rename = "Investment Club")]
    InvestmentClub,

    ///Non-individual account held by a formal trust.
    #[serde(rename = "Formal Trust")]
    FormalTrust,

    /// Non-individual account held by a partnership.
    Partnership,

    /// Non-individual account held by a sole proprietorship.
    #[serde(rename = "Sole Proprietorship")]
    SoleProprietorship,

    ///Account held by a family.
    Family,

    /// Non-individual account held by a joint and informal trust.
    #[serde(rename = "Joint and Informal Trust")]
    JointAndInformalTrust,

    ///	Non-individual account held by an institution.
    Institution,
}

/// An activity that occurred in an account
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub struct AccountActivity {
    /// Trade date.
    #[serde(rename = "tradeDate")]
    pub trade_date: DateTime<Utc>,

    /// Date of the transaction.
    #[serde(rename = "transactionDate")]
    pub transaction_date: DateTime<Utc>,

    /// Date the trade was settled.
    #[serde(rename = "settlementDate")]
    pub settlement_date: DateTime<Utc>,

    /// Activity action.
    pub action: String,

    /// Symbol name.
    pub symbol: String,

    /// Internal unique symbol identifier.
    #[serde(rename = "symbolId")]
    pub symbol_id: SymbolId,

    /// Textual description of the activity
    pub description: String,

    /// Activity currency (ISO format).
    pub currency: String,

    /// Number of items exchanged in the activity
    pub quantity: Number,

    /// Price of the items
    pub price: Number,

    /// Gross amount of the action, before fees
    #[serde(rename = "grossAmount")]
    pub gross_amount: Number,

    /// Questrade commission amount
    pub commission: Number,

    /// Net amount of the action, after fees
    #[serde(rename = "netAmount")]
    pub net_amount: Number,

    /// Type of activity.
    #[serde(rename = "type")]
    pub activity_type: String,
}

#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub struct AccountOrder {
    /// Internal order identifier.
    pub id: OrderId,

    /// Symbol that follows Questrade symbology (e.g., "TD.TO").
    pub symbol: String,

    /// Internal symbol identifier.
    #[serde(rename = "symbolId")]
    pub symbol_id: SymbolId,

    /// Total quantity of the order.
    #[serde(rename = "totalQuantity")]
    pub total_quantity: Number,

    /// Unfilled portion of the order quantity.
    #[serde(rename = "openQuantity")]
    #[serde(deserialize_with = "deserialize_nullable_number")]
    pub open_quantity: Number,

    /// Filled portion of the order quantity.
    #[serde(rename = "filledQuantity")]
    #[serde(deserialize_with = "deserialize_nullable_number")]
    pub filled_quantity: Number,

    /// Unfilled portion of the order quantity after cancellation.
    #[serde(rename = "canceledQuantity")]
    #[serde(deserialize_with = "deserialize_nullable_number")]
    pub canceled_quantity: Number,

    /// Client view of the order side (e.g., "Buy-To-Open").
    pub side: OrderSide,

    /// Order price type (e.g., "Market").
    #[serde(rename = "orderType")]
    #[serde(alias = "type")]
    pub order_type: OrderType,

    /// Limit price.
    #[serde(rename = "limitPrice")]
    pub limit_price: Option<Number>,

    /// Stop price.
    #[serde(rename = "stopPrice")]
    pub stop_price: Option<Number>,

    /// Specifies all-or-none special instruction.
    #[serde(rename = "isAllOrNone")]
    pub is_all_or_none: bool,

    /// Specifies Anonymous special instruction.
    #[serde(rename = "isAnonymous")]
    pub is_anonymous: bool,

    /// Specifies Iceberg special instruction.
    #[serde(rename = "icebergQuantity")]
    pub iceberg_quantity: Option<Number>,

    /// Specifies Minimum special instruction.
    #[serde(rename = "minQuantity")]
    pub min_quantity: Option<Number>,

    /// Average price of all executions received for this order.
    #[serde(rename = "avgExecPrice")]
    pub avg_execution_price: Option<Number>,

    /// Price of the last execution received for the order in question.
    #[serde(rename = "lastExecPrice")]
    pub last_execution_price: Option<Number>,

    /// Identifies the software / gateway where the order originated
    pub source: String,

    #[serde(rename = "timeInForce")]
    pub time_in_force: OrderTimeInForce,

    /// Good-Till-Date marker and date parameter
    #[serde(rename = "gtdDate")]
    pub good_till_date: Option<DateTime<Utc>>,

    /// Current order state
    pub state: OrderState,

    /// Human readable order rejection reason message.
    #[serde(rename = "clientReasonStr")]
    #[serde(alias = "rejectionReason")]
    #[serde(deserialize_with = "serde_with::rust::string_empty_as_none::deserialize")]
    pub rejection_reason: Option<String>,

    /// Internal identifier of a chain to which the order belongs.
    #[serde(rename = "chainId")]
    pub chain_id: OrderId,

    /// Order creation time.
    #[serde(rename = "creationTime")]
    pub creation_time: DateTime<Utc>,

    /// Time of the last update.
    #[serde(rename = "updateTime")]
    pub update_time: DateTime<Utc>,

    /// Notes that may have been manually added by Questrade staff.
    #[serde(deserialize_with = "serde_with::rust::string_empty_as_none::deserialize")]
    pub notes: Option<String>,

    #[serde(rename = "primaryRoute")]
    pub primary_route: String,

    #[serde(rename = "secondaryRoute")]
    #[serde(deserialize_with = "serde_with::rust::string_empty_as_none::deserialize")]
    pub secondary_route: Option<String>,

    /// Order route name.
    #[serde(rename = "orderRoute")]
    pub order_route: String,

    /// Venue where non-marketable portion of the order was booked.
    #[serde(rename = "venueHoldingOrder")]
    #[serde(deserialize_with = "serde_with::rust::string_empty_as_none::deserialize")]
    pub venue_holding_order: Option<String>,

    /// Total commission amount charged for this order.
    #[serde(rename = "comissionCharged")]
    #[serde(deserialize_with = "deserialize_nullable_number")]
    pub commission_charged: Number,

    /// Identifier assigned to this order by exchange where it was routed.
    #[serde(rename = "exchangeOrderId")]
    pub exchange_order_id: String,

    /// Whether user that placed the order is a significant shareholder.
    #[serde(rename = "isSignificantShareHolder")]
    pub is_significant_shareholder: bool,

    /// Whether user that placed the order is an insider.
    #[serde(rename = "isInsider")]
    pub is_insider: bool,

    /// Whether limit offset is specified in dollars (vs. percent).
    #[serde(rename = "isLimitOffsetInDollar")]
    pub is_limit_offset_in_dollars: bool,

    /// Internal identifier of user that placed the order.
    #[serde(rename = "userId")]
    pub user_id: UserId,

    /// Commission for placing the order via the Trade Desk over the phone.
    #[serde(rename = "placementCommission")]
    #[serde(deserialize_with = "deserialize_nullable_number")]
    pub placement_commission: Number,

    // /// List of OrderLeg elements.
    // TODO: legs,
    /// Multi-leg strategy to which the order belongs.
    #[serde(rename = "strategyType")]
    pub strategy_type: String,

    /// Stop price at which order was triggered.
    #[serde(rename = "triggerStopPrice")]
    pub trigger_stop_price: Option<Number>,

    /// Internal identifier of the order group.
    #[serde(rename = "orderGroupId")]
    pub order_group_id: OrderId,

    /// Bracket Order class. Primary, Profit or Loss.
    #[serde(rename = "orderClass")]
    pub order_class: Option<String>,
}

fn deserialize_nullable_number<'de, D>(deserializer: D) -> Result<Number, D::Error>
where
    D: Deserializer<'de>,
{
    let number: Option<Number> = Deserialize::deserialize(deserializer)?;

    match number {
        Some(num) => Ok(num),
        None => match json!(0) {
            Value::Number(n) => Ok(n),
            _ => Err(D::Error::custom(format!(
                "json!(0) did not return a Value::Number",
            ))),
        },
    }
}

#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub enum OrderSide {
    Buy,

    Sell,

    /// Sell short
    Short,

    #[serde(rename = "Cov")]
    Cover,

    #[serde(rename = "BTO")]
    BuyToOpen,

    #[serde(rename = "STC")]
    SellToClose,

    #[serde(rename = "STO")]
    SellToOpen,

    #[serde(rename = "BTC")]
    BuyToClose,
}

#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub enum OrderType {
    Market,
    Limit,
    Stop,
    StopLimit,
    TrailStopInPercentage,
    TrailStopInDollar,
    TrailStopLimitInPercentage,
    TrailStopLimitInDollar,
    LimitOnOpen,
    LimitOnClose,
}

#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub enum OrderTimeInForce {
    Day,
    GoodTillCanceled,
    GoodTillExtendedDay,
    GoodTillDate,
    ImmediateOrCancel,
    FillOrKill,
}

#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub enum OrderState {
    Failed,
    Pending,
    Accepted,
    Rejected,
    CancelPending,
    Canceled,
    PartialCanceled,
    Partial,
    Executed,
    ReplacePending,
    Replaced,
    Stopped,
    Suspended,
    Expired,
    Queued,
    Triggered,
    Activated,
    PendingRiskReview,
    ContingentOrder,
}

#[derive(Clone, PartialEq, Debug)]
pub enum OrderStateFilter {
    All,
    Open,
    Closed,
}

/// An account execution.
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub struct AccountExecution {
    ///Internal identifier of the execution.
    pub id: ExecutionId,

    /// Internal identifier of the order to which the execution belongs.
    #[serde(rename = "orderId")]
    pub order_id: OrderId,

    /// Symbol that follows Questrade symbology (e.g., "TD.TO").
    pub symbol: String,

    /// Internal symbol identifier.
    #[serde(rename = "symbolId")]
    pub symbol_id: SymbolId,

    /// Execution quantity.
    #[serde(rename = "quantity")]
    pub quantity: Number,

    /// Client view of the order side (e.g., "Buy-To-Open").
    pub side: OrderSide,

    /// Execution price.
    pub price: Number,

    /// Internal identifier of the order chain to which the execution belongs.
    #[serde(rename = "orderChainId")]
    pub order_chain_id: OrderId,

    /// Execution timestamp.
    pub timestamp: DateTime<Utc>,

    /// Notes that may have been manually added by Questrade staff.
    #[serde(deserialize_with = "serde_with::rust::string_empty_as_none::deserialize")]
    pub notes: Option<String>,

    /// Questrade commission.
    pub commission: Number,

    /// Liquidity fee charged by execution venue.
    #[serde(rename = "executionFee")]
    pub execution_fee: Number,

    /// SEC fee charged on all sales of US securities.
    #[serde(rename = "secFee")]
    pub sec_fee: Number,

    /// Additional execution fee charged by TSX (if applicable).
    #[serde(rename = "canadianExecutionFee")]
    pub canadian_execution_fee: Number,

    /// Internal identifierof the parent order.
    #[serde(rename = "parentId")]
    pub parent_id: OrderId,
}

/// Account balance for specific currency.
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub struct AccountBalance {
    /// Currency of the balance figure.
    pub currency: Currency,

    /// Balance amount.
    pub cash: Number,

    /// Market value of all securities in the account in a given currency.
    #[serde(rename = "marketValue")]
    pub market_value: Number,

    /// Equity as a difference between cash and marketValue properties.
    #[serde(rename = "totalEquity")]
    pub total_equity: Number,

    /// Buying power for that particular currency side of the account.
    #[serde(rename = "buyingPower")]
    pub buying_power: Number,

    /// Maintenance excess for that particular side of the account.
    #[serde(rename = "maintenanceExcess")]
    pub maintenance_excess: Number,

    /// Whether real-time data was used to calculate the above balance.
    #[serde(rename = "isRealTime")]
    pub is_real_time: bool,
}

#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub enum Currency {
    CAD,
    USD,
}

/// Account balances.
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub struct AccountBalances {
    #[serde(rename = "perCurrencyBalances")]
    pub per_currency_balances: Vec<AccountBalance>,

    #[serde(rename = "combinedBalances")]
    pub combined_balances: Vec<AccountBalance>,

    #[serde(rename = "sodPerCurrencyBalances")]
    pub sod_per_currency_balances: Vec<AccountBalance>,

    #[serde(rename = "sodCombinedBalances")]
    pub sod_combined_balances: Vec<AccountBalance>,
}

/// Account Position.
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub struct AccountPosition {
    /// Symbol that follows Questrade symbology (e.g., "TD.TO").
    pub symbol: String,

    /// Internal symbol identifier.
    #[serde(rename = "symbolId")]
    pub symbol_id: SymbolId,

    /// Position quantity remaining open.
    #[serde(rename = "openQuantity")]
    pub open_quantity: Number,

    /// Portion of the position that was closed today.
    #[serde(rename = "closedQuantity")]
    pub closed_quantity: Number,

    /// Market value of the position (quantity x price).
    #[serde(rename = "currentMarketValue")]
    pub current_market_value: Number,

    /// Current price of the position symbol.
    #[serde(rename = "currentPrice")]
    pub current_price: Number,

    /// Average price paid for all executions constituting the position.
    #[serde(rename = "averageEntryPrice")]
    pub average_entry_price: Number,

    /// Realized profit/loss on this position.
    #[serde(rename = "closedPnl")]
    pub closed_profit_and_loss: Number,

    /// Unrealized profit/loss on this position.
    #[serde(rename = "openPnl")]
    pub open_profit_and_loss: Number,

    /// Total cost of the position.
    #[serde(rename = "totalCost")]
    pub total_cost: Number,

    /// Designates whether real-time quote was used to compute PnL.
    #[serde(rename = "isRealTime")]
    pub is_real_time: bool,

    /// Designates whether a symbol is currently undergoing a reorg.
    #[serde(rename = "isUnderReorg")]
    pub is_under_reorg: bool,
}

// endregion

// region markets

/// Spot quote for a certain Equity
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub struct MarketQuote {
    /// Symbol name following Questrade’s symbology.
    pub symbol: String,

    /// Internal symbol identifier.
    #[serde(rename = "symbolId")]
    pub symbol_id: SymbolId,

    /// Market tier.
    #[serde(deserialize_with = "serde_with::rust::string_empty_as_none::deserialize")]
    pub tier: Option<String>, //FIXME - enumeration

    /// Bid price.
    #[serde(rename = "bidPrice")]
    pub bid_price: Option<Number>,

    /// Bid quantity.
    #[serde(rename = "bidSize")]
    pub bid_size: u32,

    /// Ask price.
    #[serde(rename = "askPrice")]
    pub ask_price: Option<Number>,

    /// Ask quantity.
    #[serde(rename = "askSize")]
    pub ask_size: u32,

    /// Price of the last trade during regular trade hours.
    /// The closing price.
    #[serde(rename = "lastTradePriceTrHrs")]
    pub last_trade_price_tr_hrs: Number,

    /// Price of the last trade.
    ///
    /// May include after-hours trading.
    #[serde(rename = "lastTradePrice")]
    pub last_trade_price: Number,

    /// Quantity of the last trade.
    #[serde(rename = "lastTradeSize")]
    pub last_trade_size: u32,

    /// Trade direction.
    #[serde(rename = "lastTradeTick")]
    pub last_trade_tick: TickType,

    /// Daily trading volume
    pub volume: u32,

    /// Opening trade price.
    #[serde(rename = "openPrice")]
    pub open_price: Number,

    /// Daily high price.
    #[serde(rename = "highPrice")]
    pub high_price: Number,

    /// Daily low price.
    #[serde(rename = "lowPrice")]
    pub low_price: Number,

    /// Whether a quote is delayed or real-time.
    ///
    /// If `true` then the quote is delayed 15 minutes
    #[serde(deserialize_with = "deserialize_delay")]
    pub delay: bool,

    /// Whether trading in the symbol is currently halted.
    #[serde(rename = "isHalted")]
    pub is_halted: bool,
}

fn deserialize_delay<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
    D: Deserializer<'de>,
{
    let delay: u8 = Deserialize::deserialize(deserializer)?;

    match delay {
        0 => Ok(false),
        1 => Ok(true),
        _ => Err(D::Error::custom(format!(
            "expected delay to be '0' or '1'. Got: {}",
            delay
        ))),
    }
}

/// Equity details from a search query
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub struct SearchEquitySymbol {
    /// Symbol name. (EG: BMO)
    pub symbol: String,

    /// Internal unique symbol identifier.
    #[serde(rename = "symbolId")]
    pub symbol_id: SymbolId,

    /// Symbol description.
    pub description: String,

    /// Symbol security type.
    #[serde(rename = "securityType")]
    pub security_type: SecurityType,

    /// Primary listing exchange of the symbol.
    #[serde(rename = "listingExchange")]
    pub listing_exchange: ListingExchange,

    /// Whether a symbol has live market data.
    #[serde(rename = "isQuotable")]
    pub is_quotable: bool,

    /// Whether a symbol is tradable on the platform.
    #[serde(rename = "isTradable")]
    pub is_tradable: bool,

    /// Symbol currency.
    pub currency: Currency,
}

/// Exchange where a security is listed
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub enum ListingExchange {
    /// Toronto Stock Exchange.
    TSX,

    /// Toronto Stock Exchange Index.
    TSXI,

    /// Toronto Venture Exchange.
    TSXV,

    /// Canadian National Stock Exchange.
    CNSX,

    /// Montreal Exchange.
    MX,

    /// NASDAQ.
    NASDAQ,

    /// NASDAQ Index Feed.
    NASDAQI,

    /// New York Stock Exchange.
    NYSE,

    /// NYSE AMERICAN.
    NYSEAM,

    /// NYSE Global Index Feed.
    NYSEGIF,

    /// NYSE Arca.
    ARCA,

    /// Option Reporting Authority.
    OPRA,

    /// Pink Sheets.
    #[serde(rename = "PINX")]
    PinkSheets,

    /// OTC Bulletin Board.
    OTCBB,

    /// BATS Exchange
    BATS,

    /// Dow Jones Industrial Average
    #[serde(rename = "DJI")]
    DowJonesAverage,

    /// S&P 500
    #[serde(rename = "S&P")]
    SP,

    /// NEO Exchange
    NEO,

    /// Russell Indexes
    RUSSELL,

    /// Absent exchange
    #[serde(rename = "")]
    None,
}

/// Type of security
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub enum SecurityType {
    /// Common and preferred equities, ETFs, ETNs, units, ADRs, etc.
    Stock,

    /// Equity and index options.
    Option,

    /// Debentures, notes, bonds, both corporate and government.
    Bond,

    /// Equity or bond rights and warrants.
    Right,

    /// Physical gold (coins, wafers, bars).
    Gold,

    /// Canadian or US mutual funds.
    MutualFund,

    /// Stock indices (e.g., Dow Jones).
    Index,
}

/// Direction of trading.
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub enum TickType {
    /// Designates an uptick.
    Up,

    /// Designates an downtick.
    Down,

    /// Designates a tick that took place at the same price as a previous one.
    Equal,
}

// endregion

#[cfg(test)]
mod tests {
    use crate::auth::AuthenticationInfo;
    use crate::{
        Account, AccountBalance, AccountBalances, AccountExecution, AccountOrder, AccountPosition,
        AccountStatus, AccountType, ClientAccountType, Currency, ListingExchange, MarketQuote,
        OrderSide, OrderState, OrderTimeInForce, OrderType, Questrade, SearchEquitySymbol,
        SecurityType, TickType,
    };
    use chrono::{FixedOffset, TimeZone, Utc};
    use reqwest::Client;
    use std::error::Error;
    use std::time::Instant;

    use mockito;
    use mockito::{mock, Matcher};
    use serde_json::{json, Number, Value};
    use std::fs::read_to_string;

    trait AsNumber {
        fn to_number(self) -> Number;
    }

    impl AsNumber for Value {
        fn to_number(self) -> Number {
            match self {
                Value::Number(n) => n,
                _ => panic!("Not a number"),
            }
        }
    }

    fn get_api() -> Questrade {
        let auth_info = AuthenticationInfo {
            access_token: "mock-access-token".to_string(),
            api_server: mockito::server_url(),
            refresh_token: "".to_string(),
            expires_at: Instant::now(),
            is_demo: false,
        };

        Questrade::with_authentication(auth_info, Client::new())
    }

    // region account
    #[tokio::test]
    async fn accounts() -> Result<(), Box<dyn Error>> {
        let _m = mock("GET", "/v1/accounts")
            .with_status(200)
            .with_header("content-type", "text/json")
            .with_body(read_to_string("test/response/accounts.json")?)
            .create();

        let result = get_api().accounts().await;

        assert_eq!(
            result?,
            vec![
                Account {
                    account_type: AccountType::Margin,
                    number: "123456".to_string(),
                    status: AccountStatus::Active,
                    is_primary: false,
                    is_billing: false,
                    client_account_type: ClientAccountType::Joint,
                },
                Account {
                    account_type: AccountType::Cash,
                    number: "26598145".to_string(),
                    status: AccountStatus::Active,
                    is_primary: true,
                    is_billing: true,
                    client_account_type: ClientAccountType::Individual,
                },
            ]
        );

        Ok(())
    }

    #[tokio::test]
    async fn account_orders() -> Result<(), Box<dyn Error>> {
        let _m = mock("GET", "/v1/accounts/123456/orders")
            .with_status(200)
            .with_header("content-type", "text/json")
            .with_body(read_to_string("test/response/account-orders.json")?)
            .create();

        let result = get_api().account_orders("123456", None, None, None).await;

        assert_eq!(
            result?,
            vec![
                AccountOrder {
                    id: 173577870,
                    symbol: "AAPL".to_string(),
                    symbol_id: 8049,
                    total_quantity: json!(100).to_number(),
                    open_quantity: json!(100).to_number(),
                    filled_quantity: json!(0).to_number(),
                    canceled_quantity: json!(0).to_number(),
                    side: OrderSide::Buy,
                    order_type: OrderType::Limit,
                    limit_price: Some(json!(500.95).to_number()),
                    stop_price: None,
                    is_all_or_none: false,
                    is_anonymous: false,
                    iceberg_quantity: None,
                    min_quantity: None,
                    avg_execution_price: None,
                    last_execution_price: None,
                    source: "TradingAPI".to_string(),
                    time_in_force: OrderTimeInForce::Day,
                    good_till_date: None,
                    state: OrderState::Canceled,
                    rejection_reason: None,
                    chain_id: 173577870,
                    creation_time: FixedOffset::west(4 * 3600)
                        .ymd(2014, 10, 23)
                        .and_hms_micro(20, 3, 41, 636000)
                        .with_timezone(&Utc),
                    update_time: FixedOffset::west(4 * 3600)
                        .ymd(2014, 10, 23)
                        .and_hms_micro(20, 3, 42, 890000)
                        .with_timezone(&Utc),
                    notes: None,
                    primary_route: "AUTO".to_string(),
                    secondary_route: None,
                    order_route: "LAMP".to_string(),
                    venue_holding_order: None,
                    commission_charged: json!(0).to_number(),
                    exchange_order_id: "XS173577870".to_string(),
                    is_significant_shareholder: false,
                    is_insider: false,
                    is_limit_offset_in_dollars: false,
                    user_id: 3000124,
                    placement_commission: json!(0).to_number(),
                    strategy_type: "SingleLeg".to_string(),
                    trigger_stop_price: None,
                    order_group_id: 0,
                    order_class: None
                },
                AccountOrder {
                    id: 173567569,
                    symbol: "XSP".to_string(),
                    symbol_id: 12873,
                    total_quantity: json!(3).to_number(),
                    open_quantity: json!(0).to_number(),
                    filled_quantity: json!(0).to_number(),
                    canceled_quantity: json!(0).to_number(),
                    side: OrderSide::Buy,
                    order_type: OrderType::Limit,
                    limit_price: Some(json!(35.05).to_number()),
                    stop_price: None,
                    is_all_or_none: false,
                    is_anonymous: false,
                    iceberg_quantity: None,
                    min_quantity: None,
                    avg_execution_price: None,
                    last_execution_price: None,
                    source: "QuestradeIQEdge".to_string(),
                    time_in_force: OrderTimeInForce::Day,
                    good_till_date: None,
                    state: OrderState::Replaced,
                    rejection_reason: None,
                    chain_id: 173567569,
                    creation_time: FixedOffset::west(4 * 3600)
                        .ymd(2015, 08, 12)
                        .and_hms_micro(11, 2, 37, 86000)
                        .with_timezone(&Utc),
                    update_time: FixedOffset::west(4 * 3600)
                        .ymd(2015, 08, 12)
                        .and_hms_micro(11, 2, 41, 241000)
                        .with_timezone(&Utc),
                    notes: None,
                    primary_route: "AUTO".to_string(),
                    secondary_route: Some("AUTO".to_string()),
                    order_route: "ITSR".to_string(),
                    venue_holding_order: None,
                    commission_charged: json!(0).to_number(),
                    exchange_order_id: "XS173577869".to_string(),
                    is_significant_shareholder: false,
                    is_insider: false,
                    is_limit_offset_in_dollars: false,
                    user_id: 3000124,
                    placement_commission: json!(0).to_number(),
                    strategy_type: "SingleLeg".to_string(),
                    trigger_stop_price: None,
                    order_group_id: 0,
                    order_class: None
                },
                AccountOrder {
                    id: 173567570,
                    symbol: "XSP".to_string(),
                    symbol_id: 12873,
                    total_quantity: json!(3).to_number(),
                    open_quantity: json!(0).to_number(),
                    filled_quantity: json!(3).to_number(),
                    canceled_quantity: json!(0).to_number(),
                    side: OrderSide::Buy,
                    order_type: OrderType::Limit,
                    limit_price: Some(json!(15.52).to_number()),
                    stop_price: None,
                    is_all_or_none: false,
                    is_anonymous: false,
                    iceberg_quantity: None,
                    min_quantity: None,
                    avg_execution_price: Some(json!(15.52).to_number()),
                    last_execution_price: None,
                    source: "QuestradeIQEdge".to_string(),
                    time_in_force: OrderTimeInForce::Day,
                    good_till_date: None,
                    state: OrderState::Executed,
                    rejection_reason: None,
                    chain_id: 173567570,
                    creation_time: FixedOffset::west(4 * 3600)
                        .ymd(2015, 08, 12)
                        .and_hms_micro(11, 3, 37, 86000)
                        .with_timezone(&Utc),
                    update_time: FixedOffset::west(4 * 3600)
                        .ymd(2015, 08, 12)
                        .and_hms_micro(11, 03, 41, 241000)
                        .with_timezone(&Utc),
                    notes: None,
                    primary_route: "AUTO".to_string(),
                    secondary_route: Some("AUTO".to_string()),
                    order_route: "ITSR".to_string(),
                    venue_holding_order: Some("ITSR".to_string()),
                    commission_charged: json!(0.0105).to_number(),
                    exchange_order_id: "XS173577870".to_string(),
                    is_significant_shareholder: false,
                    is_insider: false,
                    is_limit_offset_in_dollars: false,
                    user_id: 3000124,
                    placement_commission: json!(0).to_number(),
                    strategy_type: "SingleLeg".to_string(),
                    trigger_stop_price: None,
                    order_group_id: 0,
                    order_class: None
                }
            ]
        );

        Ok(())
    }

    #[tokio::test]
    async fn account_order() -> Result<(), Box<dyn Error>> {
        let _m = mock("GET", "/v1/accounts/123456/orders/173577870")
            .with_status(200)
            .with_header("content-type", "text/json")
            .with_body(read_to_string(
                "test/response/account-order-173577870.json",
            )?)
            .create();

        let result = get_api().account_order("123456", 173577870).await;

        assert_eq!(
            result?,
            Some(AccountOrder {
                id: 173577870,
                symbol: "AAPL".to_string(),
                symbol_id: 8049,
                total_quantity: json!(100).to_number(),
                open_quantity: json!(100).to_number(),
                filled_quantity: json!(0).to_number(),
                canceled_quantity: json!(0).to_number(),
                side: OrderSide::Buy,
                order_type: OrderType::Limit,
                limit_price: Some(json!(500.95).to_number()),
                stop_price: None,
                is_all_or_none: false,
                is_anonymous: false,
                iceberg_quantity: None,
                min_quantity: None,
                avg_execution_price: None,
                last_execution_price: None,
                source: "TradingAPI".to_string(),
                time_in_force: OrderTimeInForce::Day,
                good_till_date: None,
                state: OrderState::Canceled,
                rejection_reason: None,
                chain_id: 173577870,
                creation_time: FixedOffset::west(4 * 3600)
                    .ymd(2014, 10, 23)
                    .and_hms_micro(20, 3, 41, 636000)
                    .with_timezone(&Utc),
                update_time: FixedOffset::west(4 * 3600)
                    .ymd(2014, 10, 23)
                    .and_hms_micro(20, 3, 42, 890000)
                    .with_timezone(&Utc),
                notes: None,
                primary_route: "AUTO".to_string(),
                secondary_route: None,
                order_route: "LAMP".to_string(),
                venue_holding_order: None,
                commission_charged: json!(0).to_number(),
                exchange_order_id: "XS173577870".to_string(),
                is_significant_shareholder: false,
                is_insider: false,
                is_limit_offset_in_dollars: false,
                user_id: 3000124,
                placement_commission: json!(0).to_number(),
                strategy_type: "SingleLeg".to_string(),
                trigger_stop_price: None,
                order_group_id: 0,
                order_class: None
            })
        );

        Ok(())
    }

    #[tokio::test]
    async fn account_order_empty() -> Result<(), Box<dyn Error>> {
        let _m = mock("GET", "/v1/accounts/123456/orders/123456")
            .with_status(200)
            .with_header("content-type", "text/json")
            .with_body(read_to_string("test/response/account-order-empty.json")?)
            .create();

        let result = get_api().account_order("123456", 123456).await;

        assert_eq!(result?, None);

        Ok(())
    }

    #[tokio::test]
    async fn account_executions() -> Result<(), Box<dyn Error>> {
        let _m = mock("GET", "/v1/accounts/26598145/executions")
            .with_status(200)
            .with_header("content-type", "text/json")
            .with_body(read_to_string("test/response/account-executions.json")?)
            .create();

        let result = get_api().account_executions("26598145", None, None).await;

        assert_eq!(
            result?,
            vec![
                AccountExecution {
                    id: 53817310,
                    order_id: 177106005,
                    symbol: "AAPL".to_string(),
                    symbol_id: 8049,
                    quantity: json!(10).to_number(),
                    side: OrderSide::Buy,
                    price: json!(536.87).to_number(),
                    order_chain_id: 17710600,
                    timestamp: FixedOffset::west(4 * 3600)
                        .ymd(2014, 03, 31)
                        .and_hms(13, 38, 29)
                        .with_timezone(&Utc),
                    notes: None,
                    commission: json!(4.95).to_number(),
                    execution_fee: json!(0).to_number(),
                    sec_fee: json!(0).to_number(),
                    canadian_execution_fee: json!(0).to_number(),
                    parent_id: 0
                },
                AccountExecution {
                    id: 710654134,
                    order_id: 700046545,
                    symbol: "XSP.TO".to_string(),
                    symbol_id: 23963,
                    quantity: json!(3).to_number(),
                    side: OrderSide::Buy,
                    price: json!(36.52).to_number(),
                    order_chain_id: 700065471,
                    timestamp: FixedOffset::west(4 * 3600)
                        .ymd(2015, 08, 19)
                        .and_hms(11, 03, 41)
                        .with_timezone(&Utc),
                    notes: None,
                    commission: json!(0).to_number(),
                    execution_fee: json!(0.0105).to_number(),
                    sec_fee: json!(0).to_number(),
                    canadian_execution_fee: json!(0).to_number(),
                    parent_id: 710651321
                }
            ]
        );

        Ok(())
    }

    #[tokio::test]
    async fn account_balance() -> Result<(), Box<dyn Error>> {
        let _m = mock("GET", "/v1/accounts/26598145/balances")
            .with_status(200)
            .with_header("content-type", "text/json")
            .with_body(read_to_string("test/response/account-balances.json")?)
            .create();

        let result = get_api().account_balance("26598145").await;

        assert_eq!(
            result?,
            AccountBalances {
                per_currency_balances: vec![
                    AccountBalance {
                        currency: Currency::CAD,
                        cash: json!(322.7015).to_number(),
                        market_value: json!(6239.64).to_number(),
                        total_equity: json!(6562.3415).to_number(),
                        buying_power: json!(15473.182995).to_number(),
                        maintenance_excess: json!(4646.6015).to_number(),
                        is_real_time: true
                    },
                    AccountBalance {
                        currency: Currency::USD,
                        cash: json!(0).to_number(),
                        market_value: json!(0).to_number(),
                        total_equity: json!(0).to_number(),
                        buying_power: json!(0).to_number(),
                        maintenance_excess: json!(0).to_number(),
                        is_real_time: true
                    }
                ],
                combined_balances: vec![
                    AccountBalance {
                        currency: Currency::CAD,
                        cash: json!(322.7015).to_number(),
                        market_value: json!(6239.64).to_number(),
                        total_equity: json!(6562.3415).to_number(),
                        buying_power: json!(15473.182995).to_number(),
                        maintenance_excess: json!(4646.6015).to_number(),
                        is_real_time: true
                    },
                    AccountBalance {
                        currency: Currency::USD,
                        cash: json!(242.541526).to_number(),
                        market_value: json!(4689.695603).to_number(),
                        total_equity: json!(4932.237129).to_number(),
                        buying_power: json!(11629.600147).to_number(),
                        maintenance_excess: json!(3492.372416).to_number(),
                        is_real_time: true
                    }
                ],
                sod_per_currency_balances: vec![
                    AccountBalance {
                        currency: Currency::CAD,
                        cash: json!(322.7015).to_number(),
                        market_value: json!(6177).to_number(),
                        total_equity: json!(6499.7015).to_number(),
                        buying_power: json!(15473.182995).to_number(),
                        maintenance_excess: json!(4646.6015).to_number(),
                        is_real_time: true
                    },
                    AccountBalance {
                        currency: Currency::USD,
                        cash: json!(0).to_number(),
                        market_value: json!(0).to_number(),
                        total_equity: json!(0).to_number(),
                        buying_power: json!(0).to_number(),
                        maintenance_excess: json!(0).to_number(),
                        is_real_time: true
                    }
                ],
                sod_combined_balances: vec![
                    AccountBalance {
                        currency: Currency::CAD,
                        cash: json!(322.7015).to_number(),
                        market_value: json!(6177).to_number(),
                        total_equity: json!(6499.7015).to_number(),
                        buying_power: json!(15473.182995).to_number(),
                        maintenance_excess: json!(4646.6015).to_number(),
                        is_real_time: true
                    },
                    AccountBalance {
                        currency: Currency::USD,
                        cash: json!(242.541526).to_number(),
                        market_value: json!(4642.615558).to_number(),
                        total_equity: json!(4885.157084).to_number(),
                        buying_power: json!(11629.600147).to_number(),
                        maintenance_excess: json!(3492.372416).to_number(),
                        is_real_time: true
                    }
                ]
            }
        );

        Ok(())
    }

    #[tokio::test]
    async fn account_positions() -> Result<(), Box<dyn Error>> {
        let _m = mock("GET", "/v1/accounts/26598145/positions")
            .with_status(200)
            .with_header("content-type", "text/json")
            .with_body(read_to_string("test/response/account-positions.json")?)
            .create();

        let result = get_api().account_positions("26598145").await;

        assert_eq!(
            result?,
            vec![
                AccountPosition {
                    symbol: "THI.TO".to_string(),
                    symbol_id: 38738,
                    open_quantity: json!(100).to_number(),
                    closed_quantity: json!(0).to_number(),
                    current_market_value: json!(6017).to_number(),
                    current_price: json!(60.17).to_number(),
                    average_entry_price: json!(60.23).to_number(),
                    closed_profit_and_loss: json!(0).to_number(),
                    open_profit_and_loss: json!(-6).to_number(),
                    total_cost: json!(6023).to_number(),
                    is_real_time: true,
                    is_under_reorg: false
                },
                AccountPosition {
                    symbol: "XSP.TO".to_string(),
                    symbol_id: 38738,
                    open_quantity: json!(100).to_number(),
                    closed_quantity: json!(0).to_number(),
                    current_market_value: json!(3571).to_number(),
                    current_price: json!(35.71).to_number(),
                    average_entry_price: json!(32.831898).to_number(),
                    closed_profit_and_loss: json!(0).to_number(),
                    open_profit_and_loss: json!(500.789748).to_number(),
                    total_cost: json!(3070.750252).to_number(),
                    is_real_time: false,
                    is_under_reorg: false
                },
            ]
        );

        Ok(())
    }

    // endregion

    // region market
    #[tokio::test]
    async fn market_quote() -> Result<(), Box<dyn Error>> {
        let _m = mock("GET", "/v1/markets/quotes")
            .match_query(Matcher::UrlEncoded("ids".into(), "2434553,27725609".into()))
            .with_status(200)
            .with_header("content-type", "text/json")
            .with_body(read_to_string("test/response/market-quotes.json")?)
            .create();

        let result = get_api().market_quote(&[2434553, 27725609]).await;

        assert_eq!(
            result?,
            vec![
                MarketQuote {
                    symbol: "XMU.TO".to_string(),
                    symbol_id: 2434553,
                    tier: None,
                    bid_price: Some(json!(57.01).to_number()),
                    bid_size: 24,
                    ask_price: Some(json!(57.13).to_number()),
                    ask_size: 33,
                    last_trade_price_tr_hrs: json!(57.15).to_number(),
                    last_trade_price: json!(57.15).to_number(),
                    last_trade_size: 100,
                    last_trade_tick: TickType::Up,
                    volume: 2728,
                    open_price: json!(55.76).to_number(),
                    high_price: json!(57.15).to_number(),
                    low_price: json!(55.76).to_number(),
                    delay: false,
                    is_halted: false
                },
                MarketQuote {
                    symbol: "XMU.U.TO".to_string(),
                    symbol_id: 27725609,
                    tier: None,
                    bid_price: Some(json!(42.65).to_number()),
                    bid_size: 10,
                    ask_price: Some(json!(42.79).to_number()),
                    ask_size: 10,
                    last_trade_price_tr_hrs: json!(44.22).to_number(),
                    last_trade_price: json!(44.22).to_number(),
                    last_trade_size: 0,
                    last_trade_tick: TickType::Equal,
                    volume: 0,
                    open_price: json!(0).to_number(),
                    high_price: json!(0).to_number(),
                    low_price: json!(0).to_number(),
                    delay: false,
                    is_halted: false
                }
            ]
        );

        Ok(())
    }

    #[tokio::test]
    async fn symbol_search() -> Result<(), Box<dyn Error>> {
        let _m = mock("GET", "/v1/symbols/search?prefix=V&offset=0")
            .with_status(200)
            .with_header("content-type", "text/json")
            .with_body(read_to_string("test/response/symbol-search.json")?)
            .create();

        let result = get_api().symbol_search("V", 0).await;

        assert_eq!(
            result?,
            vec![
                SearchEquitySymbol {
                    symbol: "V".into(),
                    symbol_id: 40825,
                    description: "VISA INC".into(),
                    security_type: SecurityType::Stock,
                    listing_exchange: ListingExchange::NYSE,
                    is_quotable: true,
                    is_tradable: true,
                    currency: Currency::USD
                },
                SearchEquitySymbol {
                    symbol: "VA.TO".into(),
                    symbol_id: 11419773,
                    description: "VANGUARD FTSE DEV ASIA PAC ALL CAP IDX".into(),
                    security_type: SecurityType::Stock,
                    listing_exchange: ListingExchange::TSX,
                    is_quotable: true,
                    is_tradable: true,
                    currency: Currency::CAD
                },
                SearchEquitySymbol {
                    symbol: "VABB".into(),
                    symbol_id: 40790,
                    description: "VIRGINIA BANK BANKSHARES INC".into(),
                    security_type: SecurityType::Stock,
                    listing_exchange: ListingExchange::PinkSheets,
                    is_quotable: true,
                    is_tradable: true,
                    currency: Currency::USD
                },
                SearchEquitySymbol {
                    symbol: "VAC".into(),
                    symbol_id: 1261992,
                    description: "MARRIOTT VACATIONS WORLDWIDE CORP".into(),
                    security_type: SecurityType::Stock,
                    listing_exchange: ListingExchange::NYSE,
                    is_quotable: true,
                    is_tradable: true,
                    currency: Currency::USD
                },
                SearchEquitySymbol {
                    symbol: "VACNY".into(),
                    symbol_id: 20491473,
                    description: "VAT GROUP AG".into(),
                    security_type: SecurityType::Stock,
                    listing_exchange: ListingExchange::PinkSheets,
                    is_quotable: true,
                    is_tradable: true,
                    currency: Currency::USD
                },
                SearchEquitySymbol {
                    symbol: "VACQU".into(),
                    symbol_id: 32441174,
                    description: "VECTOR ACQUISITION CORP UNITS(1 ORD A & 1/3 WT)30/09/2027".into(),
                    security_type: SecurityType::Stock,
                    listing_exchange: ListingExchange::NASDAQ,
                    is_quotable: true,
                    is_tradable: true,
                    currency: Currency::USD
                },
                SearchEquitySymbol {
                    symbol: "VAEEM.IN".into(),
                    symbol_id: 1630037,
                    description: "CBOE VXEEM Ask Index".into(),
                    security_type: SecurityType::Index,
                    listing_exchange: ListingExchange::SP,
                    is_quotable: true,
                    is_tradable: false,
                    currency: Currency::USD
                }
            ]
        );

        Ok(())
    }

    // endregion
}