ctrader-connector 0.3.10

Client library for the cTrader Open API and the cTrader FIX 4.4 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
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
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
//! Orders, positions and deals of a trading account, and the requests that change them.
//!
//! Volumes are in units of the symbol and prices are exact decimals; the wire integers and
//! doubles are produced and read here and nowhere else. An order is checked against the
//! trading details of its symbol before anything is sent.
//!
//! A request that trades is answered by the first execution event the server sends for it,
//! which for an order at market is its acceptance; the events that follow, the fill among them,
//! are read from the events of the connection. Such a request is written to the socket at most
//! once and is never sent again by this library: when the connection fails or the time allowed
//! runs out after it was written, the caller gets [`ConnectorError::OutcomeUnknown`] and has to
//! look the order up before deciding to place it again.
//!
//! ```no_run
//! use ctrader_connector::common::config::ConfigurationOpenApi;
//! use ctrader_connector::common::decimals::Volume;
//! use ctrader_connector::common::ids::SymbolId;
//! use ctrader_connector::open_api::client::OpenApiClient;
//! use ctrader_connector::open_api::trading::{Label, NewOrder, TradeSide};
//!
//! # async fn run() -> Result<(), ctrader_connector::common::errors::ConnectorError> {
//! let client = OpenApiClient::connect(ConfigurationOpenApi::from_env()?).await?;
//! client.authorise_application().await?;
//! let account = client.accounts().await?[0].id;
//! client.authorise_account(account).await?;
//! let symbol = &client.symbol_details(account, &[SymbolId::new(1)?]).await?[0];
//! let volume: Volume = "1000".parse()?;
//! let order = NewOrder::market(account, symbol.id, TradeSide::Buy, volume)
//!     .label(Label::new("example")?);
//! let accepted = client.place_order(&order, symbol).await?;
//! println!("{:?}: {:?}", accepted.kind, accepted.order.map(|order| order.id));
//! # Ok(())
//! # }
//! ```

use rust_decimal::Decimal;
use rust_decimal::prelude::ToPrimitive;

use crate::common::decimals::{PRICE_SCALE, Price, Volume};
use crate::common::errors::{ConnectorError, ErrorCode, ServerError, ValueError};
use crate::common::ids::{AccountId, DealId, OrderId, PositionId, SymbolId};
use crate::common::time::Timestamp;
use crate::open_api::client::OpenApiClient;
use crate::open_api::history::CashFlow;
use crate::open_api::messages::{
    ProtoMessage, ProtoOaAmendOrderReq, ProtoOaAmendPositionSltpReq, ProtoOaCancelOrderReq,
    ProtoOaClosePositionDetail, ProtoOaClosePositionReq, ProtoOaDeal, ProtoOaDealStatus,
    ProtoOaExecutionEvent, ProtoOaExecutionType, ProtoOaNewOrderReq, ProtoOaOrder,
    ProtoOaOrderErrorEvent, ProtoOaOrderStatus, ProtoOaOrderType, ProtoOaPosition,
    ProtoOaPositionStatus, ProtoOaReconcileReq, ProtoOaReconcileRes, ProtoOaTimeInForce,
    ProtoOaTradeSide,
};
use crate::open_api::payload::Payload;
use crate::open_api::symbols::Symbol;

/// Largest number of characters of a [`Label`].
pub const MAX_LABEL_LENGTH: usize = 100;
/// Largest number of characters of a [`Comment`].
pub const MAX_COMMENT_LENGTH: usize = 512;

pub(crate) const DEFAULT_MONEY_DIGITS: u32 = 2;

const LABEL: &str = "label";
const COMMENT: &str = "comment";
const VOLUME: &str = "volume";
const PRICE: &str = "price";
const MONEY: &str = "amount of money";
const DISTANCE: &str = "distance of the protection";
const SYMBOL: &str = "symbol of the order";
const TRADE_SIDE: &str = "trade side";
const ORDER_TYPE: &str = "order type";
const ORDER_STATUS: &str = "order status";
const TIME_IN_FORCE: &str = "time in force";
const EXPIRY: &str = "expiry of the order";
const POSITION_STATUS: &str = "position status";
const DEAL_STATUS: &str = "deal status";
const EXECUTION_TYPE: &str = "execution type";
const SLIPPAGE: &str = "slippage in points";
const PROTECTION: &str = "protection given as a price";
const AMENDMENT: &str = "amendment of an order that does not wait at a price";

macro_rules! text {
    ($(#[$doc:meta])* $name:ident, $kind:expr, $limit:expr) => {
        $(#[$doc])*
        #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
        pub struct $name(String);

        impl $name {
            /// Wraps the text.
            ///
            /// # Errors
            ///
            /// Returns [`ValueError::TooLong`] when the text has more characters than the
            /// server keeps.
            pub fn new(text: impl Into<String>) -> Result<Self, ValueError> {
                let text = text.into();
                let length = text.chars().count();
                if length > $limit {
                    return Err(ValueError::TooLong {
                        kind: $kind,
                        length,
                        limit: $limit,
                    });
                }
                Ok(Self(text))
            }

            /// Returns the text.
            #[must_use]
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }

        impl std::fmt::Display for $name {
            fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                formatter.write_str(&self.0)
            }
        }
    };
}

text!(
    /// Label a client gives its orders, kept by the position an order opens; at most
    /// [`MAX_LABEL_LENGTH`] characters.
    Label,
    LABEL,
    MAX_LABEL_LENGTH
);
text!(
    /// Comment of an order, kept by the position it opens; at most [`MAX_COMMENT_LENGTH`]
    /// characters.
    Comment,
    COMMENT,
    MAX_COMMENT_LENGTH
);

/// Direction of a trade.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TradeSide {
    /// The symbol is bought.
    Buy,
    /// The symbol is sold.
    Sell,
}

impl TradeSide {
    /// Returns the other direction, the one that closes a trade of this direction.
    #[must_use]
    pub const fn opposite(self) -> Self {
        match self {
            Self::Buy => Self::Sell,
            Self::Sell => Self::Buy,
        }
    }

    const fn to_wire(self) -> ProtoOaTradeSide {
        match self {
            Self::Buy => ProtoOaTradeSide::Buy,
            Self::Sell => ProtoOaTradeSide::Sell,
        }
    }

    fn from_wire(raw: i32) -> Result<Self, ValueError> {
        match ProtoOaTradeSide::try_from(raw) {
            Ok(ProtoOaTradeSide::Buy) => Ok(Self::Buy),
            Ok(ProtoOaTradeSide::Sell) => Ok(Self::Sell),
            Err(_) => Err(ValueError::OutOfRange { kind: TRADE_SIDE }),
        }
    }
}

/// Kind of an order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum OrderType {
    /// Executed at once at the price of the market.
    Market,
    /// Executed at the limit price or a better one.
    Limit,
    /// Turned into an order at market once the stop price is reached.
    Stop,
    /// Stop loss or take profit of a position.
    StopLossTakeProfit,
    /// Executed at once unless the price moved further than the slippage allows.
    MarketRange,
    /// Turned into a limit order once the stop price is reached.
    StopLimit,
}

impl OrderType {
    fn from_wire(raw: i32) -> Result<Self, ValueError> {
        match ProtoOaOrderType::try_from(raw) {
            Ok(ProtoOaOrderType::Market) => Ok(Self::Market),
            Ok(ProtoOaOrderType::Limit) => Ok(Self::Limit),
            Ok(ProtoOaOrderType::Stop) => Ok(Self::Stop),
            Ok(ProtoOaOrderType::StopLossTakeProfit) => Ok(Self::StopLossTakeProfit),
            Ok(ProtoOaOrderType::MarketRange) => Ok(Self::MarketRange),
            Ok(ProtoOaOrderType::StopLimit) => Ok(Self::StopLimit),
            Err(_) => Err(ValueError::OutOfRange { kind: ORDER_TYPE }),
        }
    }
}

/// State of an order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum OrderStatus {
    /// Accepted by the server and waiting to be executed.
    Accepted,
    /// Executed in full.
    Filled,
    /// Refused by the server.
    Rejected,
    /// Past the moment it was good till.
    Expired,
    /// Cancelled on request.
    Cancelled,
}

impl OrderStatus {
    fn from_wire(raw: i32) -> Result<Self, ValueError> {
        match ProtoOaOrderStatus::try_from(raw) {
            Ok(ProtoOaOrderStatus::OrderStatusAccepted) => Ok(Self::Accepted),
            Ok(ProtoOaOrderStatus::OrderStatusFilled) => Ok(Self::Filled),
            Ok(ProtoOaOrderStatus::OrderStatusRejected) => Ok(Self::Rejected),
            Ok(ProtoOaOrderStatus::OrderStatusExpired) => Ok(Self::Expired),
            Ok(ProtoOaOrderStatus::OrderStatusCancelled) => Ok(Self::Cancelled),
            Err(_) => Err(ValueError::OutOfRange { kind: ORDER_STATUS }),
        }
    }
}

/// How long an order stays in force.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TimeInForce {
    /// Until the given moment.
    GoodTillDate(Timestamp),
    /// Until it is executed or cancelled.
    GoodTillCancel,
    /// Whatever can be executed at once is, the rest is cancelled.
    ImmediateOrCancel,
    /// Executed at once in full or not at all.
    FillOrKill,
    /// Executed when the market opens.
    MarketOnOpen,
}

impl TimeInForce {
    fn from_wire(raw: Option<i32>, expiry: Option<i64>) -> Result<Self, ValueError> {
        let wire = raw.map_or(Ok(ProtoOaTimeInForce::ImmediateOrCancel), |raw| {
            ProtoOaTimeInForce::try_from(raw)
        });
        match wire {
            Ok(ProtoOaTimeInForce::GoodTillDate) => expiry
                .ok_or(ValueError::Missing { kind: EXPIRY })
                .and_then(Timestamp::from_millis)
                .map(Self::GoodTillDate),
            Ok(ProtoOaTimeInForce::GoodTillCancel) => Ok(Self::GoodTillCancel),
            Ok(ProtoOaTimeInForce::ImmediateOrCancel) => Ok(Self::ImmediateOrCancel),
            Ok(ProtoOaTimeInForce::FillOrKill) => Ok(Self::FillOrKill),
            Ok(ProtoOaTimeInForce::MarketOnOpen) => Ok(Self::MarketOnOpen),
            Err(_) => Err(ValueError::OutOfRange {
                kind: TIME_IN_FORCE,
            }),
        }
    }
}

/// State of a position.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PositionStatus {
    /// Open.
    Open,
    /// Closed.
    Closed,
    /// Created for a pending order that has not been executed yet.
    Created,
    /// In a state of error.
    Error,
}

impl PositionStatus {
    fn from_wire(raw: i32) -> Result<Self, ValueError> {
        match ProtoOaPositionStatus::try_from(raw) {
            Ok(ProtoOaPositionStatus::PositionStatusOpen) => Ok(Self::Open),
            Ok(ProtoOaPositionStatus::PositionStatusClosed) => Ok(Self::Closed),
            Ok(ProtoOaPositionStatus::PositionStatusCreated) => Ok(Self::Created),
            Ok(ProtoOaPositionStatus::PositionStatusError) => Ok(Self::Error),
            Err(_) => Err(ValueError::OutOfRange {
                kind: POSITION_STATUS,
            }),
        }
    }
}

/// State of a deal.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DealStatus {
    /// Executed in full.
    Filled,
    /// Executed in part.
    PartiallyFilled,
    /// Refused by the liquidity provider.
    Rejected,
    /// Refused by the server.
    InternallyRejected,
    /// Failed with an error.
    Error,
    /// Missed by the liquidity provider.
    Missed,
}

impl DealStatus {
    fn from_wire(raw: i32) -> Result<Self, ValueError> {
        match ProtoOaDealStatus::try_from(raw) {
            Ok(ProtoOaDealStatus::Filled) => Ok(Self::Filled),
            Ok(ProtoOaDealStatus::PartiallyFilled) => Ok(Self::PartiallyFilled),
            Ok(ProtoOaDealStatus::Rejected) => Ok(Self::Rejected),
            Ok(ProtoOaDealStatus::InternallyRejected) => Ok(Self::InternallyRejected),
            Ok(ProtoOaDealStatus::Error) => Ok(Self::Error),
            Ok(ProtoOaDealStatus::Missed) => Ok(Self::Missed),
            Err(_) => Err(ValueError::OutOfRange { kind: DEAL_STATUS }),
        }
    }
}

/// What an execution event reports.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ExecutionType {
    /// The order was accepted.
    Accepted,
    /// The order was executed in full.
    Filled,
    /// The order, or the protection of a position, was amended.
    Replaced,
    /// The order was cancelled.
    Cancelled,
    /// The order expired.
    Expired,
    /// The order was refused.
    Rejected,
    /// The request to cancel the order was refused.
    CancelRejected,
    /// Swap was charged to or paid for a position.
    Swap,
    /// Money was deposited to or withdrawn from the account.
    DepositWithdraw,
    /// The order was executed in part.
    PartiallyFilled,
    /// A bonus was deposited to or withdrawn from the account.
    BonusDepositWithdraw,
}

impl ExecutionType {
    fn from_wire(raw: i32) -> Result<Self, ValueError> {
        match ProtoOaExecutionType::try_from(raw) {
            Ok(ProtoOaExecutionType::OrderAccepted) => Ok(Self::Accepted),
            Ok(ProtoOaExecutionType::OrderFilled) => Ok(Self::Filled),
            Ok(ProtoOaExecutionType::OrderReplaced) => Ok(Self::Replaced),
            Ok(ProtoOaExecutionType::OrderCancelled) => Ok(Self::Cancelled),
            Ok(ProtoOaExecutionType::OrderExpired) => Ok(Self::Expired),
            Ok(ProtoOaExecutionType::OrderRejected) => Ok(Self::Rejected),
            Ok(ProtoOaExecutionType::OrderCancelRejected) => Ok(Self::CancelRejected),
            Ok(ProtoOaExecutionType::Swap) => Ok(Self::Swap),
            Ok(ProtoOaExecutionType::DepositWithdraw) => Ok(Self::DepositWithdraw),
            Ok(ProtoOaExecutionType::OrderPartialFill) => Ok(Self::PartiallyFilled),
            Ok(ProtoOaExecutionType::BonusDepositWithdraw) => Ok(Self::BonusDepositWithdraw),
            Err(_) => Err(ValueError::OutOfRange {
                kind: EXECUTION_TYPE,
            }),
        }
    }
}

/// Converts a price the wire carries as a double, rounding it to the places a price can have.
pub(crate) fn double_price(raw: f64) -> Result<Price, ValueError> {
    let value = Decimal::try_from(raw).map_err(|_| ValueError::OutOfRange { kind: PRICE })?;
    Price::new(value.round_dp(PRICE_SCALE))
}

fn optional_price(raw: Option<f64>) -> Result<Option<Price>, ValueError> {
    raw.map(double_price).transpose()
}

fn relative_price(raw: Option<i64>) -> Result<Option<Price>, ValueError> {
    raw.map(|raw| {
        u64::try_from(raw)
            .map_err(|_| ValueError::OutOfRange { kind: DISTANCE })
            .and_then(|raw| Price::from_wire(raw, PRICE_SCALE))
    })
    .transpose()
}

/// Converts an amount of money the wire carries as an integer scaled by `moneyDigits`.
pub(crate) fn money(raw: i64, digits: Option<u32>) -> Result<Decimal, ValueError> {
    Decimal::try_new(raw, digits.unwrap_or(DEFAULT_MONEY_DIGITS))
        .map_err(|_| ValueError::OutOfRange { kind: MONEY })
}

fn moment(raw: Option<i64>) -> Result<Option<Timestamp>, ValueError> {
    raw.map(Timestamp::from_millis).transpose()
}

/// Order as the server knows it.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Order {
    /// Identifier of the order.
    pub id: OrderId,
    /// Symbol the order trades.
    pub symbol: SymbolId,
    /// Direction of the order.
    pub side: TradeSide,
    /// Volume of the order, in units of the symbol.
    pub volume: Volume,
    /// Kind of the order.
    pub kind: OrderType,
    /// State of the order.
    pub status: OrderStatus,
    /// How long the order stays in force.
    pub time_in_force: TimeInForce,
    /// Limit price of a limit order.
    pub limit_price: Option<Price>,
    /// Stop price of a stop or stop-limit order.
    pub stop_price: Option<Price>,
    /// Stop loss as a price.
    pub stop_loss: Option<Price>,
    /// Take profit as a price.
    pub take_profit: Option<Price>,
    /// Stop loss as a distance from the price of execution.
    pub relative_stop_loss: Option<Price>,
    /// Take profit as a distance from the price of execution.
    pub relative_take_profit: Option<Price>,
    /// Slippage allowed to a market-range or stop-limit order, in points.
    pub slippage_points: Option<u32>,
    /// Volume executed so far.
    pub executed_volume: Option<Volume>,
    /// Price the order was executed at.
    pub execution_price: Option<Price>,
    /// Position the order opened, changes or closes.
    pub position: Option<PositionId>,
    /// Label the client gave the order.
    pub label: Option<String>,
    /// Comment of the order.
    pub comment: Option<String>,
    /// Identifier the client gave the order.
    pub client_order_id: Option<String>,
    /// Tells whether the order closes a position or a part of one.
    pub closing: bool,
    /// Tells whether the stop loss follows the price.
    pub trailing_stop_loss: bool,
    /// Moment the order was created.
    pub opened: Option<Timestamp>,
    /// Moment the order last changed.
    pub updated: Option<Timestamp>,
}

impl TryFrom<ProtoOaOrder> for Order {
    type Error = ValueError;

    fn try_from(order: ProtoOaOrder) -> Result<Self, Self::Error> {
        let data = order.trade_data;
        Ok(Self {
            id: OrderId::new(order.order_id)?,
            symbol: SymbolId::new(data.symbol_id)?,
            side: TradeSide::from_wire(data.trade_side)?,
            volume: Volume::from_wire(data.volume)?,
            kind: OrderType::from_wire(order.order_type)?,
            status: OrderStatus::from_wire(order.order_status)?,
            time_in_force: TimeInForce::from_wire(order.time_in_force, order.expiration_timestamp)?,
            limit_price: optional_price(order.limit_price)?,
            stop_price: optional_price(order.stop_price)?,
            stop_loss: optional_price(order.stop_loss)?,
            take_profit: optional_price(order.take_profit)?,
            relative_stop_loss: relative_price(order.relative_stop_loss)?,
            relative_take_profit: relative_price(order.relative_take_profit)?,
            slippage_points: order
                .slippage_in_points
                .map(|points| {
                    u32::try_from(points).map_err(|_| ValueError::OutOfRange { kind: SLIPPAGE })
                })
                .transpose()?,
            executed_volume: order.executed_volume.map(Volume::from_wire).transpose()?,
            execution_price: optional_price(order.execution_price)?,
            position: order
                .position_id
                .filter(|id| *id != 0)
                .map(PositionId::new)
                .transpose()?,
            label: data.label,
            comment: data.comment,
            client_order_id: order.client_order_id,
            closing: order.closing_order.unwrap_or(false),
            trailing_stop_loss: order.trailing_stop_loss.unwrap_or(false),
            opened: moment(data.open_timestamp)?,
            updated: moment(order.utc_last_update_timestamp)?,
        })
    }
}

/// Position as the server knows it.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Position {
    /// Identifier of the position.
    pub id: PositionId,
    /// Symbol the position is in.
    pub symbol: SymbolId,
    /// Direction of the position.
    pub side: TradeSide,
    /// Volume of the position, in units of the symbol.
    pub volume: Volume,
    /// State of the position.
    pub status: PositionStatus,
    /// Price the position was opened at, averaged over its deals.
    pub price: Option<Price>,
    /// Stop loss as a price.
    pub stop_loss: Option<Price>,
    /// Take profit as a price.
    pub take_profit: Option<Price>,
    /// Swap charged to the position so far, in the deposit currency.
    pub swap: Decimal,
    /// Commission charged to the position so far, in the deposit currency.
    pub commission: Option<Decimal>,
    /// Margin the position holds, in the deposit currency.
    pub used_margin: Option<Decimal>,
    /// Label of the order that opened the position.
    pub label: Option<String>,
    /// Comment of the order that opened the position.
    pub comment: Option<String>,
    /// Tells whether the stop loss is guaranteed.
    pub guaranteed_stop_loss: bool,
    /// Tells whether the stop loss follows the price.
    pub trailing_stop_loss: bool,
    /// Moment the position was opened.
    pub opened: Option<Timestamp>,
    /// Moment the position last changed.
    pub updated: Option<Timestamp>,
}

impl TryFrom<ProtoOaPosition> for Position {
    type Error = ValueError;

    fn try_from(position: ProtoOaPosition) -> Result<Self, Self::Error> {
        let data = position.trade_data;
        let digits = position.money_digits;
        Ok(Self {
            id: PositionId::new(position.position_id)?,
            symbol: SymbolId::new(data.symbol_id)?,
            side: TradeSide::from_wire(data.trade_side)?,
            volume: Volume::from_wire(data.volume)?,
            status: PositionStatus::from_wire(position.position_status)?,
            price: optional_price(position.price)?,
            stop_loss: optional_price(position.stop_loss)?,
            take_profit: optional_price(position.take_profit)?,
            swap: money(position.swap, digits)?,
            commission: position
                .commission
                .map(|raw| money(raw, digits))
                .transpose()?,
            used_margin: position
                .used_margin
                .map(|raw| {
                    i64::try_from(raw)
                        .map_err(|_| ValueError::OutOfRange { kind: MONEY })
                        .and_then(|raw| money(raw, digits))
                })
                .transpose()?,
            label: data.label,
            comment: data.comment,
            guaranteed_stop_loss: position.guaranteed_stop_loss.unwrap_or(false),
            trailing_stop_loss: position.trailing_stop_loss.unwrap_or(false),
            opened: moment(data.open_timestamp)?,
            updated: moment(position.utc_last_update_timestamp)?,
        })
    }
}

/// What a deal that closes a position, or a part of one, did to the account.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct ClosingDetail {
    /// Price the closed volume was opened at.
    pub entry_price: Price,
    /// Profit before swap and commission, in the deposit currency; negative for a loss.
    pub gross_profit: Decimal,
    /// Swap of the closed volume, in the deposit currency.
    pub swap: Decimal,
    /// Commission of the closed volume, in the deposit currency.
    pub commission: Decimal,
    /// Balance of the account after the deal, in the deposit currency.
    pub balance: Decimal,
    /// Volume the deal closed.
    pub closed_volume: Option<Volume>,
}

impl TryFrom<ProtoOaClosePositionDetail> for ClosingDetail {
    type Error = ValueError;

    fn try_from(detail: ProtoOaClosePositionDetail) -> Result<Self, Self::Error> {
        let digits = detail.money_digits;
        Ok(Self {
            entry_price: double_price(detail.entry_price)?,
            gross_profit: money(detail.gross_profit, digits)?,
            swap: money(detail.swap, digits)?,
            commission: money(detail.commission, digits)?,
            balance: money(detail.balance, digits)?,
            closed_volume: detail.closed_volume.map(Volume::from_wire).transpose()?,
        })
    }
}

/// Execution of an order, in full or in part.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Deal {
    /// Identifier of the deal.
    pub id: DealId,
    /// Order the deal executed.
    pub order: OrderId,
    /// Position the deal opened, added to or closed.
    pub position: PositionId,
    /// Symbol the deal traded.
    pub symbol: SymbolId,
    /// Direction of the deal.
    pub side: TradeSide,
    /// Volume the deal was sent with.
    pub volume: Volume,
    /// Volume the deal executed.
    pub filled_volume: Volume,
    /// State of the deal.
    pub status: DealStatus,
    /// Moment the deal was created.
    pub created: Timestamp,
    /// Moment the deal was executed.
    pub executed: Timestamp,
    /// Price the deal was executed at.
    pub execution_price: Option<Price>,
    /// Commission charged for the deal, in the deposit currency.
    pub commission: Option<Decimal>,
    /// What the deal did to the account, when it closed a position or a part of one.
    pub closing: Option<ClosingDetail>,
}

impl TryFrom<ProtoOaDeal> for Deal {
    type Error = ValueError;

    fn try_from(deal: ProtoOaDeal) -> Result<Self, Self::Error> {
        let digits = deal.money_digits;
        Ok(Self {
            id: DealId::new(deal.deal_id)?,
            order: OrderId::new(deal.order_id)?,
            position: PositionId::new(deal.position_id)?,
            symbol: SymbolId::new(deal.symbol_id)?,
            side: TradeSide::from_wire(deal.trade_side)?,
            volume: Volume::from_wire(deal.volume)?,
            filled_volume: Volume::from_wire(deal.filled_volume)?,
            status: DealStatus::from_wire(deal.deal_status)?,
            created: Timestamp::from_millis(deal.create_timestamp)?,
            executed: Timestamp::from_millis(deal.execution_timestamp)?,
            execution_price: optional_price(deal.execution_price)?,
            commission: deal.commission.map(|raw| money(raw, digits)).transpose()?,
            closing: deal
                .close_position_detail
                .map(ClosingDetail::try_from)
                .transpose()?,
        })
    }
}

/// One execution event: what happened, and the order, position and deal it happened to.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Execution {
    /// Account the event belongs to.
    pub account: AccountId,
    /// What happened.
    pub kind: ExecutionType,
    /// Order the event is about, as it is after the event.
    pub order: Option<Order>,
    /// Position the event is about, as it is after the event.
    pub position: Option<Position>,
    /// Deal the event reports.
    pub deal: Option<Deal>,
    /// Deposit, withdrawal or other change of the balance outside of trading the event reports.
    pub cash_flow: Option<CashFlow>,
    /// Reason the server gives when it refuses an order.
    pub error_code: Option<ErrorCode>,
    /// Tells whether the server acted by itself, as when a stop loss is hit, and not on a
    /// request of a client.
    pub server_event: bool,
}

impl TryFrom<ProtoOaExecutionEvent> for Execution {
    type Error = ValueError;

    fn try_from(event: ProtoOaExecutionEvent) -> Result<Self, Self::Error> {
        Ok(Self {
            account: AccountId::new(event.ctid_trader_account_id)?,
            kind: ExecutionType::from_wire(event.execution_type)?,
            order: event.order.map(Order::try_from).transpose()?,
            position: event.position.map(Position::try_from).transpose()?,
            deal: event.deal.map(Deal::try_from).transpose()?,
            cash_flow: event.deposit_withdraw.map(CashFlow::try_from).transpose()?,
            error_code: event.error_code.as_deref().map(ErrorCode::from_wire),
            server_event: event.is_server_event.unwrap_or(false),
        })
    }
}

/// Positions and pending orders of an account, as the server holds them.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Reconciliation {
    /// Account the positions and orders belong to.
    pub account: AccountId,
    /// Positions that are open.
    pub positions: Vec<Position>,
    /// Orders in force: the pending ones, and the ones that hold the stop loss and take profit
    /// of a position, which have [`Order::closing`] set.
    pub orders: Vec<Order>,
}

impl TryFrom<ProtoOaReconcileRes> for Reconciliation {
    type Error = ValueError;

    fn try_from(answer: ProtoOaReconcileRes) -> Result<Self, Self::Error> {
        Ok(Self {
            account: AccountId::new(answer.ctid_trader_account_id)?,
            positions: answer
                .position
                .into_iter()
                .map(Position::try_from)
                .collect::<Result<_, _>>()?,
            orders: answer
                .order
                .into_iter()
                .map(Order::try_from)
                .collect::<Result<_, _>>()?,
        })
    }
}

impl From<ProtoOaOrderErrorEvent> for ServerError {
    fn from(event: ProtoOaOrderErrorEvent) -> Self {
        let error = Self::new(ErrorCode::from_wire(&event.error_code));
        let error = match event.description {
            Some(description) => error.with_description(description),
            None => error,
        };
        match AccountId::new(event.ctid_trader_account_id) {
            Ok(account) => error.with_account_id(account),
            Err(_) => error,
        }
    }
}

fn refusal(execution: &Execution) -> ServerError {
    let code = execution
        .error_code
        .clone()
        .unwrap_or(ErrorCode::UnknownError);
    let what = match execution.kind {
        ExecutionType::CancelRejected => "the request to cancel the order was refused",
        _ => "the order was refused",
    };
    ServerError::new(code)
        .with_description(what)
        .with_account_id(execution.account)
}

/// Reads the first message that answers a request that trades.
fn traded(message: &ProtoMessage) -> Result<Execution, ConnectorError> {
    if message.payload_type == ProtoOaOrderErrorEvent::PAYLOAD_TYPE {
        return Err(ProtoOaOrderErrorEvent::from_message(message)
            .map_or_else(|error| error, |event| ServerError::from(event).into()));
    }
    let execution = Execution::try_from(ProtoOaExecutionEvent::from_message(message)?)?;
    match execution.kind {
        ExecutionType::Rejected | ExecutionType::CancelRejected => Err(refusal(&execution).into()),
        _ => Ok(execution),
    }
}

fn checked_volume(volume: Volume, symbol: &Symbol) -> Result<i64, ValueError> {
    let value = volume.value();
    let smallest = Decimal::new(1, crate::common::decimals::VOLUME_SCALE);
    let minimum = symbol.min_volume.map_or(smallest, Volume::value);
    if value < minimum || value.is_zero() {
        return Err(ValueError::BelowMinimum {
            kind: VOLUME,
            value,
            minimum,
        });
    }
    if let Some(maximum) = symbol.max_volume.map(Volume::value) {
        if value > maximum {
            return Err(ValueError::AboveMaximum {
                kind: VOLUME,
                value,
                maximum,
            });
        }
    }
    on_step(value, symbol)?;
    volume.to_wire()
}

fn on_step(value: Decimal, symbol: &Symbol) -> Result<(), ValueError> {
    if let Some(step) = symbol.step_volume.map(Volume::value) {
        let aligned = value.checked_rem(step).is_some_and(|rest| rest.is_zero());
        if !step.is_zero() && !aligned {
            return Err(ValueError::OffStep {
                kind: VOLUME,
                value,
                step,
            });
        }
    }
    Ok(())
}

fn closing_volume(volume: Volume, position: &Position, symbol: &Symbol) -> Result<i64, ValueError> {
    if symbol.id != position.symbol {
        return Err(ValueError::Mismatch { kind: SYMBOL });
    }
    let value = volume.value();
    if value.is_zero() {
        return Err(ValueError::BelowMinimum {
            kind: VOLUME,
            value,
            minimum: Decimal::new(1, crate::common::decimals::VOLUME_SCALE),
        });
    }
    let whole = position.volume.value();
    if value > whole {
        return Err(ValueError::AboveMaximum {
            kind: VOLUME,
            value,
            maximum: whole,
        });
    }
    if value < whole {
        on_step(value, symbol)?;
    }
    volume.to_wire()
}

fn checked_digits(price: Price, kind: &'static str, symbol: &Symbol) -> Result<Price, ValueError> {
    let value = price.value();
    if value.normalize().scale() > symbol.digits {
        return Err(ValueError::TooFine {
            kind,
            value,
            digits: symbol.digits,
        });
    }
    Ok(price)
}

fn checked_slippage(points: u32, stop: Option<Price>, symbol: &Symbol) -> Result<i32, ValueError> {
    let value = Decimal::from(points);
    if points == 0 {
        return Err(ValueError::BelowMinimum {
            kind: SLIPPAGE,
            value,
            minimum: Decimal::ONE,
        });
    }
    let point = Decimal::new(1, symbol.digits.min(PRICE_SCALE));
    let furthest = stop
        .and_then(|stop| stop.value().checked_div(point))
        .map_or(Decimal::from(i32::MAX), |furthest| {
            furthest.floor().min(Decimal::from(i32::MAX))
        });
    if value > furthest {
        return Err(ValueError::AboveMaximum {
            kind: SLIPPAGE,
            value,
            maximum: furthest,
        });
    }
    i32::try_from(points).map_err(|_| ValueError::OutOfRange { kind: SLIPPAGE })
}

fn checked_distance(distance: Price, symbol: &Symbol) -> Result<i64, ValueError> {
    let distance = checked_digits(distance, DISTANCE, symbol)?;
    if distance.value().is_zero() {
        return Err(ValueError::BelowMinimum {
            kind: DISTANCE,
            value: distance.value(),
            minimum: Decimal::new(1, symbol.digits.min(PRICE_SCALE)),
        });
    }
    i64::try_from(distance.to_wire()?).map_err(|_| ValueError::Unrepresentable {
        kind: DISTANCE,
        value: distance.value(),
    })
}

fn checked_price(price: Price, kind: &'static str, symbol: &Symbol) -> Result<f64, ValueError> {
    let value = checked_digits(price, kind, symbol)?.value();
    if value.is_zero() {
        return Err(ValueError::BelowMinimum {
            kind,
            value,
            minimum: Decimal::new(1, symbol.digits.min(PRICE_SCALE)),
        });
    }
    value
        .to_f64()
        .ok_or(ValueError::Unrepresentable { kind, value })
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum Terms {
    Market,
    Limit(Price),
    Stop(Price),
    StopLimit { stop: Price, slippage: u32 },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum Protection {
    At(Price),
    Away(Price),
}

impl Protection {
    fn price(self, market: bool, symbol: &Symbol) -> Result<Option<f64>, ValueError> {
        match self {
            Self::At(_) if market => Err(ValueError::Unsupported { kind: PROTECTION }),
            Self::At(price) => checked_price(price, PROTECTION, symbol).map(Some),
            Self::Away(_) => Ok(None),
        }
    }

    fn distance(self, symbol: &Symbol) -> Result<Option<i64>, ValueError> {
        match self {
            Self::At(_) => Ok(None),
            Self::Away(distance) => checked_distance(distance, symbol).map(Some),
        }
    }
}

/// Order to be placed.
///
/// An order at market is executed at once. A limit, a stop and a stop-limit order wait at
/// their price until the market reaches it, till they are cancelled or, when
/// [`good_till`](NewOrder::good_till) names a moment, till then.
///
/// Stop loss and take profit are given as prices or as distances from the price the order is
/// executed at: the stop loss lies that far below the price of a buy and above the price of a
/// sell, the take profit on the other side. The server takes only distances for an order at
/// market.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[must_use]
pub struct NewOrder {
    account: AccountId,
    symbol: SymbolId,
    side: TradeSide,
    volume: Volume,
    terms: Terms,
    expiry: Option<Timestamp>,
    label: Option<Label>,
    comment: Option<Comment>,
    stop_loss: Option<Protection>,
    take_profit: Option<Protection>,
}

impl NewOrder {
    const fn new(
        account: AccountId,
        symbol: SymbolId,
        side: TradeSide,
        volume: Volume,
        terms: Terms,
    ) -> Self {
        Self {
            account,
            symbol,
            side,
            volume,
            terms,
            expiry: None,
            label: None,
            comment: None,
            stop_loss: None,
            take_profit: None,
        }
    }

    /// Orders the volume, in units of the symbol, at the price of the market.
    pub const fn market(
        account: AccountId,
        symbol: SymbolId,
        side: TradeSide,
        volume: Volume,
    ) -> Self {
        Self::new(account, symbol, side, volume, Terms::Market)
    }

    /// Orders the volume, in units of the symbol, at the given price or a better one.
    pub const fn limit(
        account: AccountId,
        symbol: SymbolId,
        side: TradeSide,
        volume: Volume,
        price: Price,
    ) -> Self {
        Self::new(account, symbol, side, volume, Terms::Limit(price))
    }

    /// Orders the volume, in units of the symbol, at market once the given price is reached.
    pub const fn stop(
        account: AccountId,
        symbol: SymbolId,
        side: TradeSide,
        volume: Volume,
        price: Price,
    ) -> Self {
        Self::new(account, symbol, side, volume, Terms::Stop(price))
    }

    /// Orders the volume, in units of the symbol, once the given stop price is reached, at a
    /// price no further from it than the slippage, in points of the symbol.
    ///
    /// The server models the limit of a stop-limit order as that distance and takes no limit
    /// price for it. The server itself accepts any slippage up to the largest value of the
    /// wire integer, so the bound is checked before the order is sent: the slippage is at
    /// least one point and, taken as a distance in price, no larger than the stop price,
    /// beyond which the limit of a sell order would not be a positive price. A slippage
    /// outside that range yields [`ValueError::BelowMinimum`] or [`ValueError::AboveMaximum`].
    pub const fn stop_limit(
        account: AccountId,
        symbol: SymbolId,
        side: TradeSide,
        volume: Volume,
        stop: Price,
        slippage: u32,
    ) -> Self {
        Self::new(
            account,
            symbol,
            side,
            volume,
            Terms::StopLimit { stop, slippage },
        )
    }

    /// Keeps a pending order in force till the given moment and no longer.
    ///
    /// An order at market does not wait, so one with an expiry is refused before it is sent.
    pub const fn good_till(mut self, expiry: Timestamp) -> Self {
        self.expiry = Some(expiry);
        self
    }

    /// Gives the order a label, which the position it opens keeps.
    pub fn label(mut self, label: Label) -> Self {
        self.label = Some(label);
        self
    }

    /// Gives the order a comment, which the position it opens keeps.
    pub fn comment(mut self, comment: Comment) -> Self {
        self.comment = Some(comment);
        self
    }

    /// Sets a stop loss at the given price, in place of one set before.
    ///
    /// An order at market with a stop loss given as a price is refused before it is sent.
    pub const fn stop_loss(mut self, price: Price) -> Self {
        self.stop_loss = Some(Protection::At(price));
        self
    }

    /// Sets a take profit at the given price, in place of one set before.
    ///
    /// An order at market with a take profit given as a price is refused before it is sent.
    pub const fn take_profit(mut self, price: Price) -> Self {
        self.take_profit = Some(Protection::At(price));
        self
    }

    /// Sets a stop loss at the given distance from the price of execution, in place of one
    /// set before.
    pub const fn stop_loss_distance(mut self, distance: Price) -> Self {
        self.stop_loss = Some(Protection::Away(distance));
        self
    }

    /// Sets a take profit at the given distance from the price of execution, in place of one
    /// set before.
    pub const fn take_profit_distance(mut self, distance: Price) -> Self {
        self.take_profit = Some(Protection::Away(distance));
        self
    }

    /// Returns the account the order is placed on.
    #[must_use]
    pub const fn account(&self) -> AccountId {
        self.account
    }

    /// Returns the symbol the order trades.
    #[must_use]
    pub const fn symbol(&self) -> SymbolId {
        self.symbol
    }

    /// Returns the direction of the order.
    #[must_use]
    pub const fn side(&self) -> TradeSide {
        self.side
    }

    /// Returns the volume of the order, in units of the symbol.
    #[must_use]
    pub const fn volume(&self) -> Volume {
        self.volume
    }

    /// Returns the kind of the order.
    #[must_use]
    pub const fn kind(&self) -> OrderType {
        match self.terms {
            Terms::Market => OrderType::Market,
            Terms::Limit(_) => OrderType::Limit,
            Terms::Stop(_) => OrderType::Stop,
            Terms::StopLimit { .. } => OrderType::StopLimit,
        }
    }

    fn to_wire(&self, symbol: &Symbol) -> Result<ProtoOaNewOrderReq, ValueError> {
        if symbol.id != self.symbol {
            return Err(ValueError::Mismatch { kind: SYMBOL });
        }
        let market = matches!(self.terms, Terms::Market);
        if market && self.expiry.is_some() {
            return Err(ValueError::Unsupported { kind: EXPIRY });
        }
        let (kind, limit_price, stop_price, slippage) = match self.terms {
            Terms::Market => (ProtoOaOrderType::Market, None, None, None),
            Terms::Limit(price) => (
                ProtoOaOrderType::Limit,
                Some(checked_price(price, PRICE, symbol)?),
                None,
                None,
            ),
            Terms::Stop(price) => (
                ProtoOaOrderType::Stop,
                None,
                Some(checked_price(price, PRICE, symbol)?),
                None,
            ),
            Terms::StopLimit { stop, slippage } => (
                ProtoOaOrderType::StopLimit,
                None,
                Some(checked_price(stop, PRICE, symbol)?),
                Some(checked_slippage(slippage, Some(stop), symbol)?),
            ),
        };
        let time_in_force = match (market, self.expiry) {
            (true, _) => None,
            (false, Some(_)) => Some(ProtoOaTimeInForce::GoodTillDate),
            (false, None) => Some(ProtoOaTimeInForce::GoodTillCancel),
        };
        let price = |protection: Option<Protection>| {
            protection.map_or(Ok(None), |protection| protection.price(market, symbol))
        };
        let distance = |protection: Option<Protection>| {
            protection.map_or(Ok(None), |protection| protection.distance(symbol))
        };
        Ok(ProtoOaNewOrderReq {
            ctid_trader_account_id: self.account.get(),
            symbol_id: self.symbol.get(),
            order_type: i32::from(kind),
            trade_side: i32::from(self.side.to_wire()),
            volume: checked_volume(self.volume, symbol)?,
            limit_price,
            stop_price,
            slippage_in_points: slippage,
            time_in_force: time_in_force.map(i32::from),
            expiration_timestamp: self.expiry.map(Timestamp::as_millis),
            label: self.label.as_ref().map(|label| label.as_str().to_owned()),
            comment: self
                .comment
                .as_ref()
                .map(|comment| comment.as_str().to_owned()),
            stop_loss: price(self.stop_loss)?,
            take_profit: price(self.take_profit)?,
            relative_stop_loss: distance(self.stop_loss)?,
            relative_take_profit: distance(self.take_profit)?,
            ..ProtoOaNewOrderReq::default()
        })
    }
}

/// Change to a pending order.
///
/// The amendment starts from the order as it was read and carries every value the request
/// can state, changed or not, so the order ends up exactly as the amendment describes it: a
/// stop loss, a take profit or an expiry the amendment does not hold is taken off the order.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[must_use]
pub struct OrderAmendment {
    account: AccountId,
    order: OrderId,
    symbol: SymbolId,
    kind: OrderType,
    volume: Volume,
    price: Option<Price>,
    expiry: Option<Timestamp>,
    stop_loss: Option<Protection>,
    take_profit: Option<Protection>,
    slippage: Option<u32>,
}

impl OrderAmendment {
    /// Starts an amendment that leaves the order of the account as it is.
    pub fn of(account: AccountId, order: &Order) -> Self {
        let protection = |price: Option<Price>, distance: Option<Price>| {
            price
                .map(Protection::At)
                .or_else(|| distance.map(Protection::Away))
        };
        Self {
            account,
            order: order.id,
            symbol: order.symbol,
            kind: order.kind,
            volume: order.volume,
            price: match order.kind {
                OrderType::Limit => order.limit_price,
                _ => order.stop_price,
            },
            expiry: match order.time_in_force {
                TimeInForce::GoodTillDate(expiry) => Some(expiry),
                _ => None,
            },
            stop_loss: protection(order.stop_loss, order.relative_stop_loss),
            take_profit: protection(order.take_profit, order.relative_take_profit),
            slippage: order.slippage_points,
        }
    }

    /// Changes the volume, in units of the symbol.
    pub const fn volume(mut self, volume: Volume) -> Self {
        self.volume = volume;
        self
    }

    /// Changes the price the order waits at: the limit price of a limit order, the stop price
    /// of a stop or stop-limit order.
    pub const fn price(mut self, price: Price) -> Self {
        self.price = Some(price);
        self
    }

    /// Keeps the order in force till the given moment.
    pub const fn good_till(mut self, expiry: Timestamp) -> Self {
        self.expiry = Some(expiry);
        self
    }

    /// Keeps the order in force until it is executed or cancelled.
    pub const fn good_till_cancelled(mut self) -> Self {
        self.expiry = None;
        self
    }

    /// Sets the stop loss to the given price, or takes it off the order with `None`.
    pub fn stop_loss(mut self, price: Option<Price>) -> Self {
        self.stop_loss = price.map(Protection::At);
        self
    }

    /// Sets the take profit to the given price, or takes it off the order with `None`.
    pub fn take_profit(mut self, price: Option<Price>) -> Self {
        self.take_profit = price.map(Protection::At);
        self
    }

    /// Changes the slippage of a stop-limit order, in points of the symbol.
    ///
    /// The slippage is bound as that of [`NewOrder::stop_limit`], against the stop price the
    /// amendment holds, before the amendment is sent.
    pub const fn slippage(mut self, points: u32) -> Self {
        self.slippage = Some(points);
        self
    }

    /// Returns the order the amendment changes.
    #[must_use]
    pub const fn order(&self) -> OrderId {
        self.order
    }

    fn to_wire(&self, symbol: &Symbol) -> Result<ProtoOaAmendOrderReq, ValueError> {
        if symbol.id != self.symbol {
            return Err(ValueError::Mismatch { kind: SYMBOL });
        }
        let price = self
            .price
            .map(|price| checked_price(price, PRICE, symbol))
            .transpose()?;
        let (limit_price, stop_price, slippage) = match self.kind {
            OrderType::Limit => (price, None, None),
            OrderType::Stop => (None, price, None),
            OrderType::StopLimit => (None, price, self.slippage),
            _ => return Err(ValueError::Unsupported { kind: AMENDMENT }),
        };
        let at = |protection: Option<Protection>| {
            protection.map_or(Ok(None), |protection| protection.price(false, symbol))
        };
        let away = |protection: Option<Protection>| {
            protection.map_or(Ok(None), |protection| protection.distance(symbol))
        };
        Ok(ProtoOaAmendOrderReq {
            payload_type: None,
            ctid_trader_account_id: self.account.get(),
            order_id: self.order.get(),
            volume: Some(checked_volume(self.volume, symbol)?),
            limit_price,
            stop_price,
            expiration_timestamp: self.expiry.map(Timestamp::as_millis),
            stop_loss: at(self.stop_loss)?,
            take_profit: at(self.take_profit)?,
            slippage_in_points: slippage
                .map(|points| checked_slippage(points, self.price, symbol))
                .transpose()?,
            relative_stop_loss: away(self.stop_loss)?,
            relative_take_profit: away(self.take_profit)?,
            guaranteed_stop_loss: None,
            trailing_stop_loss: None,
            stop_trigger_method: None,
        })
    }
}

/// Change to the stop loss and take profit of a position.
///
/// The amendment starts from the position as it was read; the request states both prices, and
/// one it does not state is taken off the position.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[must_use]
pub struct PositionAmendment {
    account: AccountId,
    position: PositionId,
    symbol: SymbolId,
    stop_loss: Option<Price>,
    take_profit: Option<Price>,
}

impl PositionAmendment {
    /// Starts an amendment that leaves the position of the account as it is.
    pub const fn of(account: AccountId, position: &Position) -> Self {
        Self {
            account,
            position: position.id,
            symbol: position.symbol,
            stop_loss: position.stop_loss,
            take_profit: position.take_profit,
        }
    }

    /// Sets the stop loss to the given price, or removes it with `None`.
    pub const fn stop_loss(mut self, price: Option<Price>) -> Self {
        self.stop_loss = price;
        self
    }

    /// Sets the take profit to the given price, or removes it with `None`.
    pub const fn take_profit(mut self, price: Option<Price>) -> Self {
        self.take_profit = price;
        self
    }

    /// Returns the position the amendment changes.
    #[must_use]
    pub const fn position(&self) -> PositionId {
        self.position
    }

    fn to_wire(self, symbol: &Symbol) -> Result<ProtoOaAmendPositionSltpReq, ValueError> {
        if symbol.id != self.symbol {
            return Err(ValueError::Mismatch { kind: SYMBOL });
        }
        let price = |price: Option<Price>| {
            price
                .map(|price| checked_price(price, PROTECTION, symbol))
                .transpose()
        };
        Ok(ProtoOaAmendPositionSltpReq {
            payload_type: None,
            ctid_trader_account_id: self.account.get(),
            position_id: self.position.get(),
            stop_loss: price(self.stop_loss)?,
            take_profit: price(self.take_profit)?,
            guaranteed_stop_loss: None,
            trailing_stop_loss: None,
            stop_loss_trigger_method: None,
        })
    }
}

impl OpenApiClient {
    pub(crate) async fn trade<R: Payload>(&self, request: &R) -> Result<Execution, ConnectorError> {
        let message = self
            .connection()
            .request_once(R::PAYLOAD_TYPE, request.encode_to_vec())
            .await?;
        traded(&message)
    }

    /// Places an order on an authorised account and returns the first execution event the
    /// server answers with.
    ///
    /// `symbol` holds the trading details of the symbol of the order, as
    /// [`OpenApiClient::symbol_details`] returns them. The order is checked against them and
    /// nothing is sent when its volume lies outside the smallest and largest volume of the
    /// symbol or off its step, when a price or a distance is finer than the digits of the
    /// symbol, or when the order has terms its kind does not take.
    ///
    /// The first event of an order the server takes is its acceptance, with
    /// [`ExecutionType::Accepted`]. An order at market is executed right after: the fill
    /// arrives as a further event, which is read from the events of the connection. A pending
    /// order stays in force and is listed among the orders of the account.
    ///
    /// The request is written at most once and never sent again by this library.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Value`] when the order does not fit the symbol or the answer
    /// carries a value out of range, [`ConnectorError::Server`] with the code the server gives
    /// when it refuses the order, be it with an error, an order error event or an execution
    /// event that reports the refusal, [`ConnectorError::OutcomeUnknown`] when the request was
    /// written and no answer arrived, in which case the order may or may not be in force, and
    /// the errors of
    /// [`Connection::request_once`](crate::open_api::connection::Connection::request_once)
    /// otherwise.
    pub async fn place_order(
        &self,
        order: &NewOrder,
        symbol: &Symbol,
    ) -> Result<Execution, ConnectorError> {
        let request = order.to_wire(symbol)?;
        self.trade(&request).await
    }

    /// Amends a pending order and returns the first execution event the server answers with,
    /// which for an amendment the server takes has [`ExecutionType::Replaced`] and carries
    /// the order as it is afterwards.
    ///
    /// `symbol` holds the trading details of the symbol of the order; the amendment is checked
    /// against them as an order is before it is placed. Only limit, stop and stop-limit orders
    /// can be amended.
    ///
    /// The request is written at most once and never sent again by this library.
    ///
    /// # Errors
    ///
    /// Returns the errors of [`OpenApiClient::place_order`].
    pub async fn amend_order(
        &self,
        amendment: &OrderAmendment,
        symbol: &Symbol,
    ) -> Result<Execution, ConnectorError> {
        let request = amendment.to_wire(symbol)?;
        self.trade(&request).await
    }

    /// Amends the stop loss and take profit of a position and returns the first execution
    /// event the server answers with, which carries the position as it is afterwards. For an
    /// amendment the server takes the event has [`ExecutionType::Accepted`] when the position
    /// had neither a stop loss nor a take profit before, since the order that holds them is
    /// new then, and [`ExecutionType::Replaced`] otherwise.
    ///
    /// `symbol` holds the trading details of the symbol of the position; the prices are
    /// checked against its digits before anything is sent.
    ///
    /// The request is written at most once and never sent again by this library.
    ///
    /// # Errors
    ///
    /// Returns the errors of [`OpenApiClient::place_order`].
    pub async fn amend_position(
        &self,
        amendment: &PositionAmendment,
        symbol: &Symbol,
    ) -> Result<Execution, ConnectorError> {
        let request = amendment.to_wire(symbol)?;
        self.trade(&request).await
    }

    /// Cancels a pending order of an authorised account and returns the first execution event
    /// the server answers with, which for an order the server takes out of force has
    /// [`ExecutionType::Cancelled`] and carries the order as it was last.
    ///
    /// The request is written at most once and never sent again by this library.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Value`] when the answer carries a value out of range,
    /// [`ConnectorError::Server`] with the code the server gives when it refuses to cancel,
    /// be it with an error, an order error event or an execution event that reports the
    /// refusal, [`ConnectorError::OutcomeUnknown`] when the request was written and no answer
    /// arrived, in which case the order may or may not be in force, and the errors of
    /// [`Connection::request_once`](crate::open_api::connection::Connection::request_once)
    /// otherwise.
    pub async fn cancel_order(
        &self,
        account: AccountId,
        order: OrderId,
    ) -> Result<Execution, ConnectorError> {
        self.trade(&ProtoOaCancelOrderReq {
            payload_type: None,
            ctid_trader_account_id: account.get(),
            order_id: order.get(),
        })
        .await
    }

    /// Reads the open positions and the orders in force of an authorised account.
    ///
    /// The orders include the ones that hold the stop loss and take profit of a position.
    /// The answer is returned whole or not at all: one position or order that does not parse
    /// fails the call.
    ///
    /// # Errors
    ///
    /// Returns [`ConnectorError::Value`] when the answer carries a value out of range and the
    /// errors of [`Connection::request`](crate::open_api::connection::Connection::request)
    /// otherwise.
    pub async fn reconcile(&self, account: AccountId) -> Result<Reconciliation, ConnectorError> {
        let answer = self
            .connection()
            .request(&ProtoOaReconcileReq {
                payload_type: None,
                ctid_trader_account_id: account.get(),
                return_protection_orders: Some(true),
            })
            .await?;
        Ok(Reconciliation::try_from(answer)?)
    }

    /// Closes a position of an authorised account, in whole or in part, and returns the first
    /// execution event the server answers with.
    ///
    /// `position` is the position as it was last read, `volume` the part of it to close, in
    /// units of the symbol, and `symbol` holds the trading details of the symbol of the
    /// position. Nothing is sent when the volume is zero or larger than the position, or when
    /// a part of the position lies off the step of the symbol.
    ///
    /// The server closes with an order of its own: the first event is the acceptance of that
    /// order, with [`ExecutionType::Accepted`], and the fill arrives as a further event, which
    /// is read from the events of the connection and carries the deal with its
    /// [`Deal::closing`] detail and the position as it is afterwards.
    ///
    /// The request is written at most once and never sent again by this library.
    ///
    /// # Errors
    ///
    /// Returns the errors of [`OpenApiClient::place_order`]; with
    /// [`ConnectorError::OutcomeUnknown`] the position may or may not be closed.
    pub async fn close_position(
        &self,
        account: AccountId,
        position: &Position,
        volume: Volume,
        symbol: &Symbol,
    ) -> Result<Execution, ConnectorError> {
        let request = ProtoOaClosePositionReq {
            payload_type: None,
            ctid_trader_account_id: account.get(),
            position_id: position.id.get(),
            volume: closing_volume(volume, position, symbol)?,
        };
        self.trade(&request).await
    }
}

#[cfg(test)]
mod tests {
    use rust_decimal::Decimal;

    use super::{
        ClosingDetail, Comment, Deal, DealStatus, Execution, ExecutionType, Label,
        MAX_COMMENT_LENGTH, MAX_LABEL_LENGTH, Order, OrderStatus, OrderType, Position,
        PositionStatus, TimeInForce, TradeSide, double_price, money, relative_price, traded,
    };
    use crate::common::errors::{ConnectorError, ErrorCode, ValueError};
    use crate::common::time::Timestamp;
    use crate::open_api::messages::{
        ProtoOaClosePositionDetail, ProtoOaDeal, ProtoOaExecutionEvent, ProtoOaOrder,
        ProtoOaOrderErrorEvent, ProtoOaPosition, ProtoOaTradeData,
    };
    use crate::open_api::payload::Payload;

    fn out_of_range(kind: &'static str) -> ValueError {
        ValueError::OutOfRange { kind }
    }

    fn data() -> ProtoOaTradeData {
        ProtoOaTradeData {
            symbol_id: 7,
            volume: 250,
            trade_side: 2,
            open_timestamp: Some(1_700_000_000_000),
            label: Some("run".to_owned()),
            comment: Some("note".to_owned()),
            ..ProtoOaTradeData::default()
        }
    }

    fn order() -> ProtoOaOrder {
        ProtoOaOrder {
            order_id: 9,
            trade_data: data(),
            order_type: 6,
            order_status: 1,
            expiration_timestamp: Some(1_800_000_000_000),
            execution_price: Some(101.5),
            executed_volume: Some(100),
            utc_last_update_timestamp: Some(1_700_000_000_500),
            slippage_in_points: Some(30),
            closing_order: Some(true),
            limit_price: Some(100.123_45),
            stop_price: Some(99.5),
            stop_loss: Some(90.0),
            take_profit: Some(120.25),
            client_order_id: Some("mine".to_owned()),
            time_in_force: Some(1),
            position_id: Some(0),
            relative_stop_loss: Some(150_000),
            relative_take_profit: Some(300_000),
            trailing_stop_loss: Some(true),
            ..ProtoOaOrder::default()
        }
    }

    fn position() -> ProtoOaPosition {
        ProtoOaPosition {
            position_id: 5,
            trade_data: data(),
            position_status: 1,
            swap: -1_234,
            price: Some(100.5),
            stop_loss: Some(90.0),
            take_profit: Some(120.0),
            utc_last_update_timestamp: Some(1_700_000_000_900),
            commission: Some(-7),
            guaranteed_stop_loss: Some(true),
            used_margin: Some(2_500),
            money_digits: Some(3),
            trailing_stop_loss: Some(true),
            ..ProtoOaPosition::default()
        }
    }

    fn deal() -> ProtoOaDeal {
        ProtoOaDeal {
            deal_id: 3,
            order_id: 9,
            position_id: 5,
            volume: 250,
            filled_volume: 100,
            symbol_id: 7,
            create_timestamp: 1_700_000_000_000,
            execution_timestamp: 1_700_000_000_010,
            execution_price: Some(101.5),
            trade_side: 1,
            deal_status: 3,
            commission: Some(-12),
            close_position_detail: Some(ProtoOaClosePositionDetail {
                entry_price: 100.5,
                gross_profit: 1_000,
                swap: -10,
                commission: -24,
                balance: 1_000_966,
                closed_volume: Some(100),
                money_digits: None,
                ..ProtoOaClosePositionDetail::default()
            }),
            money_digits: Some(2),
            ..ProtoOaDeal::default()
        }
    }

    fn decimal(text: &str) -> Decimal {
        text.parse().expect("decimal")
    }

    #[test]
    fn texts_are_limited_in_characters() {
        let label = Label::new("é".repeat(MAX_LABEL_LENGTH)).expect("label");
        assert_eq!(label.as_str().chars().count(), MAX_LABEL_LENGTH);
        assert_eq!(Label::new("run-7").expect("label").to_string(), "run-7");
        assert_eq!(
            Label::new("x".repeat(MAX_LABEL_LENGTH + 1)),
            Err(ValueError::TooLong {
                kind: "label",
                length: 101,
                limit: 100,
            })
        );
        assert_eq!(
            Comment::new("y".repeat(MAX_COMMENT_LENGTH))
                .expect("comment")
                .as_str()
                .len(),
            MAX_COMMENT_LENGTH
        );
        assert_eq!(Comment::new("note").expect("comment").to_string(), "note");
        assert_eq!(
            Comment::new("y".repeat(MAX_COMMENT_LENGTH + 1)),
            Err(ValueError::TooLong {
                kind: "comment",
                length: 513,
                limit: 512,
            })
        );
    }

    #[test]
    fn rejections_of_an_order_read_as_sentences() {
        let one = Decimal::ONE;
        let cases = [
            (
                ValueError::TooLong {
                    kind: "label",
                    length: 101,
                    limit: 100,
                },
                "label has 101 characters, more than the 100 allowed",
            ),
            (
                ValueError::BelowMinimum {
                    kind: "volume",
                    value: Decimal::ZERO,
                    minimum: one,
                },
                "volume must be at least 1, got 0",
            ),
            (
                ValueError::AboveMaximum {
                    kind: "volume",
                    value: Decimal::TEN,
                    maximum: one,
                },
                "volume must be at most 1, got 10",
            ),
            (
                ValueError::OffStep {
                    kind: "volume",
                    value: decimal("1.5"),
                    step: one,
                },
                "volume must be a multiple of 1, got 1.5",
            ),
            (
                ValueError::TooFine {
                    kind: "price",
                    value: decimal("1.005"),
                    digits: 2,
                },
                "price must have at most 2 decimal places, got 1.005",
            ),
            (
                ValueError::Mismatch {
                    kind: "symbol of the order",
                },
                "symbol of the order does not match",
            ),
            (
                ValueError::Unsupported {
                    kind: "expiry of the order",
                },
                "expiry of the order is not supported here",
            ),
        ];
        for (error, text) in cases {
            assert_eq!(error.to_string(), text);
        }
    }

    #[test]
    fn enumerations_follow_the_wire_numbers() {
        assert_eq!(TradeSide::from_wire(1), Ok(TradeSide::Buy));
        assert_eq!(TradeSide::from_wire(2), Ok(TradeSide::Sell));
        assert_eq!(TradeSide::from_wire(3), Err(out_of_range("trade side")));
        assert_eq!(TradeSide::Buy.opposite(), TradeSide::Sell);
        assert_eq!(TradeSide::Sell.opposite(), TradeSide::Buy);
        assert_eq!(TradeSide::Buy.to_wire() as i32, 1);
        assert_eq!(TradeSide::Sell.to_wire() as i32, 2);
        let kinds = [
            OrderType::Market,
            OrderType::Limit,
            OrderType::Stop,
            OrderType::StopLossTakeProfit,
            OrderType::MarketRange,
            OrderType::StopLimit,
        ];
        for (raw, kind) in (1..).zip(kinds) {
            assert_eq!(OrderType::from_wire(raw), Ok(kind));
        }
        assert_eq!(OrderType::from_wire(0), Err(out_of_range("order type")));
        let statuses = [
            OrderStatus::Accepted,
            OrderStatus::Filled,
            OrderStatus::Rejected,
            OrderStatus::Expired,
            OrderStatus::Cancelled,
        ];
        for (raw, status) in (1..).zip(statuses) {
            assert_eq!(OrderStatus::from_wire(raw), Ok(status));
        }
        assert_eq!(OrderStatus::from_wire(6), Err(out_of_range("order status")));
        let positions = [
            PositionStatus::Open,
            PositionStatus::Closed,
            PositionStatus::Created,
            PositionStatus::Error,
        ];
        for (raw, status) in (1..).zip(positions) {
            assert_eq!(PositionStatus::from_wire(raw), Ok(status));
        }
        assert_eq!(
            PositionStatus::from_wire(5),
            Err(out_of_range("position status"))
        );
        let deals = [
            DealStatus::Filled,
            DealStatus::PartiallyFilled,
            DealStatus::Rejected,
            DealStatus::InternallyRejected,
            DealStatus::Error,
            DealStatus::Missed,
        ];
        for (raw, status) in (2..).zip(deals) {
            assert_eq!(DealStatus::from_wire(raw), Ok(status));
        }
        assert_eq!(DealStatus::from_wire(1), Err(out_of_range("deal status")));
        let executions = [
            ExecutionType::Accepted,
            ExecutionType::Filled,
            ExecutionType::Replaced,
            ExecutionType::Cancelled,
            ExecutionType::Expired,
            ExecutionType::Rejected,
            ExecutionType::CancelRejected,
            ExecutionType::Swap,
            ExecutionType::DepositWithdraw,
            ExecutionType::PartiallyFilled,
            ExecutionType::BonusDepositWithdraw,
        ];
        for (raw, kind) in (2..).zip(executions) {
            assert_eq!(ExecutionType::from_wire(raw), Ok(kind));
        }
        assert_eq!(
            ExecutionType::from_wire(13),
            Err(out_of_range("execution type"))
        );
    }

    #[test]
    fn time_in_force_takes_its_moment_from_the_expiry() {
        let expiry = Timestamp::from_millis(1_800_000_000_000).expect("timestamp");
        assert_eq!(
            TimeInForce::from_wire(Some(1), Some(1_800_000_000_000)),
            Ok(TimeInForce::GoodTillDate(expiry))
        );
        assert_eq!(
            TimeInForce::from_wire(Some(1), None),
            Err(ValueError::Missing {
                kind: "expiry of the order"
            })
        );
        assert_eq!(
            TimeInForce::from_wire(Some(1), Some(-1)),
            Err(out_of_range("timestamp"))
        );
        assert_eq!(
            TimeInForce::from_wire(Some(2), Some(5)),
            Ok(TimeInForce::GoodTillCancel)
        );
        assert_eq!(
            TimeInForce::from_wire(Some(3), None),
            Ok(TimeInForce::ImmediateOrCancel)
        );
        assert_eq!(
            TimeInForce::from_wire(None, None),
            Ok(TimeInForce::ImmediateOrCancel)
        );
        assert_eq!(
            TimeInForce::from_wire(Some(4), None),
            Ok(TimeInForce::FillOrKill)
        );
        assert_eq!(
            TimeInForce::from_wire(Some(5), None),
            Ok(TimeInForce::MarketOnOpen)
        );
        assert_eq!(
            TimeInForce::from_wire(Some(6), None),
            Err(out_of_range("time in force"))
        );
    }

    #[test]
    fn doubles_and_scaled_integers_become_exact_decimals() {
        assert_eq!(
            double_price(64_000.25).map(|price| price.to_string()),
            Ok("64000.25".to_owned())
        );
        assert_eq!(
            double_price(1.234_564_9).map(|price| price.to_string()),
            Ok("1.23456".to_owned())
        );
        assert_eq!(double_price(f64::NAN), Err(out_of_range("price")));
        assert_eq!(double_price(f64::INFINITY), Err(out_of_range("price")));
        assert!(matches!(
            double_price(-1.0),
            Err(ValueError::Negative { .. })
        ));
        assert_eq!(money(-12_345, Some(3)), Ok(decimal("-12.345")));
        assert_eq!(money(12_345, None), Ok(decimal("123.45")));
        assert_eq!(money(1, Some(40)), Err(out_of_range("amount of money")));
        assert_eq!(
            relative_price(Some(150_000)).map(|price| price.map(|price| price.to_string())),
            Ok(Some("1.50000".to_owned()))
        );
        assert_eq!(relative_price(None), Ok(None));
        assert_eq!(
            relative_price(Some(-1)),
            Err(out_of_range("distance of the protection"))
        );
    }

    #[test]
    fn order_keeps_every_field_of_the_wire() {
        let order = Order::try_from(order()).expect("order");
        assert_eq!(order.id.get(), 9);
        assert_eq!(order.symbol.get(), 7);
        assert_eq!(order.side, TradeSide::Sell);
        assert_eq!(order.volume.to_string(), "2.50");
        assert_eq!(order.kind, OrderType::StopLimit);
        assert_eq!(order.status, OrderStatus::Accepted);
        assert_eq!(
            order.time_in_force,
            TimeInForce::GoodTillDate(Timestamp::from_millis(1_800_000_000_000).expect("moment"))
        );
        let text = |price: Option<crate::common::decimals::Price>| {
            price.map(|price| price.value().normalize().to_string())
        };
        assert_eq!(text(order.limit_price), Some("100.12345".to_owned()));
        assert_eq!(text(order.stop_price), Some("99.5".to_owned()));
        assert_eq!(text(order.stop_loss), Some("90".to_owned()));
        assert_eq!(text(order.take_profit), Some("120.25".to_owned()));
        assert_eq!(text(order.relative_stop_loss), Some("1.5".to_owned()));
        assert_eq!(text(order.relative_take_profit), Some("3".to_owned()));
        assert_eq!(text(order.execution_price), Some("101.5".to_owned()));
        assert_eq!(order.slippage_points, Some(30));
        assert_eq!(
            order.executed_volume.map(|volume| volume.to_string()),
            Some("1.00".to_owned())
        );
        assert_eq!(order.position, None);
        assert_eq!(order.label.as_deref(), Some("run"));
        assert_eq!(order.comment.as_deref(), Some("note"));
        assert_eq!(order.client_order_id.as_deref(), Some("mine"));
        assert!(order.closing);
        assert!(order.trailing_stop_loss);
        assert_eq!(
            order.opened.map(Timestamp::as_millis),
            Some(1_700_000_000_000)
        );
        assert_eq!(
            order.updated.map(Timestamp::as_millis),
            Some(1_700_000_000_500)
        );
    }

    #[test]
    fn order_with_a_value_out_of_range_is_refused() {
        let broken = |change: fn(&mut ProtoOaOrder)| {
            let mut order = order();
            change(&mut order);
            Order::try_from(order).err()
        };
        assert!(matches!(
            broken(|order| order.order_id = 0),
            Some(ValueError::InvalidId { .. })
        ));
        assert!(matches!(
            broken(|order| order.trade_data.symbol_id = 0),
            Some(ValueError::InvalidId { .. })
        ));
        assert_eq!(
            broken(|order| order.trade_data.trade_side = 0),
            Some(out_of_range("trade side"))
        );
        assert!(broken(|order| order.trade_data.volume = -1).is_some());
        assert_eq!(
            broken(|order| order.order_type = 0),
            Some(out_of_range("order type"))
        );
        assert_eq!(
            broken(|order| order.order_status = 0),
            Some(out_of_range("order status"))
        );
        assert_eq!(
            broken(|order| order.time_in_force = Some(0)),
            Some(out_of_range("time in force"))
        );
        assert_eq!(
            broken(|order| order.limit_price = Some(f64::NAN)),
            Some(out_of_range("price"))
        );
        assert_eq!(
            broken(|order| order.slippage_in_points = Some(-1)),
            Some(out_of_range("slippage in points"))
        );
        assert!(matches!(
            broken(|order| order.position_id = Some(-4)),
            Some(ValueError::InvalidId { .. })
        ));
        assert_eq!(
            broken(|order| order.utc_last_update_timestamp = Some(-1)),
            Some(out_of_range("timestamp"))
        );
    }

    #[test]
    fn position_scales_its_money_by_its_own_digits() {
        let position = Position::try_from(position()).expect("position");
        assert_eq!(position.id.get(), 5);
        assert_eq!(position.symbol.get(), 7);
        assert_eq!(position.side, TradeSide::Sell);
        assert_eq!(position.volume.to_string(), "2.50");
        assert_eq!(position.status, PositionStatus::Open);
        assert_eq!(
            position.price.map(|price| price.value().normalize()),
            Some(decimal("100.5"))
        );
        assert_eq!(
            position.stop_loss.map(|price| price.value().normalize()),
            Some(decimal("90"))
        );
        assert_eq!(
            position.take_profit.map(|price| price.value().normalize()),
            Some(decimal("120"))
        );
        assert_eq!(position.swap, decimal("-1.234"));
        assert_eq!(position.commission, Some(decimal("-0.007")));
        assert_eq!(position.used_margin, Some(decimal("2.500")));
        assert_eq!(position.label.as_deref(), Some("run"));
        assert_eq!(position.comment.as_deref(), Some("note"));
        assert!(position.guaranteed_stop_loss);
        assert!(position.trailing_stop_loss);
        assert_eq!(
            position.opened.map(Timestamp::as_millis),
            Some(1_700_000_000_000)
        );
        assert_eq!(
            position.updated.map(Timestamp::as_millis),
            Some(1_700_000_000_900)
        );
        let mut huge = self::position();
        huge.used_margin = Some(u64::MAX);
        assert_eq!(
            Position::try_from(huge),
            Err(out_of_range("amount of money"))
        );
        let mut unknown = self::position();
        unknown.position_status = 9;
        assert_eq!(
            Position::try_from(unknown),
            Err(out_of_range("position status"))
        );
    }

    #[test]
    fn deal_carries_what_closing_did_to_the_account() {
        let deal = Deal::try_from(deal()).expect("deal");
        assert_eq!(deal.id.get(), 3);
        assert_eq!(deal.order.get(), 9);
        assert_eq!(deal.position.get(), 5);
        assert_eq!(deal.symbol.get(), 7);
        assert_eq!(deal.side, TradeSide::Buy);
        assert_eq!(deal.volume.to_string(), "2.50");
        assert_eq!(deal.filled_volume.to_string(), "1.00");
        assert_eq!(deal.status, DealStatus::PartiallyFilled);
        assert_eq!(deal.created.as_millis(), 1_700_000_000_000);
        assert_eq!(deal.executed.as_millis(), 1_700_000_000_010);
        assert_eq!(
            deal.execution_price.map(|price| price.value().normalize()),
            Some(decimal("101.5"))
        );
        assert_eq!(deal.commission, Some(decimal("-0.12")));
        let closing: ClosingDetail = deal.closing.expect("closing detail");
        assert_eq!(closing.entry_price.value().normalize(), decimal("100.5"));
        assert_eq!(closing.gross_profit, decimal("10.00"));
        assert_eq!(closing.swap, decimal("-0.10"));
        assert_eq!(closing.commission, decimal("-0.24"));
        assert_eq!(closing.balance, decimal("10009.66"));
        assert_eq!(
            closing.closed_volume.map(|volume| volume.to_string()),
            Some("1.00".to_owned())
        );
        let mut unknown = self::deal();
        unknown.deal_status = 1;
        assert_eq!(Deal::try_from(unknown), Err(out_of_range("deal status")));
    }

    #[test]
    fn first_answer_to_a_trade_is_an_execution_or_a_typed_refusal() {
        let event = ProtoOaExecutionEvent {
            ctid_trader_account_id: 101,
            execution_type: 2,
            order: Some(order()),
            position: Some(position()),
            deal: Some(deal()),
            is_server_event: Some(true),
            ..ProtoOaExecutionEvent::default()
        };
        let execution = traded(&event.to_message(None)).expect("execution");
        assert_eq!(execution.kind, ExecutionType::Accepted);
        assert!(execution.server_event);
        assert!(execution.order.is_some() && execution.position.is_some());
        assert!(execution.deal.is_some());
        assert_eq!(
            Execution::try_from(ProtoOaExecutionEvent {
                ctid_trader_account_id: 0,
                ..event.clone()
            })
            .err()
            .map(|error| error.to_string()),
            Some("account id must be a positive integer, got 0".to_owned())
        );
        let rejected = ProtoOaExecutionEvent {
            execution_type: 7,
            error_code: Some("MARKET_CLOSED".to_owned()),
            ..event
        };
        match traded(&rejected.to_message(None)) {
            Err(ConnectorError::Server(error)) => {
                assert_eq!(error.code, ErrorCode::MarketClosed);
                assert_eq!(error.description.as_deref(), Some("the order was refused"));
                assert_eq!(
                    error.account_id.map(crate::common::ids::AccountId::get),
                    Some(101)
                );
            }
            other => panic!("unexpected outcome: {other:?}"),
        }
        let error = ProtoOaOrderErrorEvent {
            payload_type: None,
            ctid_trader_account_id: 101,
            error_code: "ORDER_NOT_FOUND".to_owned(),
            order_id: Some(9),
            position_id: None,
            description: Some("no such order".to_owned()),
        };
        match traded(&error.to_message(None)) {
            Err(ConnectorError::Server(error)) => {
                assert_eq!(error.code, ErrorCode::OrderNotFound);
                assert_eq!(error.description.as_deref(), Some("no such order"));
            }
            other => panic!("unexpected outcome: {other:?}"),
        }
    }
}