-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathtradewidget.cpp
More file actions
1332 lines (1254 loc) · 43.6 KB
/
tradewidget.cpp
File metadata and controls
1332 lines (1254 loc) · 43.6 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
#ifdef WIN32
#include "windows.h"
#endif
#include "tradewidget.h"
#include <QContextMenuEvent>
#include <string>
#include <QDateTime>
#include <qlibrary.h>
#include "coolsubmit.h"
#include "orderManage.h"
#include "posiManage.h"
#include "help.h"
#include <QSettings>
#include <QFile>
#include <QUrl>
#include <QTextStream>
#include "PriceView.h"
#include "configWidget.h"
#include "changePassword.h"
#include "dealView.h"
#include "notice.h"
#include <time.h>
#include <QThread>
extern configWidget * cview;
extern changePassword *cpView;
extern loginWin * loginW;
extern TradeWidget * g_tw;
clock_t a;
typedef struct
{
QString name;
QString dll;
QString params;
}RouteInfo;
#define BCESMacroFlowResumeMethodResume 2
#define ORDERWIDGETW 380
#define GRAPHH 300
using namespace std;
static quint32 g_RequestID = 0;
// 线程锁
//QMutex mutex;
quint32 CreateNewRequestID()
{
++g_RequestID;
return g_RequestID;
}
static int virtualOrderId = 100000;
quint32 CreateVirtualOrderId()
{
++virtualOrderId;
return virtualOrderId;
}
CThostFtdcTraderApi* pTraderApi = NULL;
CTradeSpiImp *pTraderSpi = NULL;
CThostFtdcMdApi* pQuotApi = NULL;
CMdSpiImp * quotSpi = NULL;
QMap<QString, TradeInfo> tradeInfoLst;
// 交易所号 文字转换
QString convertExchangeID(TThostFtdcExchangeIDType ID)
{
int x = strlen(ID);
QString str = QString::fromLocal8Bit(ID);
if(::strcmp(ID, "SHFE") == 0)
{
str = QString::fromLocal8Bit("上期所");
}
else if(::strcmp(ID, "DCE") == 0)
{
str = QString::fromLocal8Bit("大商所");
}
else if(::strcmp(ID, "CZCE") == 0)
{
str = QString::fromLocal8Bit("郑商所");
}
else if(::strcmp(ID, "CFFEX") == 0)
{
str = QString::fromLocal8Bit("中金所");
}
else if(::strcmp(ID, "SZ") == 0)
{
str = QString::fromLocal8Bit("深市");
}
else if(::strcmp(ID, "SH") == 0)
{
str = QString::fromLocal8Bit("沪市");
}
else if(::strcmp(ID, "INE") == 0)
{
str = QString::fromLocal8Bit("能源中心");
}
else if(::strcmp(ID, "NULL") == 0)
{
str = QString::fromLocal8Bit("TickTrader");
}
return str;
}
// 价格类型 文字转换
QString convertPriceType(TThostFtdcOrderPriceTypeType flag)
{
QString str = "";
switch(flag)
{
case THOST_FTDC_OPT_LimitPrice:
str = QString::fromLocal8Bit("限价");
break;
case THOST_FTDC_OPT_AnyPrice:
str = QString::fromLocal8Bit("市价");
break;
// case BCESConstPriceTypeStop:
// str = QString::fromLocal8Bit(BCESConstCommentPriceTypeStop);
// break;
// case BCESConstPriceTypeLimit:
// str = QString::fromLocal8Bit(BCESConstCommentPriceTypeLimit);
// break;
}
return str;
}
// 开平 文字转换
QString convertOcFlag(TThostFtdcOffsetFlagType flag)
{
QString str = "";
switch(flag)
{
case THOST_FTDC_OF_Open:
str = QString::fromLocal8Bit("开");
break;
case THOST_FTDC_OF_Close:
str = QString::fromLocal8Bit("平");
break;
case THOST_FTDC_OF_CloseToday:
str = QString::fromLocal8Bit("平今");
break;
case THOST_FTDC_OF_ForceClose:
str = QString::fromLocal8Bit("强平");
break;
}
return str;
}
// 买卖 文字转换
QString convertBsFlag(TThostFtdcDirectionType flag)
{
QString str = "";
switch(flag)
{
case THOST_FTDC_D_Buy:
str = QString::fromLocal8Bit("买");
break;
case THOST_FTDC_D_Sell:
str = QString::fromLocal8Bit("卖");
break;
// case BCESConstBSFlagExecute:
// str = QString::fromLocal8Bit(BCESConstCommentBSFlagExecute);
// break;
}
return str;
}
// 订单状态文字转换
QString convertOrderStatus(TThostFtdcOrderStatusType flag)
{
QString str = "";
switch(flag)
{
case THOST_FTDC_OST_NoTradeNotQueueing:
str = QString::fromLocal8Bit("申报中");
break;
case THOST_FTDC_OST_NoTradeQueueing:
str = QString::fromLocal8Bit("已申报");
break;
case THOST_FTDC_OST_AllTraded:
str = QString::fromLocal8Bit("全部成交");
break;
case THOST_FTDC_OST_PartTradedQueueing:
str = QString::fromLocal8Bit("部分成交");
break;
case THOST_FTDC_OST_Canceled:
str = QString::fromLocal8Bit("已撤消");
break;
case THOST_FTDC_OST_NotTouched:
str = QString::fromLocal8Bit("未触发");
break;
}
return str;
}
// 条件类型文字转换
QString convertConditionMethod(TThostFtdcDirectionType flag)
{
QString str = "";
switch(flag)
{
// case THOST_FTDC_CC_Immediately:
// str = QString::fromLocal8Bit(BCESConstCommentConditionMethodNone);
// break;
// case BCESConstConditionMethodEqual:
// str = QString::fromLocal8Bit(BCESConstCommentConditionMethodEqual);
// break;
// case BCESConstConditionMethodMore:
// str = QString::fromLocal8Bit(BCESConstCommentConditionMethodMore);
// break;
// case BCESConstConditionMethodMoreEqual:
// str = QString::fromLocal8Bit(BCESConstCommentConditionMethodMoreEqual);
// break;
// case BCESConstConditionMethodLess:
// str = QString::fromLocal8Bit(BCESConstCommentConditionMethodLess);
// break;
// case BCESConstConditionMethodLessEqual:
// str = QString::fromLocal8Bit(BCESConstCommentConditionMethodLessEqual);
// break;
}
return str;
}
int TradeWidget::getScale(QString InstrumentID)
{
int pScale = 2;
CThostFtdcInstrumentField * sbInstr = insMap[InstrumentID];
if(!sbInstr)
return pScale;
if(sbInstr->PriceTick > 0.95)
pScale = 0;
else if(sbInstr->PriceTick > 0.095 && sbInstr->PriceTick < 0.95)
pScale = 1;
else if(sbInstr->PriceTick > 0.0095 && sbInstr->PriceTick < 0.095)
pScale = 2;
else if(sbInstr->PriceTick > 0.00095 && sbInstr->PriceTick < 0.0095)
pScale = 3;
return pScale;
}
TradeWidget::TradeWidget(QWidget *parent, Qt::WindowFlags flags)
:QMainWindow(parent, flags)
{
initTradeWin();
CSubmit = NULL;
omWidget = NULL;
cmWidget = NULL;
pview = NULL;
//oview = NULL;
dview = NULL;
loginStatusLbl = new QLabel(this);
this->ui.statusBar->addWidget(loginStatusLbl);
//this->ui.statusBar->setStyleSheet("font-size:7px;");
this->setMaximumWidth(320);
// 关闭时自动释放
setAttribute(Qt::WA_DeleteOnClose, true);
setGeometry(DW/2-160,DH/2-250,320,500);
connect(&m_timer, SIGNAL(timeout()), this, SLOT(onTimerReqPos()));
}
void TradeWidget::closeEvent (QCloseEvent * event)
{
Notice info(Notice::NOTICE_TYPE_WARNING, QString::fromLocal8Bit("退出TickTrader?"), false, QString::fromLocal8Bit("提示"), NULL, 0);
info.exec();
if(info.pushButton) {
exit(0);
}
event->ignore();
}
void TradeWidget::doCancelOrder(CThostFtdcInputOrderActionField *pOrderCancelRsp)
{
for(int i=0;i<o2upLst.length();i++)
{
NEWORDERINF & iti = o2upLst[i];
if(::strcmp(pOrderCancelRsp->OrderRef, iti.OrderRef) == 0)
{
int nRequestID = CreateNewRequestID();
CThostFtdcInputOrderField pInputOrder;
::memset(&pInputOrder,0,sizeof(CThostFtdcInputOrderField));
strncpy(pInputOrder.BrokerID, loginW->m_users.BrokerID, sizeof(pInputOrder.BrokerID));
strncpy(pInputOrder.InvestorID,iti.InvestorID, sizeof(pInputOrder.InvestorID)); /* 投资者号 */
strncpy(pInputOrder.InstrumentID, iti.InstrumentID, sizeof(pInputOrder.InstrumentID));
pInputOrder.Direction = iti.Direction; /* 买卖标志 */
pInputOrder.CombOffsetFlag[0] = iti.CombOffsetFlag[0]; /* 开平标志 */
pInputOrder.CombHedgeFlag[0] = THOST_FTDC_BHF_Speculation; /* 投机套保标志 */
pInputOrder.TimeCondition = THOST_FTDC_TC_GFD;
pInputOrder.VolumeCondition = THOST_FTDC_VC_AV;
pInputOrder.MinVolume = 1;
pInputOrder.ForceCloseReason = THOST_FTDC_FCC_NotForceClose;
pInputOrder.OrderPriceType = iti.PriceType; /* 价格类型 */
pInputOrder.LimitPrice = iti.Price; /* 价格 */
pInputOrder.TimeCondition = iti.ConditionMethod; /* 条件方法 */
pInputOrder.VolumeTotalOriginal = iti.Qty; /* 数量 */
strncpy(pInputOrder.ExchangeID, iti.ExchangeID, sizeof(pInputOrder.ExchangeID));
tradeInfoLst[iti.tif].api->ReqOrderInsert(&pInputOrder, nRequestID); // 录入订单
o2upLst.removeAt(i);
break;
}
}
// delete pOrderCancelRsp;
}
// 撤单成功后检查待下的新单列表
void TradeWidget::checkCancelOrder(CThostFtdcInputOrderActionField *pOrderCancelRsp)
{
CThostFtdcInputOrderActionField * cr = new CThostFtdcInputOrderActionField();
if(pOrderCancelRsp)
::memcpy(cr, pOrderCancelRsp,sizeof(CThostFtdcInputOrderActionField));
emit cancelOrder(cr);
}
void TradeWidget::tradingAftorLogin()
{
loginW->hide();
this->show();
UserInfo product;
strncpy(product.name,loginW->userName,sizeof(product.name));
strncpy(product.pass,loginW->password,sizeof(product.pass));
// strncpy(product.serv,loginW->server.name,sizeof(product.serv));
runTrade(product);
//QLabel * noticeLbl = new QLabel(QString::fromLocal8Bit(" 正在接收行情,请等待..."));
//QFont font;
// font.setFamily(QString::fromUtf8("Cambria Math"));
// font.setPointSize(24);
// noticeLbl->setFont(font);
// noticeLbl->setAlignment(Qt::AlignCenter);
//setCentralWidget(noticeLbl);
CSubmit = new CoolSubmit(g_tw->insMap.begin().key(), NULL, g_tw);
setCentralWidget(CSubmit);
orderMessageEmit(loginW->userName + QString::fromLocal8Bit(" \r\n登录成功!"));
loginStatusLbl->setText(QString::fromLocal8Bit("已登录"));
a = clock();
}
void TradeWidget::runTrade(UserInfo & element)
{
TradeInfo temp;
temp.name = QString(element.name);
TradeInfo & ti = tradeInfoLst[temp.name];
if(ti.name != "" && ti.updated == false)
return;
temp.accountName= QString(element.name);
temp.accountPass = QString(element.pass);
temp.updated = false;
temp.fund = new CThostFtdcTradingAccountField();
temp.orderLst.clear();
temp.tradeLst.clear();
temp.posiLst.clear();
::memset(temp.fund,0,sizeof(CThostFtdcTradingAccountField));
strncpy(temp.fund->AccountID,temp.accountName.toLatin1().data(),sizeof(temp.fund->AccountID));
temp.api=pTraderApi;
temp.spi=pTraderSpi;
tradeInfoLst[temp.name] = temp;
}
// 更新状态栏
void TradeWidget::updateStatusBar(CThostFtdcTradingAccountField * fund)
{
//double dqqy = fund->FreeBalance+fund->Margin+fund->FeeFrozen+fund->FrozenMargin+fund->FloatingPL; // 当前权益
//QString lsb = QString::fromLocal8Bit("当前权益:");
//lsb.append(QString::number(dqqy,'f',0));
//lsb.append(QString::fromLocal8Bit(",可用资金:"));
//lsb.append(QString::number(fund->FreeBalance,'f',0));
//lsb.append(QString::fromLocal8Bit(",浮动盈亏:"));
//lsb.append(QString::number(fund->FloatingPL,'f',0));
//loginStatusLbl->setText(lsb);
}
// 交易账户连接成功
void TradeWidget::TradeConnect(CTradeSpiImp * t)
{
emit tradeConnSec(t);
}
// 交易账户连接成功
void TradeWidget::doTradeConnSec(CTradeSpiImp * t)
{
QMapIterator<QString, TradeInfo> i(tradeInfoLst);
while (i.hasNext())
{
TradeInfo & ti= tradeInfoLst[i.next().key()];
if(ti.spi == t)
{
CThostFtdcReqUserLoginField LogonReq;
memset(&LogonReq,0x00,sizeof(LogonReq));
QString userName =ti.accountName;
QString pwd = ti.accountPass;
strncpy(LogonReq.UserID,userName.toLatin1().data(),sizeof(LogonReq.UserID));
strncpy(LogonReq.Password,pwd.toLatin1().data(),sizeof(LogonReq.Password));
memcpy(LogonReq.UserProductInfo, "openctp", sizeof(LogonReq.UserProductInfo));
// LogonReq.ProductVersion = PRODUCT_VERSION;
ti.api->ReqUserLogin(&LogonReq,0);
break;
}
}
}
// 行情推送
void TradeWidget::priceEmit(CThostFtdcDepthMarketDataField *p)
{
CThostFtdcDepthMarketDataField * pe = new CThostFtdcDepthMarketDataField;
::memcpy(pe, p,sizeof(CThostFtdcDepthMarketDataField));
emit getPpricePush(pe);
}
// 添加合约信息
void TradeWidget::instrEmit(CTradeSpiImp * t)
{
emit getInstrPush(t);
}
// 添加持仓消息
void TradeWidget::posiEmit(CTradeSpiImp * t, CThostFtdcInvestorPositionField * pPosi, bool bLast)
{
if(pPosi)
{
CThostFtdcInvestorPositionField * posi = new CThostFtdcInvestorPositionField;
::memcpy(posi, pPosi, sizeof(CThostFtdcInvestorPositionField));
emit getPosiPush(t, posi, bLast);
}
else
emit getPosiPush(t, pPosi, bLast);
}
// 添加账户资金消息
void TradeWidget::fundEmit(CTradeSpiImp * t, CThostFtdcTradingAccountField * pFund)
{
CThostFtdcTradingAccountField * fund = new CThostFtdcTradingAccountField;
::memcpy(fund, pFund, sizeof(CThostFtdcTradingAccountField));
emit getFundPush(t, fund);
}
// 添加订单消息
void TradeWidget::orderEmit(CTradeSpiImp * t, CThostFtdcOrderField * pOrder, bool bLast)
{
if(pOrder){
CThostFtdcOrderField * order = new CThostFtdcOrderField;
::memcpy(order, pOrder, sizeof(CThostFtdcOrderField));
if(order->OrderStatus==THOST_FTDC_OST_Canceled)
{
CThostFtdcInputOrderActionField oRsp;
strncpy(oRsp.OrderRef, order->OrderRef, sizeof(oRsp.OrderRef));
checkCancelOrder(&oRsp);
}
emit getOrderPush(t, order, bLast);
}
else
emit getOrderPush(t, pOrder, bLast);
}
// 添加成交消息
void TradeWidget::tradeEmit(CTradeSpiImp * t, CThostFtdcTradeField * pTrade, bool bLast)
{
if(pTrade){
CThostFtdcTradeField * trade = new CThostFtdcTradeField;
::memcpy(trade, pTrade, sizeof(CThostFtdcTradeField));
emit getTradePush(t, trade, bLast);
}
else
emit getTradePush(t, pTrade, bLast);
}
// 订单消息推送
void TradeWidget::orderMessageEmit(QString mes)
{
QString mess = mes;
emit orderMessage(mess);
}
// 添加行情记录
void TradeWidget::addPrice(CThostFtdcDepthMarketDataField *p)
{
CThostFtdcDepthMarketDataField * sIn = quotMap[QString::fromLocal8Bit(p->InstrumentID)];
CThostFtdcDepthMarketDataField * cIn = NULL;
// 判断是否需要更新主力合约列表
CThostFtdcInstrumentField * qins = insMap[QString::fromLocal8Bit(p->InstrumentID)];
if(qins && QString(qins->ProductID) != "")
{
QMap<QString, CThostFtdcInstrumentField *>::const_iterator iter = insMap_zl.find(QString::fromLocal8Bit(qins->ProductID));
CThostFtdcInstrumentField * zlins = iter != insMap_zl.end() ? iter.value():NULL;
if(!zlins)
{
insMap_zl[QString::fromLocal8Bit(qins->ProductID)] = qins;
}
else
{
CThostFtdcDepthMarketDataField * qq = quotMap[QString::fromLocal8Bit(zlins->InstrumentID)];
if(qq && qq->OpenInterest < p->OpenInterest)
insMap_zl[QString::fromLocal8Bit(qins->ProductID)] = qins;
}
}
if(!sIn)
{
quotMap[QString::fromLocal8Bit(p->InstrumentID)] = p;
cIn = p;
if(pTraderSpi->loginFlags && !CSubmit && cIn)
{
slot_showOrderWin(cIn->InstrumentID);
}
return;
}
else
{
cIn = sIn;
//// 判断价格有无变化 没有的话直接return;
//if(sIn->Price-p->Price+0.00001 < 0.0001)
//{
// delete p;
// return;
//}
::memcpy(sIn,p,sizeof(CThostFtdcDepthMarketDataField));
delete p;
}
// 校验订单状态
checkOrderStatus(sIn);
checkFloatingPL(sIn);
if(CSubmit && CSubmit->selectInstr)
{
if(!CSubmit->selectInstr->curInstr)
{
CSubmit->selectInstr->curInstr = qins;
emit floating();
}
else if(strcmp(CSubmit->selectInstr->curInstr->InstrumentID , cIn->InstrumentID) == 0 || cmWidget || pview)
{
emit floating();
}
}
}
// 校验浮动盈亏
void TradeWidget::checkFloatingPL(CThostFtdcDepthMarketDataField * p)
{
QMapIterator<QString, TradeInfo> ti(tradeInfoLst);
while (ti.hasNext())
{
QString key = ti.next().key();
TradeInfo & tti = tradeInfoLst[key];
tti.fund->PositionProfit = 0;
QMapIterator<QString, PosiPloy *> poi(tti.posiLst);
while(poi.hasNext())
{
QString keyP = poi.next().key();
PosiPloy * pPloy = tti.posiLst[keyP];
QList<CThostFtdcInvestorPositionField *> uposi;
if(pPloy)
uposi = pPloy->posi;
if(uposi.size() > 0)
{
// if(keyP == p->InstrumentID && p->LastPrice > 0)
// {
// double yk = insMap[QString::fromLocal8Bit(p->InstrumentID)]->TradeUnit*((p->LastPrice-uposi->BuyPrice)*uposi->BuyQty+(uposi->SellPrice - p->LastPrice)*uposi->SellQty);
// uposi->PositionProfit = yk;
// tti.fund->PositionProfit += yk;
// }
// else
for(int index = 0; index < uposi.size(); index++)
{
tti.fund->PositionProfit += uposi[index]->PositionProfit;
}
}
}
updateStatusBar(tti.fund);
}
}
// 跟踪OCO状态
void TradeWidget::checkOcoStatus(TradeInfo & tf, TThostFtdcOrderRefType OrderRef)
{
for(int oci=0;oci<ocoList.length();oci++)
{
OCOGROUP & ocog = ocoList[oci];
if(::strcmp(ocog.OrderID1, OrderRef) == 0)
{
CThostFtdcOrderField * oco2 = tf.orderLst[ocog.OrderID2];
if(!oco2) continue;
oco2->OrderStatus = THOST_FTDC_OST_Canceled;
ocoList.removeAt(oci);
break;
}
if(::strcmp(ocog.OrderID2, OrderRef) == 0)
{
CThostFtdcOrderField * oco2 = tf.orderLst[ocog.OrderID1];
if(!oco2) continue;
oco2->OrderStatus = THOST_FTDC_OST_Canceled;
ocoList.removeAt(oci);
break;
}
}
}
void TradeWidget::checkOrderStatus(CThostFtdcDepthMarketDataField * cQuot)
{
if(!cQuot) return;
TradeInfo & tf = tradeInfoLst[loginW->userName];
QMap<QString,PosiPloy *>::const_iterator iter = tf.posiLst.find(QString::fromLocal8Bit(cQuot->InstrumentID));
PosiPloy * pploy = iter != tf.posiLst.end() ? iter.value():NULL;
CThostFtdcInstrumentField * ci = insMap[QString::fromLocal8Bit(cQuot->InstrumentID)];
if(!ci) return;
double minMove = ci->PriceTick;
if(!ci) // 缺少合约信息
return;
QMapIterator<QString, CThostFtdcOrderField *> ot(tf.orderLst);
while(ot.hasNext())
{
CThostFtdcOrderField * iti = tf.orderLst[ot.next().key()];
if(!iti) //订单项为空
continue;
// 只处理未触发的订单
if(iti->OrderStatus != THOST_FTDC_OST_NotTouched)
continue;
if(::strcmp(iti->InstrumentID, cQuot->InstrumentID) != 0)
continue;
bool sendFlag = false;
double priceDis = cQuot->LastPrice - iti->LimitPrice;
if(pploy && QString(iti->OrderRef).startsWith("ZZZS")) // 追踪止损
{
if(iti->Direction == THOST_FTDC_D_Sell && cQuot->LastPrice >= pploy->trailPriceu+0.00001)
{
pploy->trigFlag = true; // 多仓追踪止损触发
}
if(iti->Direction == THOST_FTDC_D_Buy && cQuot->LastPrice <= pploy->trailPriceu-0.00001)
{
pploy->trigFlag = true; // 空仓追踪止损触发
}
if(iti->Direction == THOST_FTDC_D_Sell && cQuot->LastPrice - iti->LimitPrice > pploy->points +0.00001 && pploy->trigFlag) // 多仓止损 当前价-止损价 变大
{
iti->LimitPrice = cQuot->LastPrice - pploy->points;
pploy->trailPriceu = iti->LimitPrice + pploy->points;
}
if(iti->Direction == THOST_FTDC_D_Buy && iti->LimitPrice - cQuot->LastPrice > pploy->points - 0.00001 && pploy->trigFlag) // 空仓止损 止损价-当前价 变大
{
iti->LimitPrice = cQuot->LastPrice + pploy->points;
pploy->trailPriceu = iti->LimitPrice-pploy->points;
}
if(iti->Direction == THOST_FTDC_D_Sell && pploy->trigFlag && cQuot->LastPrice <= iti->LimitPrice-0.00001)
{
sendFlag = true; // 多仓止损条件达到
}
if(iti->Direction == THOST_FTDC_D_Buy && pploy->trigFlag && cQuot->LastPrice >= iti->LimitPrice+0.00001)
{
sendFlag = true; // 空仓止损条件达到
}
}
else
{
switch(iti->ContingentCondition)
{
case THOST_FTDC_CC_Immediately:
{
if(priceDis < 0.00001 && priceDis > -0.00001)
{
sendFlag = true;
}
}
break;
case THOST_FTDC_CC_LastPriceGreaterThanStopPrice:
{
if(cQuot->LastPrice > iti->LimitPrice+minMove-0.00001)
{
sendFlag = true;
}
}
break;
case THOST_FTDC_CC_LastPriceGreaterEqualStopPrice:
{
if(cQuot->LastPrice > iti->LimitPrice-0.00001)
{
sendFlag = true;
}
}
break;
case THOST_FTDC_CC_LastPriceLesserThanStopPrice:
{
if(cQuot->LastPrice < iti->LimitPrice-minMove+0.00001)
{
sendFlag = true;
}
}
break;
case THOST_FTDC_CC_LastPriceLesserEqualStopPrice:
{
if(cQuot->LastPrice < iti->LimitPrice+0.00001)
{
sendFlag = true;
}
}
break;
}
}
if(sendFlag)
{
CThostFtdcInputOrderField pInputOrder;
::memset(&pInputOrder,0,sizeof(CThostFtdcInputOrderField));
strncpy(pInputOrder.BrokerID, loginW->m_users.BrokerID, sizeof(pInputOrder.BrokerID));
strncpy(pInputOrder.InvestorID, iti->InvestorID,sizeof(pInputOrder.InvestorID)); /* 投资者号 */
memcpy(pInputOrder.InstrumentID, iti->InstrumentID,sizeof(pInputOrder.InstrumentID));
pInputOrder.Direction = iti->Direction; /* 买卖标志 */
pInputOrder.CombOffsetFlag[0] = iti->CombOffsetFlag[0]; /* 开平标志 */
pInputOrder.CombHedgeFlag[0] = THOST_FTDC_BHF_Speculation;
pInputOrder.VolumeTotalOriginal = iti->VolumeTotalOriginal; /* 数量 */
strncpy(pInputOrder.OrderRef,iti->OrderRef,sizeof(pInputOrder.OrderRef));
pInputOrder.ContingentCondition = THOST_FTDC_CC_Immediately; // 通道只接受‘5’
strncpy(pInputOrder.ExchangeID, iti->ExchangeID,sizeof(pInputOrder.ExchangeID));// 交易所号
if(pploy)
{
pploy->trigFlag = false;
pploy->trailPriceu = 0;
pploy->points = 0;
}
if(iti->Direction == THOST_FTDC_D_Sell)
{
pInputOrder.LimitPrice = cQuot->LowerLimitPrice; /* 跌停价格 */
}
else
{
pInputOrder.LimitPrice = cQuot->UpperLimitPrice; /* 涨停价格 */
}
pInputOrder.OrderPriceType = iti->OrderPriceType;
pInputOrder.TimeCondition = THOST_FTDC_TC_GFD;
pInputOrder.VolumeCondition = THOST_FTDC_VC_AV;
pInputOrder.MinVolume = 1;
pInputOrder.ForceCloseReason = THOST_FTDC_FCC_NotForceClose;
// strcpy( pInputOrder.MacAddress, "fe80::75ef:97de:2366:e490" );
// strcpy( pInputOrder.IPAddress, "10.150.1.23" );
iti->OrderStatus = THOST_FTDC_OST_Canceled;
tf.api->ReqOrderInsert(&pInputOrder, 0); // 录入订单
orderEmit(tf.spi, iti);
checkOcoStatus(tf,iti->OrderRef);
}
}
}
// 添加合约信息
void TradeWidget::addInstr(CTradeSpiImp * t)
{
disconnect(this, SIGNAL(getInstrPush(CTradeSpiImp *)),this, SLOT(addInstr(CTradeSpiImp *)));
insMap = t->tempCons;
QMapIterator<QString, CThostFtdcInstrumentField *> insItr(insMap);
while(insItr.hasNext())
{
QString keyP = insItr.next().key();
CThostFtdcInstrumentField * instr = insMap[keyP];
// 自选合约
// todo 与db配置做判断
// 主力合约 行情接收后做判断
// 上期所
if(::strcmp(instr->ExchangeID, "SHFE") == 0)
{
insMap_sq[keyP] = instr;
}
// 郑商所
if(::strcmp(instr->ExchangeID, "CZCE") == 0)
{
insMap_zs[keyP] = instr;
}
// 大商所
if(::strcmp(instr->ExchangeID, "DCE") == 0)
{
insMap_ds[keyP] = instr;
}
// 中金所
if(::strcmp(instr->ExchangeID, "CFFEX") == 0)
{
insMap_zj[keyP] = instr;
}
// 能源中心
if(::strcmp(instr->ExchangeID, "INE") == 0)
{
insMap_ny[keyP] = instr;
}
}
pQuotApi = CThostFtdcMdApi::CreateFtdcMdApi("md");
quotSpi = new CMdSpiImp(pQuotApi);
if( pQuotApi == NULL || quotSpi == NULL )
{
return;
}
pQuotApi->RegisterSpi(quotSpi);
pQuotApi->RegisterFront((char*)loginW->m_listAddr.at(loginW->serverAddrIndex).marketServ.toStdString().c_str());
pQuotApi->Init( );
connect(this, SIGNAL(getPpricePush(CThostFtdcDepthMarketDataField *)),this, SLOT(addPrice(CThostFtdcDepthMarketDataField *)), Qt::QueuedConnection);
}
// 添加订单记录
void TradeWidget::addOrder(CTradeSpiImp * t, CThostFtdcOrderField * order, bool bLast)
{
if(bLast)
{
for( ; ; )
{
QThread::msleep(1000);
int nRequestIDs = CreateNewRequestID();
CThostFtdcQryTradeField reqInfo = {0};
int ret = pTraderApi->ReqQryTrade(&reqInfo, nRequestIDs);
qInfo() << "ReqQryTrade: " << ret;
if(ret == -2 || ret == -3)
QThread::msleep(100);
else
break;
}
}
if(!order)return;
//mutex.lock();
CThostFtdcOrderField & pOrder = *order;
QMapIterator<QString, TradeInfo> i(tradeInfoLst);
int scale = getScale(pOrder.InstrumentID);
while (i.hasNext())
{
TradeInfo & ti = tradeInfoLst[i.next().key()];
if(ti.spi == t)
{
CThostFtdcOrderField * olt = ti.orderLst[QString::fromLocal8Bit(pOrder.OrderRef)];
if(!olt)
{
if(pOrder.InsertTime[0] == 0)
{
QTime t = QTime::currentTime();
QDate dt = QDate::currentDate();
sprintf(pOrder.InsertDate,"%04d%02d%02d", dt.year(), dt.month(),dt.day());
sprintf(pOrder.InsertTime,"%02d:%02d:%02d", t.hour(), t.minute(),t.second());
}
ti.orderLst[QString::fromLocal8Bit(pOrder.OrderRef)] = order;
}
else
{
::memcpy(olt,order,sizeof(CThostFtdcOrderField));
delete order;
}
break;
}
}
//mutex.unlock();
if(omWidget)
{
omWidget->update();
}
if(CSubmit)
{
CSubmit->update();
}
}
// 添加成交记录
void TradeWidget::addTrade(CTradeSpiImp * t, CThostFtdcTradeField * trade, bool bLast)
{
if(bLast)
{
for( ; ; )
{
QThread::msleep(1000);
int nRequestIDs = CreateNewRequestID();
CThostFtdcQryInvestorPositionField reqInfo = {0};
int ret = pTraderApi->ReqQryInvestorPosition(&reqInfo, nRequestIDs);
qInfo() << "ReqQryInvestorPosition: " << ret;
if(ret == -2 || ret == -3)
QThread::msleep(100);
else
break;
}
}
if(!trade) return;
//mutex.lock();
CThostFtdcTradeField & pTrade = *trade;
QMapIterator<QString, TradeInfo> i(tradeInfoLst);
int scale = getScale(pTrade.InstrumentID);
QString MOid = QString::fromLocal8Bit(pTrade.TradeID).append("_").append(pTrade.OrderRef);
while (i.hasNext())
{
TradeInfo & ti = tradeInfoLst[i.next().key()];
if(ti.spi == t)
{
CThostFtdcTradeField * olt = ti.tradeLst[MOid];
if(!olt)
{
ti.tradeLst[MOid] = trade;
}
else
{
::memcpy(olt,olt,sizeof(CThostFtdcTradeField));
delete trade;
}
break;
}
}
}
void TradeWidget::onTimerReqPos()
{
for( ; ; )
{
QThread::msleep(1000);
int nRequestIDs = CreateNewRequestID();
CThostFtdcQryInvestorPositionField reqInfo = {0};
int ret = pTraderApi->ReqQryInvestorPosition(&reqInfo, nRequestIDs);
qInfo() << "ReqQryInvestorPosition: " << ret;
if(ret == -2 || ret == -3)
QThread::msleep(100);
else
break;
}
}
// 添加账户资金记录
void TradeWidget::addFunds(CTradeSpiImp * t, CThostFtdcTradingAccountField * fund)
{
//mutex.lock();
CThostFtdcTradingAccountField pFund = *fund;
bool updateFlag = false;
QMapIterator<QString, TradeInfo> i(tradeInfoLst);
while (i.hasNext())
{
TradeInfo & ti = tradeInfoLst[i.next().key()];
if(ti.spi == t)
{
::memcpy(ti.fund, &pFund,sizeof(CThostFtdcTradingAccountField));
updateFlag = true;
// 需重新清算该资金账户的浮动盈亏
ti.fund->PositionProfit = 0;
QMapIterator<QString, PosiPloy *> poi(ti.posiLst);
while(poi.hasNext())
{
QString keyP = poi.next().key();
QList<CThostFtdcInvestorPositionField *> uposi;
if(ti.posiLst[keyP])
uposi = ti.posiLst[keyP]->posi;
// if(uposi.size() != 0 && ::memcmp(uposi->InvestorID,fund->AccountID,sizeof(TThostFtdcInvestorIDType)) == 0)
if(uposi.size() > 0)
{
for(int index = 0; index < uposi.size(); index++)
ti.fund->PositionProfit += uposi[index]->PositionProfit;
}
}
updateStatusBar(ti.fund);
break;
}
}
delete fund;
// m_timer.start(5000);
}
void TradeWidget::addPosi(CTradeSpiImp * t, CThostFtdcInvestorPositionField * posi, bool bLast)
{
if(bLast)
{
for( ; ; )
{
QThread::msleep(1000);
int nRequestIDs = CreateNewRequestID();
CThostFtdcQryTradingAccountField reqInfo = {0};
int ret = pTraderApi->ReqQryTradingAccount(&reqInfo, nRequestIDs);
qInfo() << "ReqQryTradingAccount: " << ret;
if(ret == -2 || ret == -3)
QThread::msleep(100);
else
break;
}
}
//mutex.lock();
if(!posi)
return;
CThostFtdcInvestorPositionField & pPosi = *posi;
// 绘制前先订阅
int count = 1;
char **InstrumentID = new char*[count];
InstrumentID[0] = posi->InstrumentID;
pQuotApi->SubscribeMarketData(InstrumentID, 1);
insMap_dy[QString::fromLocal8Bit(posi->InstrumentID)] = insMap[QString::fromLocal8Bit(posi->InstrumentID)];
delete[] InstrumentID;
int scale = getScale(pPosi.InstrumentID);
QMapIterator<QString, TradeInfo> i(tradeInfoLst);
while (i.hasNext())
{
TradeInfo & ti = tradeInfoLst[i.next().key()];
if(ti.spi == t)
{
PosiPloy * oltp = ti.posiLst[posi->InstrumentID];
if(!oltp)
{
PosiPloy * pp = new PosiPloy;