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
use chrono::NaiveDateTime;
use uuid::Uuid;

use crate::{
    fixapi::FixApi,
    messages::{
        NewOrderSingleReq, OrderMassStatusReq, PositionsReq, ResponseMessage, SecurityListReq,
    },
    parse_func,
    types::{
        ConnectionHandler, Error, ExeuctionReport, Field, OrderType, PositionReport, Side,
        SymbolInformation, DELIMITER,
    },
};
use std::{collections::HashMap, sync::Arc};

pub struct TradeClient {
    internal: FixApi,
}
impl TradeClient {
    pub fn new(
        host: String,
        login: String,
        password: String,
        sender_comp_id: String,
        heartbeat_interval: Option<u32>,
    ) -> Self {
        Self {
            internal: FixApi::new(
                crate::types::SubID::TRADE,
                host,
                login,
                password,
                sender_comp_id,
                heartbeat_interval,
            ),
        }
    }

    pub fn register_connection_handler<T: ConnectionHandler + Send + Sync + 'static>(
        &mut self,
        handler: T,
    ) {
        self.internal.register_connection_handler(handler);
    }

    pub fn register_connection_handler_arc<T: ConnectionHandler + Send + Sync + 'static>(
        &mut self,
        handler: Arc<T>,
    ) {
        self.internal.register_connection_handler_arc(handler);
    }

    pub async fn connect(&mut self) -> Result<(), Error> {
        self.internal.connect().await?;
        self.internal.logon().await
    }

    pub async fn disconnect(&mut self) -> Result<(), Error> {
        self.internal.disconnect().await
    }

    pub fn is_connected(&self) -> bool {
        self.internal.is_connected()
    }

    async fn fetch_response(
        &self,
        arg: Vec<(&str, Field, String)>,
    ) -> Result<Vec<ResponseMessage>, Error> {
        let arg = arg.into_iter().map(|v| (v.0, v)).collect::<HashMap<_, _>>();
        while let Ok(msg_type) = self.internal.wait_notifier().await {
            let has_key = arg.contains_key(&msg_type.as_str());
            if has_key {
                match self.internal.check_responses(arg.clone()).await {
                    Ok(res) => {
                        log::debug!("in fetch response - {:?}", res);
                        return Ok(res);
                    }
                    Err(Error::NoResponse) => {
                        // log::debug!("no reponse {:?}", msg_type);
                        if let Err(err) = self.internal.trigger.send(msg_type).await {
                            return Err(Error::TriggerError(err));
                        }
                    }
                    Err(err) => {
                        log::debug!("err in fetch response for {} - {:?}", msg_type, err);
                        return Err(err);
                    }
                }
            } else {
                if let Err(err) = self.internal.trigger.send(msg_type).await {
                    return Err(Error::TriggerError(err));
                }
            }
        }
        Err(Error::UnknownError)
    }

    fn create_unique_id(&self) -> String {
        Uuid::new_v4().to_string()
    }

    /// Fetch the security list from the server.
    ///
    ///
    /// This is asn asynchronous method that sends a request to the server and waits for the
    /// response. It returns a result containing the data if the request succesful, or an error if
    /// it fails.
    pub async fn fetch_security_list(&self) -> Result<Vec<SymbolInformation>, Error> {
        let security_req_id = self.create_unique_id();
        let req = SecurityListReq::new(security_req_id.clone(), 0, None);
        self.internal.send_message(req).await?;
        match self
            .fetch_response(vec![("y", Field::SecurityReqID, security_req_id)])
            .await
        {
            Ok(res) => {
                let res = res.first().unwrap();
                parse_func::parse_security_list(res)
            }
            Err(err) => Err(err),
        }
    }

    pub async fn fetch_positions(&self) -> Result<Vec<PositionReport>, Error> {
        let pos_req_id = self.create_unique_id();
        let req = PositionsReq::new(pos_req_id.clone(), None);
        self.internal.send_message(req).await?;

        match self
            .fetch_response(vec![("AP", Field::PosReqID, pos_req_id)])
            .await
        {
            Ok(res) => {
                let res = res.first().unwrap();
                parse_func::parse_positions(res)
            }
            Err(err) => Err(err),
        }
    }

    pub async fn fetch_all_order_status(
        &self,
        issue_data: Option<NaiveDateTime>,
    ) -> Result<Vec<ExeuctionReport>, Error> {
        let mass_status_req_id = self.create_unique_id();
        // FIXME if mass_status_req_id is not 7, then return 'j' but response does not include the mass_status_req_id
        let req = OrderMassStatusReq::new(mass_status_req_id.clone(), 7, issue_data);
        self.internal.send_message(req).await?;

        match self
            .fetch_response(vec![
                ("8", Field::MassStatusReqID, mass_status_req_id.clone()),
                ("j", Field::BusinessRejectRefID, mass_status_req_id.clone()),
            ])
            .await
        {
            Ok(res) => {
                if let Some(_) = res
                    .iter()
                    .filter(|r| r.get_field_value(Field::MsgType).unwrap() == "j")
                    .next()
                {
                    // not error: order not found
                    return Ok(Vec::new());
                    // let reason = rej
                    //     .get_field_value(Field::Text)
                    //     .unwrap_or("Rejected".into());
                    // return Err(Error::RequestRejected(reason));
                }

                // FIXME unnecessary line
                if let Some(res) = res
                    .into_iter()
                    .filter(|r| r.get_field_value(Field::MsgType).unwrap() == "8")
                    .next()
                {
                    return parse_func::parse_order_mass_status(res);
                }

                // let res = res.first().unwrap();
                // parse_positions(res)
                //
                Err(Error::UnknownError)
            }
            Err(err) => Err(err),
        }
        // let res = self.fetch_response(seq_num).await?;
        // parse_order_mass(res)
    }

    async fn new_order(&self, req: NewOrderSingleReq) -> Result<ExeuctionReport, Error> {
        let cl_ord_id = req.cl_ord_id.clone();

        self.internal.send_message(req).await?;
        match self
            .fetch_response(vec![
                ("8", Field::ClOrdId, cl_ord_id.clone()),
                ("j", Field::BusinessRejectRefID, cl_ord_id.clone()),
            ])
            .await
        {
            Ok(res) => {
                if let Some(rej) = res
                    .iter()
                    .filter(|r| r.get_field_value(Field::MsgType).unwrap() == "j")
                    .next()
                {
                    // Order Rejected
                    return Err(Error::OrderRejected(
                        rej.get_field_value(Field::Text).unwrap_or("Unknown".into()),
                    ));
                }

                if let Some(res) = res
                    .into_iter()
                    .filter(|r| r.get_field_value(Field::MsgType).unwrap() == "8")
                    .next()
                {
                    return parse_func::parse_execution_report(res);
                }
                //
                Err(Error::UnknownError)
            }
            Err(err) => Err(err),
        }
    }

    pub async fn new_market_order(
        &self,
        symbol: u32,
        side: Side,
        order_qty: f64,
        cl_ord_id: Option<String>,
        pos_id: Option<String>,
        transact_time: Option<NaiveDateTime>,
        custom_ord_label: Option<String>,
    ) -> Result<ExeuctionReport, Error> {
        let req = NewOrderSingleReq::new(
            cl_ord_id.unwrap_or(self.create_unique_id()),
            symbol,
            side,
            transact_time,
            order_qty,
            OrderType::MARKET,
            None,
            None,
            None,
            pos_id,
            custom_ord_label,
        );
        self.new_order(req).await
    }

    pub async fn new_limit_order(
        &self,
        symbol: u32,
        side: Side,
        price: f64,
        order_qty: f64,
        cl_ord_id: Option<String>,
        pos_id: Option<String>,
        expire_time: Option<NaiveDateTime>,
        transact_time: Option<NaiveDateTime>,
        custom_ord_label: Option<String>,
    ) -> Result<ExeuctionReport, Error> {
        let req = NewOrderSingleReq::new(
            cl_ord_id.unwrap_or(self.create_unique_id()),
            symbol,
            side,
            transact_time,
            order_qty,
            OrderType::LIMIT,
            Some(price),
            None,
            expire_time,
            pos_id,
            custom_ord_label,
        );

        self.new_order(req).await
    }

    pub async fn new_stop_order(
        &self,
        symbol: u32,
        side: Side,
        stop_px: f64,
        order_qty: f64,
        cl_ord_id: Option<String>,
        pos_id: Option<String>,
        expire_time: Option<NaiveDateTime>,
        transact_time: Option<NaiveDateTime>,
        custom_ord_label: Option<String>,
    ) -> Result<ExeuctionReport, Error> {
        let req = NewOrderSingleReq::new(
            cl_ord_id.unwrap_or(self.create_unique_id()),
            symbol,
            side,
            transact_time,
            order_qty,
            OrderType::STOP,
            None,
            Some(stop_px),
            expire_time,
            pos_id,
            custom_ord_label,
        );

        self.new_order(req).await
    }

    pub async fn replace_order(&self) -> Result<(), Error> {
        unimplemented!()
    }

    pub async fn close_position(&self) -> Result<(), Error> {
        unimplemented!()
    }

    pub async fn close_all_position(&self) -> Result<(), Error> {
        unimplemented!()
    }

    pub async fn cancel_order(&self) -> Result<(), Error> {
        unimplemented!()
    }

    pub async fn cancel_all_position(&self) -> Result<(), Error> {
        unimplemented!()
    }
}