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
use chrono::NaiveDateTime;
use serde::Deserialize;
use std::{collections::HashMap, future::Future, pin::Pin, str::FromStr, sync::Arc};

use async_trait::async_trait;
use num_enum::{IntoPrimitive, TryFromPrimitive};

use crate::messages::ResponseMessage;

pub const DELIMITER: &str = "\u{1}";

#[async_trait]
pub trait ConnectionHandler {
    async fn on_connect(&self);
    async fn on_logon(&self);
    async fn on_disconnect(&self);
}

#[async_trait]
pub trait MarketDataHandler {
    async fn on_price_of(&self, symbol_id: u32, price: SpotPrice);
    async fn on_market_depth_full_refresh(
        &self,
        symbol_id: u32,
        full_depth: HashMap<String, DepthPrice>,
    );
    async fn on_market_depth_incremental_refresh(&self, refresh: Vec<IncrementalRefresh>);

    async fn on_accpeted_spot_subscription(&self, symbol_id: u32);
    async fn on_accpeted_depth_subscription(&self, symbol_id: u32);

    async fn on_rejected_spot_subscription(&self, symbol_id: u32, err_msg: String);
    async fn on_rejected_depth_subscription(&self, symbol_id: u32, err_msg: String);
}

// == Trade type definitions
#[derive(Debug)]
pub struct SymbolInformation {
    pub id: u32,
    pub name: String,
    pub digits: u32,
}

#[derive(Debug)]
pub struct PositionReport {
    pub symbol_id: u32,
    pub position_id: String,
    pub long_qty: f64,
    pub short_qty: f64,
    pub settle_price: f64,
    pub absolute_tp: Option<f64>,
    pub absolute_sl: Option<f64>,
    pub trailing_sl: Option<bool>,
    pub trigger_method_sl: Option<u32>,
    pub guaranteed_sl: Option<bool>,
}

#[derive(Debug)]
pub struct NewOrderReport {
    pub symbol: u32,
    pub order_qty: f64,
    pub order_status: OrderStatus,
    pub order_type: OrderType,
    pub side: Side,
    pub time_in_force: String,
    pub transact_time: NaiveDateTime,
    pub leaves_qty: f64,
    pub pos_main_rept_id: String,
}

#[derive(Debug)]
pub struct OrderStatusReport {
    pub symbol: u32,
    pub order_id: String,
    pub cum_qty: f64,
    pub order_qty: f64,
    pub leaves_qty: f64,
    pub order_status: OrderStatus,
    pub order_type: OrderType,
    pub price: f64,
    pub side: Side,
    pub time_in_force: String,
    pub transact_time: NaiveDateTime,
    pub pos_main_rept_id: String,
}

#[derive(Debug)]
pub enum OrderStatus {
    New,
    ParitallyFilled,
    Filled,
    Rejected,
    Cancelled,
    Expired,
}

#[derive(Debug, PartialEq, Eq)]
pub struct ParseError(String);

impl FromStr for OrderStatus {
    type Err = ParseError;
    fn from_str(s: &str) -> Result<OrderStatus, Self::Err> {
        match s {
            "0" => Ok(Self::New),
            "1" => Ok(Self::ParitallyFilled),
            "2" => Ok(Self::Filled),
            "8" => Ok(Self::Rejected),
            "4" => Ok(Self::Cancelled),
            "C" => Ok(Self::Expired),
            _ => Err(ParseError(s.into())),
        }
    }
}

// #[derive(Debug)]
// pub enum ExeuctionReport {
//     /// ExecType = 'I'
//     OrderStatus {},
//
//     // not implemented
//     New(ResponseMessage),
//     Canceled(ResponseMessage),
//     Replace(ResponseMessage),
//     Rejected(ResponseMessage),
//     Expired(ResponseMessage),
//     Trade(ResponseMessage),
// }
//
// #[derive(Debug)]
// pub struct ExecutionReport {
//     order_id: String,
//     cl_ord_id: Option<String>,
//     exec_type: char,    //
//     order_status: char, //
//     symbol: u32,
//     side: Side,
// }

// == Market type definition

#[derive(Debug)]
pub enum MarketType {
    Spot,
    Depth,
}

impl std::fmt::Display for MarketType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            Self::Spot => "Spot",
            Self::Depth => "Depth",
        };
        f.write_str(s)
    }
}

#[derive(Debug, Clone)]
pub enum PriceType {
    Bid,
    Ask,
}

impl FromStr for PriceType {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "0" => Ok(Self::Bid),
            "1" => Ok(Self::Ask),
            _ => Err(()),
        }
    }
}

#[derive(Debug, Clone)]
pub struct SpotPrice {
    pub bid: f64,
    pub ask: f64,
}

#[derive(Debug, Clone)]
pub struct DepthPrice {
    pub price_type: PriceType,
    pub price: f64,
    pub size: f64,
}

#[derive(Debug, Clone)]
pub enum IncrementalRefresh {
    New {
        symbol_id: u32,
        entry_id: String,
        data: DepthPrice,
    },
    Delete {
        symbol_id: u32,
        entry_id: String,
    },
}

#[derive(thiserror::Error, Debug)]
pub enum Error {
    // connection errors
    #[error("No connection")]
    NotConnected,
    #[error("logged out")]
    LoggedOut,

    #[error("Field not found : {0}")]
    FieldNotFoundError(Field),

    #[error("Request failed")]
    RequestFailed,
    #[error("Order Rejected : {0}")]
    OrderRejected(String),

    // subscription errors for market client
    #[error("Failed to {2} subscription {0}: {1}")]
    SubscriptionError(u32, String, MarketType),
    #[error("Already subscribed {1} for symbol({0})")]
    SubscribedAlready(u32, MarketType),
    #[error("Waiting then response of {1} subscription for symbol({0})")]
    RequestingSubscription(u32, MarketType),
    #[error("Not susbscribed {1} for symbol({0})")]
    NotSubscribed(u32, MarketType),

    // internal errors
    #[error("Request rejected - {0}")]
    RequestRejected(String),
    #[error("Failed to find the response")]
    NoResponse,
    #[error("Unknown errro")]
    UnknownError,

    // reponse send error
    #[error(transparent)]
    SendError(#[from] async_std::channel::SendError<ResponseMessage>),
    #[error(transparent)]
    TriggerError(#[from] async_std::channel::SendError<String>),
    #[error(transparent)]
    RecvError(#[from] async_std::channel::RecvError),
    #[error(transparent)]
    Io(#[from] std::io::Error),
}

//
// only for internal
pub type MarketCallback = Arc<dyn Fn(InternalMDResult) -> () + Send + Sync>;
//

pub enum InternalMDResult {
    MD {
        msg_type: char,
        symbol_id: u32,
        data: Vec<HashMap<Field, String>>,
    },
    MDReject {
        symbol_id: u32,
        md_req_id: String,
        err_msg: String,
    },
}

#[derive(Debug, Deserialize, Clone)]
pub struct Config {
    pub host: String,
    pub username: String,
    pub password: String,
    pub sender_comp_id: String,
    pub heart_beat: u32,
}

impl Config {
    pub fn new(
        host: String,
        username: String,
        password: String,
        sender_comp_id: String,
        heart_beat: u32,
    ) -> Self {
        Self {
            host,
            username,
            password,
            sender_comp_id,
            heart_beat,
        }
    }
}
#[repr(u32)]
#[derive(Debug, PartialEq, TryFromPrimitive, IntoPrimitive, Clone, Eq, Hash, Copy)]
pub enum Field {
    AvgPx = 6,
    BeginSeqNo = 7,
    BeginString = 8,
    BodyLength = 9,
    CheckSum = 10,
    ClOrdId = 11,
    CumQty = 14,
    EndSeqNo = 16,
    OrdQty = 32,
    MsgSeqNum = 34,
    MsgType = 35,
    NewSeqNo = 36,
    OrderID = 37,
    OrderQty = 38,
    OrdStatus = 39,
    OrdType = 40,
    OrigClOrdID = 41,
    Price = 44,
    RefSeqNum = 45,
    SenderCompID = 49,
    SenderSubID = 50,
    SendingTime = 52,
    Side = 54,
    Symbol = 55,
    TargetCompID = 56,
    TargetSubID = 57,
    Text = 58,
    TimeInForce = 59,
    TransactTime = 60,
    EncryptMethod = 98,
    StopPx = 99,
    OrdRejReason = 103,
    HeartBtInt = 108,
    TestReqID = 112,
    GapFillFlag = 123,
    ExpireTime = 126,
    ResetSeqNumFlag = 141,
    NoRelatedSym = 146,
    ExecType = 150,
    LeavesQty = 151,
    IssueDate = 225,
    MDReqID = 262,
    SubscriptionRequestType = 263,
    MarketDepth = 264,
    MDUpdateType = 265,
    NoMDEntryTypes = 267,
    NoMDEntries = 268,
    MDEntryType = 269,
    MDEntryPx = 270,
    MDEntrySize = 271,
    MDEntryID = 278,
    MDUpdateAction = 279,
    SecurityReqID = 320,
    SecurityResponseID = 322,
    EncodedTextLen = 354,
    EncodedText = 355,
    RefTagID = 371,
    RefMsgType = 372,
    SessionRejectReason = 373,
    BusinessRejectRefID = 379,
    BusinessRejectReason = 380,
    CxlRejResponseTo = 434,
    Designation = 494,
    Username = 553,
    Password = 554,
    SecurityListRequestType = 559,
    SecurityRequestResult = 560,
    MassStatusReqID = 584,
    MassStatusReqType = 585,
    NoPositions = 702,
    LongQty = 704,
    ShortQty = 705,
    PosReqID = 710,
    PosMaintRptID = 721,
    TotalNumPosReports = 727,
    PosReqResult = 728,
    SettlPrice = 730,
    TotNumReports = 911,
    AbsoluteTP = 1000,
    RelativeTP = 1001,
    AbsoluteSL = 1002,
    RelativeSL = 1003,
    TrailingSL = 1004,
    TriggerMethodSL = 1005,
    GuaranteedSL = 1006,
    SymbolName = 1007,
    SymbolDigits = 1008,
}
impl std::fmt::Display for Field {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&format!("{:?}", self))
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Copy)]
pub enum SubID {
    QUOTE,
    TRADE,
}

impl std::fmt::Display for SubID {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            SubID::QUOTE => "QUOTE",
            SubID::TRADE => "TRADE",
        };
        f.write_str(s)
    }
}

impl FromStr for SubID {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "QUOTE" => Ok(SubID::QUOTE),
            "TRADE" => Ok(SubID::TRADE),
            _ => Err(()),
        }
    }
}

#[repr(u32)]
#[derive(Debug, PartialEq, TryFromPrimitive, Clone, Copy)]
pub enum Side {
    BUY = 1,
    SELL = 2,
}

impl Default for Side {
    fn default() -> Self {
        Side::BUY
    }
}

#[repr(u32)]
#[derive(Debug, PartialEq, TryFromPrimitive, Clone, Copy)]
pub enum OrderType {
    MARKET = 1,
    LIMIT = 2,
    STOP = 3,
    STOP_LIMIT = 4,
}

impl FromStr for OrderType {
    type Err = ParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "1" => Ok(Self::MARKET),
            "2" => Ok(Self::LIMIT),
            "3" => Ok(Self::STOP),
            "4" => Ok(Self::STOP_LIMIT),
            _ => Err(ParseError(s.into())),
        }
    }
}

impl Default for OrderType {
    fn default() -> Self {
        OrderType::MARKET
    }
}