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
use crate::errors::XTPError;
use crate::sys::{
    CreateTraderApi, TraderApi_CancelOrder, TraderApi_FundTransfer, TraderApi_GetAccountByXTPID,
    TraderApi_GetApiLastError, TraderApi_GetApiVersion, TraderApi_GetClientIDByXTPID,
    TraderApi_GetTradingDay, TraderApi_InsertOrder, TraderApi_IsServerRestart, TraderApi_Login,
    TraderApi_Logout, TraderApi_QueryAsset, TraderApi_QueryETF, TraderApi_QueryETFTickerBasket,
    TraderApi_QueryFundTransfer, TraderApi_QueryIPOInfoList, TraderApi_QueryIPOQuotaInfo,
    TraderApi_QueryOptionAuctionInfo, TraderApi_QueryOrderByXTPID, TraderApi_QueryOrders,
    TraderApi_QueryOrdersByPage, TraderApi_QueryPosition, TraderApi_QueryStructuredFund,
    TraderApi_QueryTrades, TraderApi_QueryTradesByPage, TraderApi_QueryTradesByXTPID,
    TraderApi_RegisterSpi, TraderApi_Release, TraderApi_SetHeartBeatInterval,
    TraderApi_SetSoftwareKey, TraderApi_SetSoftwareVersion, TraderApi_SubscribePublicTopic,
    TraderSpiStub, TraderSpiStub_Destructor, XTP_API_TraderApi, XTP_API_TraderSpi, XTP_LOG_LEVEL,
};
use crate::trader_spi::TraderSpi;
use crate::types;
use crate::types::FromRaw;
use failure::Fallible;
use libc::c_void;
use std::ffi::{CStr, CString};
use std::mem::transmute;
use std::net::SocketAddrV4;

pub struct TraderApi {
    trader_api: *mut XTP_API_TraderApi,
    trader_spi_stub: Option<*mut TraderSpiStub>, // Free the stub after we freed XTP_API_QuoteApi in drop()
}

impl TraderApi {
    pub fn new(id: u8, path: &str, log_level: types::XTPLogLevel) -> TraderApi {
        let cpath = CString::new(path);
        let trader_api = unsafe {
            CreateTraderApi(
                id,
                cpath.unwrap().as_c_str().as_ptr(),
                transmute::<_, XTP_LOG_LEVEL>(log_level),
            )
        };

        TraderApi {
            trader_api,
            trader_spi_stub: None,
        }
    }

    fn translate_code(&mut self, code: i64, zero_ok: bool) -> Fallible<i64> {
        if (code == 0) == zero_ok {
            return Ok(code);
        }

        let underlying_error = self.get_api_last_error();
        Err(XTPError::XTPClientError {
            error_id: underlying_error.error_id as i64,
            error_msg: underlying_error.error_msg,
        }
        .into())
    }
}

impl TraderApi {
    fn release(&mut self) {
        unsafe { TraderApi_Release(self.trader_api) };
    }

    pub fn get_trading_day(&mut self) -> &str {
        let ptr = unsafe { TraderApi_GetTradingDay(self.trader_api) }; // The string is freed by them
        unsafe { CStr::from_ptr(ptr) }.to_str().unwrap()
    }

    pub fn register_spi<T: TraderSpi>(&mut self, spi: T) {
        let trait_object_box: Box<Box<dyn TraderSpi>> = Box::new(Box::new(spi));
        let trait_object_pointer =
            Box::into_raw(trait_object_box) as *mut Box<dyn TraderSpi> as *mut c_void;

        let quote_spi_stub = unsafe { TraderSpiStub::new(trait_object_pointer) };

        let ptr = Box::into_raw(Box::new(quote_spi_stub));
        self.trader_spi_stub = Some(ptr);
        unsafe { TraderApi_RegisterSpi(self.trader_api, ptr as *mut XTP_API_TraderSpi) };
    }

    pub fn get_api_last_error(&mut self) -> types::XTPRspInfoStruct {
        unsafe { types::XTPRspInfoStruct::from_raw(&*TraderApi_GetApiLastError(self.trader_api)) }
    }

    pub fn get_api_version(&mut self) -> &CStr {
        let ptr = unsafe { TraderApi_GetApiVersion(self.trader_api) }; // The string is freed by them
        unsafe { CStr::from_ptr(ptr) }
    }

    pub fn get_client_id_by_xtpid(&mut self, order_xtp_id: u64) -> u8 {
        unsafe { TraderApi_GetClientIDByXTPID(self.trader_api, order_xtp_id) }
    }

    pub fn get_account_by_xtpid(&mut self, order_xtp_id: u64) -> &CStr {
        let ptr = unsafe { TraderApi_GetAccountByXTPID(self.trader_api, order_xtp_id) };
        unsafe { CStr::from_ptr(ptr) }
    }

    pub fn subscribe_public_topic(&mut self, resume_type: types::XTPTeResumeType) {
        unsafe { TraderApi_SubscribePublicTopic(self.trader_api, resume_type.into()) };
    }

    pub fn set_software_version(&mut self, version: &str) -> Fallible<()> {
        let version = CString::new(version)?;
        unsafe { TraderApi_SetSoftwareVersion(self.trader_api, version.as_ptr()) };
        Ok(())
    }

    pub fn set_software_key(&mut self, key: &str) -> Fallible<()> {
        let key = CString::new(key)?;
        unsafe { TraderApi_SetSoftwareKey(self.trader_api, key.as_ptr()) };
        Ok(())
    }

    pub fn set_heart_beat_interval(&mut self, interval: u32) {
        unsafe { TraderApi_SetHeartBeatInterval(self.trader_api, interval) }
    }

    pub fn login(
        &mut self,
        server_addr: SocketAddrV4,
        username: &str,
        password: &str,
        sock_type: types::XTPProtocolType,
    ) -> Fallible<i64> {
        {
            let ip = CString::new(format!("{}", server_addr.ip()))?;
            let username = CString::new(username)?;
            let password = CString::new(password)?;
            let ret_code = unsafe {
                TraderApi_Login(
                    self.trader_api,
                    ip.as_ptr(),
                    server_addr.port() as i32,
                    username.as_ptr(),
                    password.as_ptr(),
                    sock_type.into(),
                )
            };
            self.translate_code(ret_code as i64, false)
        }
    }

    pub fn logout(&mut self, session_id: u64) -> Fallible<i64> {
        let retc = unsafe { TraderApi_Logout(self.trader_api, session_id) };
        self.translate_code(retc as i64, true)
    }

    pub fn is_server_restart(&mut self, session_id: u64) -> bool {
        unsafe { TraderApi_IsServerRestart(self.trader_api, session_id) }
    }

    pub fn insert_order(
        &mut self,
        order: &types::XTPOrderInsertInfo,
        session_id: u64,
    ) -> Fallible<i64> {
        let mut order = order.into();
        let retc =
            unsafe { TraderApi_InsertOrder(self.trader_api, &mut order as *mut _, session_id) };
        self.translate_code(retc as i64, false)
    }

    pub fn cancel_order(&mut self, order_xtp_id: u64, session_id: u64) -> Fallible<i64> {
        let retc = unsafe { TraderApi_CancelOrder(self.trader_api, order_xtp_id, session_id) };
        self.translate_code(retc as i64, false)
    }

    pub fn query_order_by_xtpid(
        &mut self,
        order_xtp_id: u64,
        session_id: u64,
        request_id: i32,
    ) -> Fallible<i64> {
        let retc = unsafe {
            TraderApi_QueryOrderByXTPID(self.trader_api, order_xtp_id, session_id, request_id)
        };
        self.translate_code(retc as i64, true)
    }

    pub fn query_orders(
        &mut self,
        query_param: &types::XTPQueryOrderReq,
        session_id: u64,
        request_id: i32,
    ) -> Fallible<i64> {
        let mut query_param = query_param.into();

        let retc = unsafe {
            TraderApi_QueryOrders(
                self.trader_api,
                &mut query_param as *mut _,
                session_id,
                request_id,
            )
        };
        self.translate_code(retc as i64, true)
    }

    pub fn query_orders_by_page(
        &mut self,
        query_param: &types::XTPQueryOrderByPageReq,
        session_id: u64,
        request_id: i32,
    ) -> Fallible<i64> {
        let mut query_param = query_param.into();

        let retc = unsafe {
            TraderApi_QueryOrdersByPage(
                self.trader_api,
                &mut query_param as *mut _,
                session_id,
                request_id,
            )
        };
        self.translate_code(retc as i64, true)
    }

    pub fn query_trades_by_xtpid(
        &mut self,
        order_xtp_id: u64,
        session_id: u64,
        request_id: i32,
    ) -> Fallible<i64> {
        let retc = unsafe {
            TraderApi_QueryTradesByXTPID(self.trader_api, order_xtp_id, session_id, request_id)
        };
        self.translate_code(retc as i64, true)
    }

    pub fn query_trades(
        &mut self,
        query_param: &types::XTPQueryTraderReq,
        session_id: u64,
        request_id: i32,
    ) -> Fallible<i64> {
        let retc = unsafe {
            TraderApi_QueryTrades(
                self.trader_api,
                &mut query_param.into() as *mut _,
                session_id,
                request_id,
            )
        };
        self.translate_code(retc as i64, true)
    }

    pub fn query_trades_by_page(
        &mut self,
        query_param: &types::XTPQueryTraderByPageReq,
        session_id: u64,
        request_id: i32,
    ) -> Fallible<i64> {
        let retc = unsafe {
            TraderApi_QueryTradesByPage(
                self.trader_api,
                &mut query_param.into() as *mut _,
                session_id,
                request_id,
            )
        };

        self.translate_code(retc as i64, true)
    }

    pub fn query_position(
        &mut self,
        ticker: &str,
        session_id: u64,
        request_id: i32,
    ) -> Fallible<i64> {
        let s = CString::new(ticker).unwrap();

        let retc =
            unsafe { TraderApi_QueryPosition(self.trader_api, s.as_ptr(), session_id, request_id) };
        self.translate_code(retc as i64, true)
    }

    pub fn query_asset(&mut self, session_id: u64, request_id: i32) -> Fallible<i64> {
        let retc = unsafe { TraderApi_QueryAsset(self.trader_api, session_id, request_id) };
        self.translate_code(retc as i64, true)
    }

    pub fn query_structured_fund(
        &mut self,
        query_param: &types::XTPQueryStructuredFundInfoReq,
        session_id: u64,
        request_id: i32,
    ) -> Fallible<i64> {
        let retc = unsafe {
            TraderApi_QueryStructuredFund(
                self.trader_api,
                &mut query_param.into() as *mut _,
                session_id,
                request_id,
            )
        };
        self.translate_code(retc as i64, true)
    }

    pub fn fund_transfer(
        &mut self,
        fund_transfer: &types::XTPFundTransferReq,
        session_id: u64,
    ) -> Fallible<i64> {
        let retc = unsafe {
            TraderApi_FundTransfer(
                self.trader_api,
                &mut fund_transfer.into() as *mut _,
                session_id,
            )
        };
        self.translate_code(retc as i64, false)
    }

    pub fn query_fund_transfer(
        &mut self,
        query_param: types::XTPQueryFundTransferLogReq,
        session_id: u64,
        request_id: i32,
    ) -> Fallible<i64> {
        let retc = unsafe {
            TraderApi_QueryFundTransfer(
                self.trader_api,
                &mut (&query_param).into() as *mut _,
                session_id,
                request_id,
            )
        };
        self.translate_code(retc as i64, true)
    }

    pub fn query_etf(
        &mut self,
        query_param: &types::XTPQueryETFBaseReq,
        session_id: u64,
        request_id: i32,
    ) -> Fallible<i64> {
        let retc = unsafe {
            TraderApi_QueryETF(
                self.trader_api,
                &mut query_param.into(),
                session_id,
                request_id,
            )
        };
        self.translate_code(retc as i64, true)
    }

    pub fn query_etf_ticker_basket(
        &mut self,
        query_param: &types::XTPQueryETFComponentReq,
        session_id: u64,
        request_id: i32,
    ) -> Fallible<i64> {
        let retc = unsafe {
            TraderApi_QueryETFTickerBasket(
                self.trader_api,
                &mut query_param.into() as *mut _,
                session_id,
                request_id,
            )
        };
        self.translate_code(retc as i64, true)
    }

    pub fn query_ipo_info_list(&mut self, session_id: u64, request_id: i32) -> Fallible<i64> {
        let retc = unsafe { TraderApi_QueryIPOInfoList(self.trader_api, session_id, request_id) };
        self.translate_code(retc as i64, true)
    }

    pub fn query_ipo_quota_info(&mut self, session_id: u64, request_id: i32) -> Fallible<i64> {
        let retc = unsafe { TraderApi_QueryIPOQuotaInfo(self.trader_api, session_id, request_id) };
        self.translate_code(retc as i64, true)
    }

    pub fn query_option_auction_info(
        &mut self,
        query_param: &types::XTPQueryOptionAuctionInfoReq,
        session_id: u64,
        request_id: i32,
    ) -> Fallible<i64> {
        let retc = unsafe {
            TraderApi_QueryOptionAuctionInfo(
                self.trader_api,
                &mut query_param.into() as *mut _,
                session_id,
                request_id,
            )
        };
        self.translate_code(retc as i64, true)
    }
}

impl Drop for TraderApi {
    fn drop(&mut self) {
        self.release();
        if let Some(spi_stub) = self.trader_spi_stub {
            unsafe { TraderSpiStub_Destructor(spi_stub) };
        }
    }
}