Repository navigation
Expand file tree
/
Copy pathTraderApi.cpp
More file actions
2385 lines (2009 loc) · 79.3 KB
/
Copy pathTraderApi.cpp
File metadata and controls
2385 lines (2009 loc) · 79.3 KB
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
#include "stdafx.h"
#include "TraderApi.h"
#include "../../include/QueueEnum.h"
#include "../../include/ApiHeader.h"
#include "../../include/ApiStruct.h"
#include "../../include/toolkit.h"
#include "../../include/queue/MsgQueue.h"
#include "../CTP/TypeConvert.h"
#include <cstring>
#include <assert.h>
#include <cfloat>
#if defined(_MSC_VER) || defined(_WIN32)
#include <direct.h>
#endif
#ifdef ENABLE_LICENSE
#include "../../common/License/License.h"
#endif
void* __stdcall Query(char type, void* pApi1, void* pApi2, double double1, double double2, void* ptr1, int size1, void* ptr2, int size2, void* ptr3, int size3)
{
// 由内部调用,不用检查是否为空
CTraderApi* pApi = (CTraderApi*)pApi2;
pApi->QueryInThread(type, pApi1, pApi2, double1, double2, ptr1, size1, ptr2, size2, ptr3, size3);
return nullptr;
}
void CTraderApi::QueryInThread(char type, void* pApi1, void* pApi2, double double1, double double2, void* ptr1, int size1, void* ptr2, int size2, void* ptr3, int size3)
{
int iRet = 0;
switch (type)
{
case E_Init:
iRet = _Init();
break;
case E_Disconnect:
_Disconnect(true);
// 不再循环
return;
}
if (m_pApi)
{
switch (type)
{
case E_ReqAuthenticateField:
iRet = _ReqAuthenticate(type, pApi1, pApi2, double1, double2, ptr1, size1, ptr2, size2, ptr3, size3);
break;
case E_ReqUserLoginField:
iRet = _ReqUserLogin(type, pApi1, pApi2, double1, double2, ptr1, size1, ptr2, size2, ptr3, size3);
break;
case E_UserLogoutField:
iRet = _ReqUserLogout(type, pApi1, pApi2, double1, double2, ptr1, size1, ptr2, size2, ptr3, size3);
break;
case E_ReqUserPasswordUpdateField:
iRet = _ReqUserPasswordUpdate(type, pApi1, pApi2, double1, double2, ptr1, size1, ptr2, size2, ptr3, size3);
break;
case QueryType::QueryType_ReqQryTradingAccount:
iRet = _ReqQryTradingAccount(type, pApi1, pApi2, double1, double2, ptr1, size1, ptr2, size2, ptr3, size3);
break;
case QueryType::QueryType_ReqQryInvestorPosition:
iRet = _ReqQryInvestorPosition(type, pApi1, pApi2, double1, double2, ptr1, size1, ptr2, size2, ptr3, size3);
break;
case QueryType::QueryType_ReqQryInstrument:
iRet = _ReqQryInstrument(type, pApi1, pApi2, double1, double2, ptr1, size1, ptr2, size2, ptr3, size3);
break;
case QueryType::QueryType_ReqQryInvestor:
iRet = _ReqQryInvestor(type, pApi1, pApi2, double1, double2, ptr1, size1, ptr2, size2, ptr3, size3);
break;
case QueryType::QueryType_ReqQryOrder:
iRet = _ReqQryOrder(type, pApi1, pApi2, double1, double2, ptr1, size1, ptr2, size2, ptr3, size3);
break;
case QueryType::QueryType_ReqQryTrade:
iRet = _ReqQryTrade(type, pApi1, pApi2, double1, double2, ptr1, size1, ptr2, size2, ptr3, size3);
break;
#ifdef HAS_Quote
case QueryType::QueryType_ReqQryQuote:
iRet = _ReqQryQuote(type, pApi1, pApi2, double1, double2, ptr1, size1, ptr2, size2, ptr3, size3);
break;
#endif // HAS_Quote
#ifdef HAS_Settlement
case E_SettlementInfoConfirmField:
iRet = _ReqSettlementInfoConfirm(type, pApi1, pApi2, double1, double2, ptr1, size1, ptr2, size2, ptr3, size3);
break;
case QueryType::QueryType_ReqQrySettlementInfo:
iRet = _ReqQrySettlementInfo(type, pApi1, pApi2, double1, double2, ptr1, size1, ptr2, size2, ptr3, size3);
break;
#endif // HAS_Settlement
default:
break;
}
}
if (0 == iRet)
{
//返回成功,填加到已发送池
m_nSleep = 1;
}
else
{
m_msgQueue_Query->Input_Copy(type, pApi1, pApi2, double1, double2, ptr1, size1, ptr2, size2, ptr3, size3);
//失败,按4的幂进行延时,但不超过1s
m_nSleep *= 4;
m_nSleep %= 1023;
}
this_thread::sleep_for(chrono::milliseconds(m_nSleep));
}
void CTraderApi::Register(void* pCallback, void* pClass)
{
m_pClass = pClass;
if (m_msgQueue == nullptr)
return;
m_msgQueue_Query->Register(Query);
m_msgQueue->Register((fnOnResponse)pCallback);
if (pCallback)
{
m_msgQueue_Query->StartThread();
m_msgQueue->StartThread();
}
else
{
m_msgQueue_Query->StopThread();
m_msgQueue->StopThread();
}
}
CTraderApi::CTraderApi(void)
{
m_pApi = nullptr;
m_lRequestID = 0;
m_nSleep = 1;
// 自己维护两个消息队列
m_msgQueue = new CMsgQueue();
m_msgQueue_Query = new CMsgQueue();
m_msgQueue_Query->Register(Query);
m_msgQueue_Query->StartThread();
#ifdef ENABLE_LICENSE
// 为了这个加密库,居然把编译选项由/MDd改成了/MTd,以后一定要想办法改回去
m_pLicense = new CLicense();
char szPath[MAX_PATH] = { 0 };
m_pLicense->GetDllPathByFunctionName("XRequest", szPath);
m_pLicense->SetLicensePath(szPath);
// 这里选的是从文件中加载公钥,可以写死到资源或代码中,这样用户就没有那么容易自己生成公私钥对替换了
m_pLicense->SetPublicKeyString(DLL_PUBLIC_KEY);
string signatureString = m_pLicense->LoadStringFromFile(m_pLicense->m_SignaturePath);
m_pLicense->SetSignatureString(signatureString.c_str());
#endif
//m_delete = false;
}
CTraderApi::~CTraderApi(void)
{
_Disconnect(false);
#ifdef ENABLE_LICENSE
if (m_pLicense == nullptr)
{
delete m_pLicense;
m_pLicense = nullptr;
}
#endif
}
bool CTraderApi::IsErrorRspInfo(const char* szSource, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
bool bRet = ((pRspInfo) && (pRspInfo->ErrorID != 0));
if (bRet)
{
ErrorField* pField = (ErrorField*)m_msgQueue->new_block(sizeof(ErrorField));
pField->RawErrorID = pRspInfo->ErrorID;
strcpy(pField->Text, pRspInfo->ErrorMsg);
strcpy(pField->Source, szSource);
m_msgQueue->Input_NoCopy(ResponseType::ResponseType_OnRtnError, m_msgQueue, m_pClass, bIsLast, 0, pField, sizeof(ErrorField), nullptr, 0, nullptr, 0);
}
return bRet;
}
bool CTraderApi::IsErrorRspInfo(CThostFtdcRspInfoField *pRspInfo)
{
bool bRet = ((pRspInfo) && (pRspInfo->ErrorID != 0));
return bRet;
}
void CTraderApi::Connect(const string& szPath,
ServerInfoField* pServerInfo,
UserInfoField* pUserInfo,
int count)
{
m_szPath = szPath;
memcpy(&m_ServerInfo, pServerInfo, sizeof(ServerInfoField));
memcpy(&m_UserInfo, pUserInfo, sizeof(UserInfoField));
m_msgQueue_Query->Input_NoCopy(RequestType::E_Init, m_msgQueue_Query, this, 0, 0,
nullptr, 0, nullptr, 0, nullptr, 0);
}
int CTraderApi::_Init()
{
#ifdef ENABLE_LICENSE
int err = m_pLicense->LoadIni();
if (err != 0)
{
// 没有授权文件
m_pLicense->CreateDefault();
m_pLicense->AddUser(m_UserInfo.UserID, "*");
err = m_pLicense->SaveIni();
}
if (err == 0)
{
err = m_pLicense->GetErrorCodeForMachineID();
}
if (err == 0)
{
err = m_pLicense->GetErrorCodeByAccount(m_UserInfo.UserID);
}
if (err == 0)
{
err = m_pLicense->GetErrorCodeForSign();
}
if (err == 0)
{
err = m_pLicense->GetErrorCodeForExpireDate();
}
if (err != 0)
{
RspUserLoginField* pField = (RspUserLoginField*)m_msgQueue->new_block(sizeof(RspUserLoginField));
pField->RawErrorID = err;
strncpy(pField->Text, m_pLicense->GetErrorInfo(), sizeof(Char256Type));
// >0的错误表示不严重,可以继续
if (err > 0)
{
m_msgQueue->Input_NoCopy(ResponseType::ResponseType_OnConnectionStatus, m_msgQueue, m_pClass, ConnectionStatus::ConnectionStatus_Initialized, 0, pField, sizeof(RspUserLoginField), nullptr, 0, nullptr, 0);
}
else if (err < 0)
{
m_msgQueue->Input_NoCopy(ResponseType::ResponseType_OnConnectionStatus, m_msgQueue, m_pClass, ConnectionStatus::ConnectionStatus_Disconnected, 0, pField, sizeof(RspUserLoginField), nullptr, 0, nullptr, 0);
return 0;
}
}
#endif
char *pszPath = new char[m_szPath.length() + 1024];
srand((unsigned int)time(nullptr));
sprintf(pszPath, "%s/%s/%s/Td/%d/", m_szPath.c_str(), m_ServerInfo.BrokerID, m_UserInfo.UserID, rand());
makedirs(pszPath);
// 本来想使用chdir的方法解决Kingstar的证书问题,测试多次发现还是读取的exe目录下
// 打算使用文件复制的方法来实现,
// 1.先检查证书是否存在,存在就跳过
// 2.复制,用完要删
#ifdef KS_COPYFILE
lock_guard<mutex> cl(m_csOrderRef);
char szExePath[MAX_PATH] = { 0 };
GetExePath(szExePath);
char szDllPath[MAX_PATH] = { 0 };
GetDllPathByFunctionName("XRequest", szDllPath);
char szExistingFileName[MAX_PATH] = { 0 };
char szNewFileName[MAX_PATH] = { 0 };
GetNewPathInSameDirectory(szDllPath, KS_LKC_FILENAME, KS_LKC_EXT, szExistingFileName);
GetNewPathInSameDirectory(szExePath, KS_LKC_FILENAME, KS_LKC_EXT, szNewFileName);
bool bRet = CopyFileA(szExistingFileName, szNewFileName, false);
if (!bRet)
{
char szBuf[256] = { 0 };
LPVOID lpMsgBuf;
DWORD dw = GetLastError();
FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)&lpMsgBuf,
0, NULL);
LogField* pField = (LogField*)m_msgQueue->new_block(sizeof(LogField));
sprintf(pField->Message, "CopyFile:%s", lpMsgBuf);
m_msgQueue->Input_NoCopy(ResponseType::ResponseType_OnLog, m_msgQueue, m_pClass, true, 0, pField, sizeof(LogField), nullptr, 0, nullptr, 0);
}
#endif // KS_COPYFILE
m_msgQueue->Input_NoCopy(ResponseType::ResponseType_OnConnectionStatus, m_msgQueue, m_pClass, ConnectionStatus::ConnectionStatus_Initialized, 0, nullptr, 0, nullptr, 0, nullptr, 0);
m_pApi = CThostFtdcTraderApi::CreateFtdcTraderApi(pszPath);
delete[] pszPath;
if (m_pApi)
{
m_pApi->RegisterSpi(this);
//添加地址
size_t len = strlen(m_ServerInfo.Address) + 1;
char* buf = new char[len];
strncpy(buf, m_ServerInfo.Address, len);
char* token = strtok(buf, _QUANTBOX_SEPS_);
while (token)
{
if (strlen(token) > 0)
{
m_pApi->RegisterFront(token);
}
token = strtok(nullptr, _QUANTBOX_SEPS_);
}
delete[] buf;
//如果空着,反而是从头开始接收了,所以这里要特别处理一下
if (m_ServerInfo.PublicTopicResumeType < ResumeType::ResumeType_Undefined)
{
m_pApi->SubscribePublicTopic((THOST_TE_RESUME_TYPE)m_ServerInfo.PublicTopicResumeType);
}
else
{
m_pApi->SubscribePublicTopic(THOST_TERT_QUICK);
}
if (m_ServerInfo.PrivateTopicResumeType < ResumeType::ResumeType_Undefined)
{
m_pApi->SubscribePrivateTopic((THOST_TE_RESUME_TYPE)m_ServerInfo.PrivateTopicResumeType);
}
else
{
m_pApi->SubscribePrivateTopic(THOST_TERT_QUICK);
}
//初始化连接
m_pApi->Init();
m_msgQueue->Input_NoCopy(ResponseType::ResponseType_OnConnectionStatus, m_msgQueue, m_pClass, ConnectionStatus::ConnectionStatus_Connecting, 0, nullptr, 0, nullptr, 0, nullptr, 0);
}
else
{
RspUserLoginField* pField = (RspUserLoginField*)m_msgQueue->new_block(sizeof(RspUserLoginField));
pField->RawErrorID = 0;
strncpy(pField->Text, "(Api==null)", sizeof(Char256Type));
m_msgQueue->Input_NoCopy(ResponseType::ResponseType_OnConnectionStatus, m_msgQueue, m_pClass, ConnectionStatus::ConnectionStatus_Disconnected, 0, pField, sizeof(RspUserLoginField), nullptr, 0, nullptr, 0);
}
#ifdef KS_COPYFILE
if (bRet)
{
DeleteFileA(szNewFileName);
}
#endif // KS_COPYFILE
return 0;
}
void CTraderApi::OnFrontConnected()
{
m_msgQueue->Input_NoCopy(ResponseType::ResponseType_OnConnectionStatus, m_msgQueue, m_pClass, ConnectionStatus::ConnectionStatus_Connected, 0, nullptr, 0, nullptr, 0, nullptr, 0);
//连接成功后自动请求认证或登录
if (strlen(m_ServerInfo.AuthCode) > 0)
{
//填了认证码就先认证
ReqAuthenticate();
}
else
{
ReqUserLogin();
}
}
void CTraderApi::OnFrontDisconnected(int nReason)
{
RspUserLoginField* pField = (RspUserLoginField*)m_msgQueue->new_block(sizeof(RspUserLoginField));
//连接失败返回的信息是拼接而成,主要是为了统一输出
pField->RawErrorID = nReason;
GetOnFrontDisconnectedMsg(nReason, pField->Text);
m_msgQueue->Input_NoCopy(ResponseType::ResponseType_OnConnectionStatus, m_msgQueue, m_pClass, ConnectionStatus::ConnectionStatus_Disconnected, 0, pField, sizeof(RspUserLoginField), nullptr, 0, nullptr, 0);
// 收到登录失败后并没有销毁API,飞鼠只能登录一个用户,所以导致飞鼠登录失败
_DisconnectInThread();
}
void CTraderApi::ReqAuthenticate()
{
CThostFtdcReqAuthenticateField* pBody = (CThostFtdcReqAuthenticateField*)m_msgQueue_Query->new_block(sizeof(CThostFtdcReqAuthenticateField));
strncpy(pBody->BrokerID, m_ServerInfo.BrokerID, sizeof(TThostFtdcBrokerIDType));
strncpy(pBody->UserID, m_UserInfo.UserID, sizeof(TThostFtdcInvestorIDType));
strncpy(pBody->UserProductInfo, m_ServerInfo.UserProductInfo, sizeof(TThostFtdcProductInfoType));
strncpy(pBody->AuthCode, m_ServerInfo.AuthCode, sizeof(TThostFtdcAuthCodeType));
#ifdef USE_APP_ID
// CTP接口新加了穿透试认证
strncpy(pBody->AppID, m_ServerInfo.AppID, sizeof(TThostFtdcAppIDType));
#endif
m_msgQueue_Query->Input_NoCopy(RequestType::E_ReqAuthenticateField, m_msgQueue_Query, this, 0, 0,
pBody, sizeof(CThostFtdcReqAuthenticateField), nullptr, 0, nullptr, 0);
}
int CTraderApi::_ReqAuthenticate(char type, void* pApi1, void* pApi2, double double1, double double2, void* ptr1, int size1, void* ptr2, int size2, void* ptr3, int size3)
{
m_msgQueue->Input_NoCopy(ResponseType::ResponseType_OnConnectionStatus, m_msgQueue, m_pClass, ConnectionStatus::ConnectionStatus_Authorizing, 0, nullptr, 0, nullptr, 0, nullptr, 0);
return m_pApi->ReqAuthenticate((CThostFtdcReqAuthenticateField*)ptr1, ++m_lRequestID);
}
void CTraderApi::OnRspAuthenticate(CThostFtdcRspAuthenticateField *pRspAuthenticateField, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
if (!IsErrorRspInfo(pRspInfo)
&& pRspAuthenticateField)
{
m_msgQueue->Input_NoCopy(ResponseType::ResponseType_OnConnectionStatus, m_msgQueue, m_pClass, ConnectionStatus::ConnectionStatus_Authorized, 0, nullptr, 0, nullptr, 0, nullptr, 0);
ReqUserLogin();
}
else
{
RspUserLoginField* pField = (RspUserLoginField*)m_msgQueue->new_block(sizeof(RspUserLoginField));
pField->RawErrorID = pRspInfo->ErrorID;
strncpy(pField->Text, pRspInfo->ErrorMsg, sizeof(Char256Type));
m_msgQueue->Input_NoCopy(ResponseType::ResponseType_OnConnectionStatus, m_msgQueue, m_pClass, ConnectionStatus::ConnectionStatus_Disconnected, 0, pField, sizeof(RspUserLoginField), nullptr, 0, nullptr, 0);
}
}
void CTraderApi::ReqUserLogin()
{
CThostFtdcReqUserLoginField* pBody = (CThostFtdcReqUserLoginField*)m_msgQueue_Query->new_block(sizeof(CThostFtdcReqUserLoginField));
strncpy(pBody->BrokerID, m_ServerInfo.BrokerID, sizeof(TThostFtdcBrokerIDType));
strncpy(pBody->UserID, m_UserInfo.UserID, sizeof(TThostFtdcInvestorIDType));
strncpy(pBody->Password, m_UserInfo.Password, sizeof(TThostFtdcPasswordType));
strncpy(pBody->UserProductInfo, m_ServerInfo.UserProductInfo, sizeof(TThostFtdcProductInfoType));
m_msgQueue_Query->Input_NoCopy(RequestType::E_ReqUserLoginField, m_msgQueue_Query, this, 0, 0,
pBody, sizeof(CThostFtdcReqUserLoginField), nullptr, 0, nullptr, 0);
}
int CTraderApi::_ReqUserLogin(char type, void* pApi1, void* pApi2, double double1, double double2, void* ptr1, int size1, void* ptr2, int size2, void* ptr3, int size3)
{
m_msgQueue->Input_NoCopy(ResponseType::ResponseType_OnConnectionStatus, m_msgQueue, m_pClass, ConnectionStatus::ConnectionStatus_Logining, 0, nullptr, 0, nullptr, 0, nullptr, 0);
return m_pApi->ReqUserLogin((CThostFtdcReqUserLoginField*)ptr1, ++m_lRequestID);
}
void CTraderApi::ReqUserLogout()
{
CThostFtdcUserLogoutField* pBody = (CThostFtdcUserLogoutField*)m_msgQueue_Query->new_block(sizeof(CThostFtdcUserLogoutField));
strncpy(pBody->BrokerID, m_ServerInfo.BrokerID, sizeof(TThostFtdcBrokerIDType));
strncpy(pBody->UserID, m_UserInfo.UserID, sizeof(TThostFtdcInvestorIDType));
if (m_msgQueue_Query)
{
m_msgQueue_Query->Input_NoCopy(RequestType::E_UserLogoutField, m_msgQueue_Query, this, 0, 0,
pBody, sizeof(CThostFtdcReqUserLoginField), nullptr, 0, nullptr, 0);
}
}
int CTraderApi::_ReqUserLogout(char type, void* pApi1, void* pApi2, double double1, double double2, void* ptr1, int size1, void* ptr2, int size2, void* ptr3, int size3)
{
if (m_pApi)
{
return m_pApi->ReqUserLogout((CThostFtdcUserLogoutField*)ptr1, ++m_lRequestID);
}
return 0;
}
void CTraderApi::OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
RspUserLoginField* pField = (RspUserLoginField*)m_msgQueue->new_block(sizeof(RspUserLoginField));
if (!IsErrorRspInfo(pRspInfo)
&& pRspUserLogin)
{
#ifdef HAS_TradingDay_UserLogin
pField->TradingDay = str_to_yyyyMMdd(pRspUserLogin->TradingDay);
#else
pField->TradingDay = current_date();
#endif // HAS_TradingDay_UserLogin
pField->LoginTime = str_to_HHmmss(pRspUserLogin->LoginTime);
sprintf(pField->SessionID, "%d:%d", pRspUserLogin->FrontID, pRspUserLogin->SessionID);
m_msgQueue->Input_NoCopy(ResponseType::ResponseType_OnConnectionStatus, m_msgQueue, m_pClass, ConnectionStatus::ConnectionStatus_Logined, 0, pField, sizeof(RspUserLoginField), nullptr, 0, nullptr, 0);
// 记下登录信息,可能会用到
memcpy(&m_RspUserLogin, pRspUserLogin, sizeof(CThostFtdcRspUserLoginField));
// 飞鼠是报单引用是长字符串
#ifdef USE_LONG_ORDER_REF
m_nMaxOrderRef = atol(pRspUserLogin->MaxOrderRef);
#else
m_nMaxOrderRef = atol(pRspUserLogin->MaxOrderRef);
#endif
// 自己发单时ID从1开始,不能从0开始
//m_nMaxOrderRef = m_nMaxOrderRef>1 ? m_nMaxOrderRef : 1;
// 飞鼠接口,这个数返回的是上次退出时最大编号,所以将要使用的得+1
// 而其它接口是这次可以使用的报单编号,所以出于使用考虑,直接+1
m_nMaxOrderRef += 1;
// 结算单确认,CTP必须确认才能下单
#ifdef HAS_Settlement
ReqSettlementInfoConfirm();
#else
QueryOrderTrade(false);
#endif // HAS_Settlement
#ifdef IS_SGIT_API
// 飞鼠返回的资金太多了,关闭掉
m_pApi->IsReviveNtyCapital(FALSE);
#ifdef ENABLE_LICENSE
// 飞鼠由于目前没办法查投资者列表,无法根据姓名来判断授权,所以只能提前设置为可用
m_pLicense->SetSendOrderFlag(true);
#endif
#else
// 查询投资查,授权认证时使
// 飞鼠使用此功能需要服务器升级
ReqQueryField body = { 0 };
ReqQuery(QueryType::QueryType_ReqQryInvestor, &body);
#endif
//TEST:测完要删
//body.DateStart = 20151111;
//ReqQuery(QueryType::ReqQrySettlementInfo, &body);
}
else
{
// 140,首次登录改密码
// 131 弱密码
//if (pRspInfo->ErrorID == 140)
//{
// // ReqUserPasswordUpdate("123456", "123@abc");
// ReqUserPasswordUpdate("123456", "279183@ABC");
// return;
//}
pField->RawErrorID = pRspInfo->ErrorID;
strncpy(pField->Text, pRspInfo->ErrorMsg, sizeof(Char256Type));
m_msgQueue->Input_NoCopy(ResponseType::ResponseType_OnConnectionStatus, m_msgQueue, m_pClass, ConnectionStatus::ConnectionStatus_Disconnected, 0, pField, sizeof(RspUserLoginField), nullptr, 0, nullptr, 0);
// 收到登录失败后并没有销毁API,飞鼠一次只能登录一个用户,所以导致飞鼠用户失败
_DisconnectInThread();
}
}
void CTraderApi::ReqUserPasswordUpdate(char* szOldPassword, char* szNewPassword)
{
CThostFtdcUserPasswordUpdateField* pBody = (CThostFtdcUserPasswordUpdateField*)m_msgQueue_Query->new_block(sizeof(CThostFtdcUserPasswordUpdateField));
strncpy(pBody->BrokerID, m_ServerInfo.BrokerID, sizeof(TThostFtdcBrokerIDType));
strncpy(pBody->UserID, m_UserInfo.UserID, sizeof(TThostFtdcUserIDType));
strncpy(pBody->OldPassword, szOldPassword, sizeof(TThostFtdcPasswordType));
strncpy(pBody->NewPassword, szNewPassword, sizeof(TThostFtdcPasswordType));
m_msgQueue_Query->Input_NoCopy(RequestType::E_ReqUserPasswordUpdateField, m_msgQueue_Query, this, 0, 0,
pBody, sizeof(CThostFtdcUserPasswordUpdateField), nullptr, 0, nullptr, 0);
}
int CTraderApi::_ReqUserPasswordUpdate(char type, void* pApi1, void* pApi2, double double1, double double2, void* ptr1, int size1, void* ptr2, int size2, void* ptr3, int size3)
{
return m_pApi->ReqUserPasswordUpdate((CThostFtdcUserPasswordUpdateField*)ptr1, ++m_lRequestID);
}
void CTraderApi::OnRspUserPasswordUpdate(CThostFtdcUserPasswordUpdateField *pUserPasswordUpdate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
if (!IsErrorRspInfo(pRspInfo)
&& pUserPasswordUpdate)
{
}
else
{
}
}
void CTraderApi::QueryOrderTrade(bool bForceQuery)
{
if (bForceQuery ||
(m_ServerInfo.PrivateTopicResumeType > ResumeType::ResumeType_Restart
&& (m_ServerInfo.PrivateTopicResumeType < ResumeType::ResumeType_Undefined)))
{
ReqQueryField body = { 0 };
ReqQuery(QueryType::QueryType_ReqQryOrder, &body);
ReqQuery(QueryType::QueryType_ReqQryQuote, &body);
}
}
#ifdef HAS_Settlement
void CTraderApi::ReqSettlementInfoConfirm()
{
CThostFtdcSettlementInfoConfirmField* pBody = (CThostFtdcSettlementInfoConfirmField*)m_msgQueue_Query->new_block(sizeof(CThostFtdcSettlementInfoConfirmField));
strncpy(pBody->BrokerID, m_ServerInfo.BrokerID, sizeof(TThostFtdcBrokerIDType));
strncpy(pBody->InvestorID, m_UserInfo.UserID, sizeof(TThostFtdcInvestorIDType));
m_msgQueue_Query->Input_NoCopy(RequestType::E_SettlementInfoConfirmField, m_msgQueue_Query, this, 0, 0,
pBody, sizeof(CThostFtdcSettlementInfoConfirmField), nullptr, 0, nullptr, 0);
}
int CTraderApi::_ReqSettlementInfoConfirm(char type, void* pApi1, void* pApi2, double double1, double double2, void* ptr1, int size1, void* ptr2, int size2, void* ptr3, int size3)
{
m_msgQueue->Input_NoCopy(ResponseType::ResponseType_OnConnectionStatus, m_msgQueue, m_pClass, ConnectionStatus::ConnectionStatus_Confirming, 0, nullptr, 0, nullptr, 0, nullptr, 0);
return m_pApi->ReqSettlementInfoConfirm((CThostFtdcSettlementInfoConfirmField*)ptr1, ++m_lRequestID);
}
void CTraderApi::OnRspSettlementInfoConfirm(CThostFtdcSettlementInfoConfirmField *pSettlementInfoConfirm, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
if (!IsErrorRspInfo(pRspInfo)
&& pSettlementInfoConfirm)
{
m_msgQueue->Input_NoCopy(ResponseType::ResponseType_OnConnectionStatus, m_msgQueue, m_pClass, ConnectionStatus::ConnectionStatus_Confirmed, 0, nullptr, 0, nullptr, 0, nullptr, 0);
m_msgQueue->Input_NoCopy(ResponseType::ResponseType_OnConnectionStatus, m_msgQueue, m_pClass, ConnectionStatus::ConnectionStatus_Done, 0, nullptr, 0, nullptr, 0, nullptr, 0);
// 结算单确认完成,后查询委托与成交
QueryOrderTrade(false);
}
else
{
RspUserLoginField* pField = (RspUserLoginField*)m_msgQueue->new_block(sizeof(RspUserLoginField));
pField->RawErrorID = pRspInfo->ErrorID;
strncpy(pField->Text, pRspInfo->ErrorMsg, sizeof(Char256Type));
m_msgQueue->Input_NoCopy(ResponseType::ResponseType_OnConnectionStatus, m_msgQueue, m_pClass, ConnectionStatus::ConnectionStatus_Disconnected, 0, pField, sizeof(RspUserLoginField), nullptr, 0, nullptr, 0);
}
}
#endif // HAS_Settlement
void CTraderApi::Disconnect()
{
_Disconnect(false);
}
void CTraderApi::_DisconnectInThread()
{
m_msgQueue_Query->Input_NoCopy(RequestType::E_Disconnect, m_msgQueue_Query, this, 0, 0,
nullptr, 0, nullptr, 0, nullptr, 0);
}
void CTraderApi::_Disconnect(bool IsInQueue)
{
//if (m_delete)
// return;
//m_delete = true;
// 由于飞鼠一次只能登录一个账号,以前的方法连接可能没有断开,这里只能主动退出,其它的程序就不管了
#ifdef IS_SGIT_API
ReqUserLogout();
Sleep(1000);
#endif
if (IsInQueue)
{
}
else
{
if (m_msgQueue_Query)
{
m_msgQueue_Query->StopThread();
m_msgQueue_Query->Register(nullptr);
m_msgQueue_Query->Clear();
delete m_msgQueue_Query;
m_msgQueue_Query = nullptr;
}
}
if (m_pApi)
{
// 为何感觉飞鼠没有登出成功,还在运行?
m_pApi->RegisterSpi(nullptr);
m_pApi->Release();
m_pApi = nullptr;
// 全清理,只留最后一个
m_msgQueue->Clear();
m_msgQueue->Input_NoCopy(ResponseType::ResponseType_OnConnectionStatus, m_msgQueue, m_pClass, ConnectionStatus::ConnectionStatus_Disconnected, 0, nullptr, 0, nullptr, 0, nullptr, 0);
// 主动触发
m_msgQueue->Process();
}
if (m_msgQueue)
{
m_msgQueue->StopThread();
m_msgQueue->Register(nullptr);
m_msgQueue->Clear();
delete m_msgQueue;
m_msgQueue = nullptr;
}
m_lRequestID = 0;
Clear();
}
void CTraderApi::Clear()
{
for (unordered_map<string, OrderField*>::iterator it = m_id_platform_order.begin(); it != m_id_platform_order.end(); ++it)
delete it->second;
m_id_platform_order.clear();
for (unordered_map<string, CThostFtdcOrderField*>::iterator it = m_id_api_order.begin(); it != m_id_api_order.end(); ++it)
delete it->second;
m_id_api_order.clear();
for (unordered_map<string, PositionField*>::iterator it = m_id_platform_position.begin(); it != m_id_platform_position.end(); ++it)
delete it->second;
m_id_platform_position.clear();
for (unordered_map<string, CThostFtdcInvestorPositionField*>::iterator it = m_id_api_position.begin(); it != m_id_api_position.end(); ++it)
delete it->second;
m_id_api_position.clear();
#ifdef HAS_Quote
for (unordered_map<string, QuoteField*>::iterator it = m_id_platform_quote.begin(); it != m_id_platform_quote.end(); ++it)
delete it->second;
m_id_platform_quote.clear();
for (unordered_map<string, CThostFtdcQuoteField*>::iterator it = m_id_api_quote.begin(); it != m_id_api_quote.end(); ++it)
delete it->second;
m_id_api_quote.clear();
#endif // HAS_Quote
}
char* CTraderApi::ReqOrderInsert(
OrderField* pOrder,
int count,
char* pszLocalIDBuf)
{
int OrderRef = -1;
if (nullptr == m_pApi)
return nullptr;
CThostFtdcInputOrderField body = { 0 };
strncpy(body.BrokerID, m_RspUserLogin.BrokerID, sizeof(TThostFtdcBrokerIDType));
strncpy(body.InvestorID, m_RspUserLogin.UserID, sizeof(TThostFtdcInvestorIDType));
#ifdef IS_SGIT_API
// 为飞鼠加的,否则报席位不符
strncpy(body.UserID, m_RspUserLogin.UserID, sizeof(TThostFtdcUserIDType));
#endif
body.MinVolume = 1;
body.ForceCloseReason = THOST_FTDC_FCC_NotForceClose;
body.IsAutoSuspend = 0;
body.UserForceClose = 0;
body.IsSwapOrder = 0;
//合约
strncpy(body.InstrumentID, pOrder->InstrumentID, sizeof(TThostFtdcInstrumentIDType));
#ifdef HAS_ExchangeID_Order
strncpy(body.ExchangeID, pOrder->ExchangeID, sizeof(TThostFtdcExchangeIDType));
#endif // HAS_ExchangeID_Order
//买卖
body.Direction = OrderSide_2_TThostFtdcDirectionType(pOrder->Side);
//开平
body.CombOffsetFlag[0] = OpenCloseType_2_TThostFtdcOffsetFlagType(pOrder->OpenClose);
//投保
body.CombHedgeFlag[0] = HedgeFlagType_2_TThostFtdcHedgeFlagType(pOrder->HedgeFlag);
//数量
body.VolumeTotalOriginal = (int)pOrder->Qty;
// 对于套利单,是用第一个参数的价格,还是用两个参数的价格差呢?
body.LimitPrice = pOrder->Price;
body.StopPrice = pOrder->StopPx;
// 针对第二个进行处理,如果有第二个参数,认为是交易所套利单
if (count > 1)
{
body.CombOffsetFlag[1] = OpenCloseType_2_TThostFtdcOffsetFlagType(pOrder[1].OpenClose);
body.CombHedgeFlag[1] = HedgeFlagType_2_TThostFtdcHedgeFlagType(pOrder[1].HedgeFlag);
// 交易所的移仓换月功能,没有实测过
body.IsSwapOrder = (body.CombOffsetFlag[0] != body.CombOffsetFlag[1]);
}
// 市价与限价
switch (pOrder->Type)
{
case OrderType_Market:
case OrderType_Stop:
case OrderType_MarketOnClose:
case OrderType_TrailingStop:
body.OrderPriceType = THOST_FTDC_OPT_AnyPrice;
body.TimeCondition = THOST_FTDC_TC_IOC;
body.LimitPrice = 0;
break;
case OrderType_Limit:
case OrderType_StopLimit:
case OrderType_TrailingStopLimit:
default:
body.OrderPriceType = THOST_FTDC_OPT_LimitPrice;
body.TimeCondition = THOST_FTDC_TC_GFD;
break;
}
// IOC与FOK
switch (pOrder->TimeInForce)
{
case TimeInForce_IOC:
body.TimeCondition = THOST_FTDC_TC_IOC;
body.VolumeCondition = THOST_FTDC_VC_AV;
break;
case TimeInForce_FOK:
body.TimeCondition = THOST_FTDC_TC_IOC;
body.VolumeCondition = THOST_FTDC_VC_CV;
//body.MinVolume = body.VolumeTotalOriginal; // 这个地方必须加吗?
break;
default:
body.VolumeCondition = THOST_FTDC_VC_AV;
break;
}
// 条件单
switch (pOrder->Type)
{
case OrderType_Stop:
case OrderType_TrailingStop:
case OrderType_StopLimit:
case OrderType_TrailingStopLimit:
// 条件单没有测试,先留空
body.ContingentCondition = THOST_FTDC_CC_Immediately;
break;
default:
body.ContingentCondition = THOST_FTDC_CC_Immediately;
break;
}
int nRet = 0;
{
//可能报单太快,m_nMaxOrderRef还没有改变就提交了
lock_guard<mutex> cl(m_csOrderRef);
if (OrderRef < 0)
{
nRet = m_nMaxOrderRef;
++m_nMaxOrderRef;
}
else
{
nRet = OrderRef;
}
sprintf(body.OrderRef, "%d", nRet);
#ifdef USE_LONG_ORDER_REF
sprintf(body.OrderRef, "%012lld", nRet);
#endif
// 测试平台穿越速度,用完后需要注释掉
//WriteLog("CTP:ReqOrderInsert:%s %d", body.InstrumentID, nRet);
#ifdef ENABLE_LICENSE
int err = m_pLicense->GetErrorCodeForSendOrder();
if (err < 0)
{
sprintf(m_orderInsert_Id, "%d", -5);
OrderField* pField = (OrderField*)m_msgQueue->new_block(sizeof(OrderField));
memcpy(pField, pOrder, sizeof(OrderField));
strcpy(pField->ID, m_orderInsert_Id);
strcpy(pField->LocalID, pField->ID);
m_id_platform_order.insert(pair<string, OrderField*>(pField->LocalID, pField));
pField->RawErrorID = err;
strncpy(pField->Text, m_pLicense->GetErrorInfo(), sizeof(Char256Type));
pField->Status = OrderStatus::OrderStatus_Rejected;
pField->ExecType = ExecType::ExecType_Rejected;
strncpy((char*)pszLocalIDBuf, m_orderInsert_Id, sizeof(OrderIDType));
// 这个问题的关键是先到队列还是先返回
m_msgQueue->Input_Copy(ResponseType::ResponseType_OnRtnOrder, m_msgQueue, m_pClass, 0, 0, pField, sizeof(OrderField), nullptr, 0, nullptr, 0);
return pszLocalIDBuf;
}
#endif
//不保存到队列,而是直接发送
int n = m_pApi->ReqOrderInsert(&body, ++m_lRequestID);
if (n < 0)
{
nRet = n;
sprintf(m_orderInsert_Id, "%d", nRet);
}
else
{
// 用于各种情况下找到原订单,用于进行响应的通知
sprintf(m_orderInsert_Id, "%d:%d:%d", m_RspUserLogin.FrontID, m_RspUserLogin.SessionID, nRet);
#ifdef USE_LONG_ORDER_REF
sprintf(m_orderInsert_Id, "%d:%d:%012lld", m_RspUserLogin.FrontID, m_RspUserLogin.SessionID, nRet);
#endif
OrderField* pField = (OrderField*)m_msgQueue->new_block(sizeof(OrderField));
memcpy(pField, pOrder, sizeof(OrderField));
strcpy(pField->ID, m_orderInsert_Id);
strcpy(pField->LocalID, pField->ID);
m_id_platform_order.insert(pair<string, OrderField*>(pField->LocalID, pField));
}
strncpy((char*)pszLocalIDBuf, m_orderInsert_Id, sizeof(OrderIDType));
}
return pszLocalIDBuf;
}
void CTraderApi::OnRspOrderInsert(CThostFtdcInputOrderField *pInputOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
OrderIDType orderId = { 0 };
// 飞鼠报单成功也会走此路,所以需要处理一下,即只有发现有错误信息时才报出去
if (pInputOrder)
{
sprintf(orderId, "%d:%d:%s", m_RspUserLogin.FrontID, m_RspUserLogin.SessionID, pInputOrder->OrderRef);
}
else
{
// IsErrorRspInfo("OnRspOrderInsert", pRspInfo, nRequestID, bIsLast);
}
if (IsErrorRspInfo(pRspInfo))
{
unordered_map<string, OrderField*>::iterator it = m_id_platform_order.find(orderId);
if (it == m_id_platform_order.end())
{
// 没找到?不应当,这表示出错了
//assert(false);
}
else
{
// 找到了,要更新状态
// 得使用上次的状态
OrderField* pField = it->second;
pField->ExecType = ExecType::ExecType_Rejected;
pField->Status = OrderStatus::OrderStatus_Rejected;
pField->RawErrorID = pRspInfo->ErrorID;
strncpy(pField->Text, pRspInfo->ErrorMsg, sizeof(Char256Type));
m_msgQueue->Input_Copy(ResponseType::ResponseType_OnRtnOrder, m_msgQueue, m_pClass, 0, 0, pField, sizeof(OrderField), nullptr, 0, nullptr, 0);
}
}
}
void CTraderApi::OnErrRtnOrderInsert(CThostFtdcInputOrderField *pInputOrder, CThostFtdcRspInfoField *pRspInfo)
{
OrderIDType orderId = { 0 };
if (pInputOrder)
{
sprintf(orderId, "%d:%d:%s", m_RspUserLogin.FrontID, m_RspUserLogin.SessionID, pInputOrder->OrderRef);
}
else
{
IsErrorRspInfo("OnErrRtnOrderInsert", pRspInfo, 0, true);