-
Notifications
You must be signed in to change notification settings - Fork 21
/
uiKLine.py.bak
2169 lines (2027 loc) · 103 KB
/
uiKLine.py.bak
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
# -*- coding: utf-8 -*-
"""
Python K线模块,包含十字光标和鼠标键盘交互
Support By 量投科技(http://www.quantdo.com.cn/)
"""
import traceback
import talib as ta
import numpy as np
import pandas as pd
import os
from functools import partial
from collections import deque
from qtpy.QtGui import *
from qtpy.QtCore import *
from qtpy.QtWidgets import *
from qtpy import QtGui,QtCore
from uiCrosshair import Crosshair
from uiCustomMenu import CustomMenu
import pyqtgraph as pg
from qtpy.QtGui import QPainter, QPainterPath, QPen, QColor, QPixmap, QIcon, QBrush, QCursor,QFont
import datetime as dt
import json
import sys
from sys import path
path.append('F:\\vnpy-1.9.0\\examples\\CtaBacktesting')
reload(sys)
sys.setdefaultencoding('utf-8')
#from runBacktesting_WH import calculateDailyResult_to_CSV as strategyDoubleMa_rb9999DailyResult
#from runBacktesting_WH import get_strategy_init_days as strategyDoubleMa_get_strategy_init_days
#from runBacktesting_WH import calculateDailyResult_init as strategyDoubleMa_calculateDailyResult_init
import importlib
import runBacktesting_ShortTermStrategy_RB as STRB
import runBacktesting_ShortTermStrategy_Overhigh_RB as STOVRB
import runBacktesting_RB as DMARB
import runBacktesting_Volatility_RB as VRB
import runBacktesting_Volatility_RB_V1 as VRB1
import runBacktesting_WaiBaoDay_RB as WBDRB
# 字符串转换
#---------------------------------------------------------------------------------------
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
########################################################################
# 键盘鼠标功能
########################################################################
class KeyWraper(QWidget):
"""键盘鼠标功能支持的元类"""
#初始化
#----------------------------------------------------------------------
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.setMouseTracking(True)
#重载方法keyPressEvent(self,event),即按键按下事件方法
#----------------------------------------------------------------------
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Up:
self.onUp()
elif event.key() == QtCore.Qt.Key_Down:
self.onDown()
elif event.key() == QtCore.Qt.Key_Left:
self.onLeft()
elif event.key() == QtCore.Qt.Key_Right:
self.onRight()
elif event.key() == QtCore.Qt.Key_PageUp:
self.onPre()
elif event.key() == QtCore.Qt.Key_PageDown:
self.onNxt()
#重载方法mousePressEvent(self,event),即鼠标点击事件方法
#----------------------------------------------------------------------
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.RightButton:
self.onRClick(event.pos())
elif event.button() == QtCore.Qt.LeftButton:
self.onLClick(event.pos())
#重载方法mouseReleaseEvent(self,event),即鼠标点击事件方法
#----------------------------------------------------------------------
def mouseRelease(self, event):
if event.button() == QtCore.Qt.RightButton:
self.onRRelease(event.pos())
elif event.button() == QtCore.Qt.LeftButton:
self.onLRelease(event.pos())
self.releaseMouse()
#重载方法wheelEvent(self,event),即滚轮事件方法
#----------------------------------------------------------------------
def wheelEvent(self, event):
if event.angleDelta().y() > 0 :
self.onUp()
else:
self.onDown()
pass
return
#重载方法paintEvent(self,event),即拖动事件方法
#----------------------------------------------------------------------
def paintEvent(self, event):
self.onPaint()
# PgDown键
#----------------------------------------------------------------------
def onNxt(self):
pass
# PgUp键
#----------------------------------------------------------------------
def onPre(self):
pass
# 向上键和滚轮向上
#----------------------------------------------------------------------
def onUp(self):
pass
# 向下键和滚轮向下
#----------------------------------------------------------------------
def onDown(self):
pass
# 向左键
#----------------------------------------------------------------------
def onLeft(self):
pass
# 向右键
#----------------------------------------------------------------------
def onRight(self):
pass
# 鼠标左单击
#----------------------------------------------------------------------
def onLClick(self,pos):
pass
# 鼠标右单击
#----------------------------------------------------------------------
def onRClick(self,pos):
pass
# 鼠标左释放
#----------------------------------------------------------------------
def onLRelease(self,pos):
pass
# 鼠标右释放
#----------------------------------------------------------------------
def onRRelease(self,pos):
pass
# 画图
#----------------------------------------------------------------------
def onPaint(self):
pass
########################################################################
# 选择缩放功能支持
########################################################################
class CustomViewBox(pg.ViewBox):
#----------------------------------------------------------------------
def __init__(self, *args, **kwds):
pg.ViewBox.__init__(self, *args, **kwds)
# 拖动放大模式
#self.setMouseMode(self.RectMode)
## 右键自适应
#----------------------------------------------------------------------
def mouseClickEvent(self, ev):
if ev.button() == QtCore.Qt.RightButton:
self.autoRange()
########################################################################
# 时间序列,横坐标支持
########################################################################
class MyStringAxis(pg.AxisItem):
"""时间序列横坐标支持"""
# 初始化
#----------------------------------------------------------------------
def __init__(self, xdict, *args, **kwargs):
pg.AxisItem.__init__(self, *args, **kwargs)
self.minVal = 0
self.maxVal = 0
self.xdict = xdict
self.x_values = np.asarray(xdict.keys())
self.x_strings = xdict.values()
self.setPen(color=(255, 255, 255, 255), width=0.8)
self.setStyle(tickFont = QFont("Roman times",10,QFont.Bold),autoExpandTextSpace=True)
# 更新坐标映射表
#----------------------------------------------------------------------
def update_xdict(self, xdict):
self.xdict.update(xdict)
self.x_values = np.asarray(self.xdict.keys())
self.x_strings = self.xdict.values()
# 将原始横坐标转换为时间字符串,第一个坐标包含日期
#----------------------------------------------------------------------
def tickStrings(self, values, scale, spacing):
strings = []
for v in values:
vs = v * scale
if vs in self.x_values:
vstr = self.x_strings[np.abs(self.x_values-vs).argmin()]
vstr = vstr.strftime('%Y-%m-%d')
else:
vstr = ""
strings.append(vstr)
return strings
########################################################################
# K线图形对象
########################################################################
class CandlestickItem(pg.GraphicsObject):
"""K线图形对象"""
# 初始化
#----------------------------------------------------------------------
def __init__(self, data):
"""初始化"""
pg.GraphicsObject.__init__(self)
# 数据格式: [ (time, open, close, low, high),...]
self.data = data
# 只重画部分图形,大大提高界面更新速度
self.rect = None
self.picture = None
self.setFlag(self.ItemUsesExtendedStyleOption)
# 画笔和画刷
w = 0.4
self.offset = 0
self.low = 0
self.high = 1
self.picture = QtGui.QPicture()
self.pictures = []
self.bPen = pg.mkPen(color=(0, 240, 240, 255), width=w*2)
self.bBrush = pg.mkBrush((0, 240, 240, 255))
self.rPen = pg.mkPen(color=(255, 60, 60, 255), width=w*2)
self.rBrush = pg.mkBrush((255, 60, 60, 255))
self.rBrush.setStyle(Qt.NoBrush)
# 刷新K线
self.generatePicture(self.data)
# 画K线
#----------------------------------------------------------------------
def generatePicture(self,data=None,redraw=False):
"""重新生成图形对象"""
# 重画或者只更新最后一个K线
if redraw:
self.pictures = []
elif self.pictures:
self.pictures.pop()
w = 0.4
bPen = self.bPen
bBrush = self.bBrush
rPen = self.rPen
rBrush = self.rBrush
self.low,self.high = (np.min(data['low']),np.max(data['high'])) if len(data)>0 else (0,1)
npic = len(self.pictures)
for (t, open0, close0, low0, high0) in data:
if t >= npic:
picture = QtGui.QPicture()
p = QtGui.QPainter(picture)
# 下跌蓝色(实心), 上涨红色(空心)
pen,brush,pmin,pmax = (bPen,bBrush,close0,open0)\
if open0 > close0 else (rPen,rBrush,open0,close0)
p.setPen(pen)
p.setBrush(brush)
# 画K线方块和上下影线
if open0 == close0:
p.drawLine(QtCore.QPointF(t-w,open0), QtCore.QPointF(t+w, close0))
else:
p.drawRect(QtCore.QRectF(t-w, open0, w*2, close0-open0))
if pmin > low0:
p.drawLine(QtCore.QPointF(t,low0), QtCore.QPointF(t, pmin))
if high0 > pmax:
p.drawLine(QtCore.QPointF(t,pmax), QtCore.QPointF(t, high0))
p.end()
self.pictures.append(picture)
# 手动重画
#----------------------------------------------------------------------
def update(self):
if not self.scene() is None:
self.scene().update()
# 自动重画
#----------------------------------------------------------------------
def paint(self, painter, opt, w):
rect = opt.exposedRect
xmin,xmax = (max(0,int(rect.left())),min(int(len(self.pictures)),int(rect.right())))
if not self.rect == (rect.left(),rect.right()) or self.picture is None:
self.rect = (rect.left(),rect.right())
self.picture = self.createPic(xmin,xmax)
self.picture.play(painter)
elif not self.picture is None:
self.picture.play(painter)
# 缓存图片
#----------------------------------------------------------------------
def createPic(self,xmin,xmax):
picture = QPicture()
p = QPainter(picture)
[pic.play(p) for pic in self.pictures[xmin:xmax]]
p.end()
return picture
# 定义边界
#----------------------------------------------------------------------
def boundingRect(self):
return QtCore.QRectF(0,self.low,len(self.pictures),(self.high-self.low))
#----------------------------------------------------------------------
def hide(self):
self.parent.hide()
pass
########################################################################
class KLineWidget(KeyWraper):
"""用于显示价格走势图"""
# 窗口标识
clsId = 0
# 保存K线数据的列表和Numpy Array对象
listBar = []
listVol = []
listHigh = []
listLow = []
KLINE_DATE = []
KLINE_OPEN = []
KLINE_HIGH = []
KLINE_LOW = []
KLINE_SHORT_TERM_LOW = []
KLINE_SHORT_TERM_HIGH = []
KLINE_SHORT_TERM_LIST_ALL=[]
KLINE_SHORT_TERM_LIST_FIRST=[]
KLINE_SHORT_TERM_LIST_LIMIT=[]
KLINE_WAIBAORI=[]
KLINE_GJR_BUY=[]
KLINE_GJR_SELL=[]
listClose = []
listSig = []
listOpenInterest = []
arrows = []
KLINE_SHORT_TERM_LIST_ALL_arrows = []
KLINE_SHORT_TERM_LIST_FIRST_arrows = []
KLINE_SHORT_TERM_LIST_LIMIT_arrows = []
KLINE_WAI_BAO_RI_arrows = []
KLINE_GJR_BUY_arrows = []
KLINE_GJR_SELL_arrows = []
curves = []
KLINE_SHORT_TERM_LIST_ALL_curves = []
KLINE_SHORT_TERM_LIST_FIRST_curves = []
KLINE_SHORT_TERM_LIST_LIMIT_curves = []
listSig_deal_DIRECTION = []
listSig_deal_OFFSET = []
KLINE_CLOSE=[]
start_date=[] #[20090327开始日期,列表的位置]
end_date=[] #[20181127结束日期,结束的位置]
KLINE_show =True
MA_SHORT_show =False
MA_LONG_show =False
listbarshow =False
SHORT_TERM_SHOW =False
SHORT_TERM_SHOW_FIRST=False
SHORT_TERM_SHOW_LIMIT=False
SHORT_TERM_SHOW_ALL =False
WAIBAORI_SHOW =False
GJRBUY_SHOW =False
signal_show =True
# 是否完成了历史数据的读取
initCompleted = False
#----------------------------------------------------------------------
def __init__(self,parent=None):
"""Constructor"""
self.parent = parent
super(KLineWidget, self).__init__(parent)
# 当前序号
self.index = None # 下标
self.countK = 60 # 显示的K线范围
KLineWidget.clsId += 1
self.windowId = str(KLineWidget.clsId)
# 缓存数据
self.datas = []
self.listBar = []
self.listbarshow= True
self.listVol = []
self.listHigh = []
self.listLow = []
self.listSig = []
self.listOpenInterest = []
self.arrows = []
self.curves = []
self.listSig_deal_DIRECTION = []
self.listSig_deal_OFFSET = []
self.KLINE_CLOSE=[]
self.MA_SHORT_real=[]
self.MA_LONG_real=[]
self.start_time=[]
self.MA_SHORT_show=False
self.MA_LONG_show=False
self.SHORT_TERM_SHOW=False
self.SHORT_TERM_SHOW_FIRST=False
self.SHORT_TERM_SHOW_LIMIT=False
self.SHORT_TERM_SHOW_ALL=False
self.signal_show=False
self.cur_jsonname=u'json\\uiKLine_startpara.json'
self.SP_signal='close'
self.BP_signal='close'
self.dailyresult_path = ''
self.dailydata_path = ''
# 所有K线上信号图
self.allColor = deque(['blue','green','yellow','white'])
self.sigData = {}
self.sigColor = {}
self.sigPlots = {}
# 所副图上信号图
self.allSubColor = deque(['blue','green','yellow','white'])
self.subSigData = {}
self.subSigColor = {}
self.subSigPlots = {}
# 初始化完成
self.initCompleted = False
# 调用函数
self.initUi()
self.menu= CustomMenu(self)
#----------------------------------------------------------------------
# 初始化相关
#----------------------------------------------------------------------
def initUi(self):
"""初始化界面"""
self.setWindowTitle(u'K线工具')
# 主图
self.pw = pg.PlotWidget()
# 界面布局
self.lay_KL = pg.GraphicsLayout(border=(100,100,100))
self.lay_KL.setContentsMargins(10, 10, 10, 10)
self.lay_KL.setSpacing(0)
self.lay_KL.setBorder(color=(255, 0, 0, 255), width=0.8)
self.lay_KL.setZValue(0)
self.KLtitle = self.lay_KL.addLabel(u'')
self.pw.setCentralItem(self.lay_KL)
# 设置横坐标
xdict = {}
self.axisTime = MyStringAxis(xdict, orientation='bottom')
# 初始化子图
self.initplotKline()
self.initplotVol()
self.initplotOI()
# 注册十字光标
self.crosshair = Crosshair(self.pw,self)
# 设置界面
self.vb = QVBoxLayout()
self.vb.addWidget(self.pw)
self.setLayout(self.vb)
# 初始化完成
self.initCompleted = True
#----------------------------------------------------------------------
def makePI(self,name):
"""生成PlotItem对象"""
vb = CustomViewBox()
plotItem = pg.PlotItem(viewBox = vb, name=name ,axisItems={'bottom': self.axisTime})
plotItem.setMenuEnabled(False)
plotItem.setClipToView(True)
plotItem.hideAxis('left')
plotItem.showAxis('right')
plotItem.setDownsampling(mode='peak')
plotItem.setRange(xRange = (0,1),yRange = (0,1))
plotItem.getAxis('right').setWidth(30)
plotItem.getAxis('right').setStyle(tickFont = QFont("Roman times",10,QFont.Bold))
plotItem.getAxis('right').setPen(color=(255, 0, 0, 255), width=0.8)
plotItem.showGrid(True,True)
plotItem.hideButtons()
return plotItem
#----------------------------------------------------------------------
def initplotVol(self):
"""初始化成交量子图"""
self.pwVol = self.makePI('_'.join([self.windowId,'PlotVOL']))
self.volume = CandlestickItem(self.listVol)
self.pwVol.addItem(self.volume)
self.pwVol.setMaximumHeight(50)
self.pwVol.setXLink('_'.join([self.windowId,'PlotOI']))
self.pwVol.hideAxis('bottom')
self.lay_KL.nextRow()
self.lay_KL.addItem(self.pwVol)
#----------------------------------------------------------------------
def initplotKline(self):
"""初始化K线子图以及指标子图"""
self.pwKL = self.makePI('_'.join([self.windowId,'PlotKL']))
self.candle = CandlestickItem(self.listBar)
self.pwKL.addItem(self.candle)
self.KLINEOI_CLOSE = pg.PlotCurveItem(pen=({'color': "w", 'width': 1}))
self.pwKL.addItem(self.KLINEOI_CLOSE)
self.KLINEOI_CLOSE.hide()
self.MA_SHORTOI = pg.PlotCurveItem(pen=({'color': "r", 'width': 1}))
self.pwKL.addItem(self.MA_SHORTOI)
self.MA_SHORTOI.hide()
self.MA_LONGOI = pg.PlotCurveItem(pen=({'color': "r", 'width': 1,'dash':[3, 3, 3, 3]}))
self.pwKL.addItem(self.MA_LONGOI)
self.MA_LONGOI.hide()
self.start_date_Line = pg.InfiniteLine(angle=90, movable=False,pen=({'color': [255, 255, 255, 100], 'width': 0.5}))
self.pwKL.addItem(self.start_date_Line)
self.end_date_Line = pg.InfiniteLine(angle=90,movable=False,pen=({'color': [255, 255, 0, 100], 'width': 0.5}))
self.pwKL.addItem(self.end_date_Line)
self.pwKL.setMinimumHeight(350)
self.pwKL.setXLink('_'.join([self.windowId,'PlotOI']))
self.pwKL.hideAxis('bottom')
self.lay_KL.nextRow()
self.lay_KL.addItem(self.pwKL)
#----------------------------------------------------------------------
def initplotOI(self):
"""初始化持仓量子图"""
self.pwOI = self.makePI('_'.join([self.windowId,'PlotOI']))
self.curveOI = self.pwOI.plot()
self.pwOI.setMaximumHeight(50)
self.lay_KL.nextRow()
self.lay_KL.addItem(self.pwOI)
pass
#----------------------------------------------------------------------
def reinit(self,pingzhongname,filename,dailyresultname,jsonname):
"""更换品种,重新初始化"""
# K线界面
ui.loadKLineSetting(jsonname)
ui.KLtitle.setText(pingzhongname+' '+ui.StrategyName ,size='10pt',color='FFFF00')
ui.loadData(pd.DataFrame.from_csv(filename))
ui.loadData_listsig(pd.DataFrame.from_csv(dailyresultname))
# 初始化界面显示
self.SHORT_TERM_SHOW_ALL =False
self.SHORT_TERM_SHOW_FIRST =False
self.SHORT_TERM_SHOW_LIMIT =False
ui.initIndicator(u'MA SHORT')
ui.initIndicator(u'MA LONG')
ui.initIndicator(u'KLINE')
ui.initIndicator(u'SHORT TERM(First)')
ui.initIndicator(u'SHORT TERM(All)')
ui.initIndicator(u'SHORT TERM(Limit)')
if ui.signal_show == True :
ui.initIndicator(u'信号显示')
else:
ui.initIndicator(u'信号隐藏')
ui.refreshAll()
#----------------------------------------------------------------------
# 画图相关
#----------------------------------------------------------------------
def plotVol(self,redraw=False,xmin=0,xmax=-1):
"""重画成交量子图"""
if self.initCompleted:
self.volume.generatePicture(self.listVol[xmin:xmax],redraw) # 画成交量子图
#----------------------------------------------------------------------
def plotKline(self,redraw=False,xmin=0,xmax=-1):
"""重画K线子图"""
if self.initCompleted:
self.candle.generatePicture(self.listBar[xmin:xmax],redraw) # 画K线
self.KLINEOI_CLOSE.setData(np.array(self.KLINE_CLOSE)) #画收盘价曲线
self.plotMark() # 显示开平仓信号位置
#----------------------------------------------------------------------
def plotMA_SHORT(self):
"""重画MA_SHORT """
if self.initCompleted:
self.MA_SHORTOI.setData(np.array(self.MA_SHORT_real))#画MA_SHORT
self.refresh()
#----------------------------------------------------------------------
def plotMA_LONG(self):
"""重画MA_LONG """
if self.initCompleted:
self.MA_LONGOI.setData(np.array(self.MA_LONG_real))#画MA_LONG
self.refresh()
#----------------------------------------------------------------------
def plot_startdate(self,pos):
"""重画起始日期 """
if self.initCompleted:
self.start_date_Line.setPos(pos)
#----------------------------------------------------------------------
def plot_enddate(self,pos):
"""重画起始日期 """
if self.initCompleted:
self.end_date_Line.setPos(pos)
#----------------------------------------------------------------------
def plotOI(self,xmin=0,xmax=-1):
"""重画持仓量子图"""
if self.initCompleted:
self.curveOI.setData(np.append(self.listOpenInterest[xmin:xmax],0), pen='w', name="OpenInterest")
#----------------------------------------------------------------------
def addSig(self,sig,main=True):
"""新增信号图"""
if main:
if sig in self.sigPlots:
self.pwKL.removeItem(self.sigPlots[sig])
self.sigPlots[sig] = self.pwKL.plot()
self.sigColor[sig] = self.allColor[0]
self.allColor.append(self.allColor.popleft())
else:
if sig in self.subSigPlots:
self.pwOI.removeItem(self.subSigPlots[sig])
self.subSigPlots[sig] = self.pwOI.plot()
self.subSigColor[sig] = self.allSubColor[0]
self.allSubColor.append(self.allSubColor.popleft())
#----------------------------------------------------------------------
def showSig(self,datas,main=True,clear=False):
"""刷新信号图"""
if clear:
self.clearSig(main)
if datas and not main:
sigDatas = np.array(datas.values()[0])
self.listOpenInterest = sigDatas
self.datas['openInterest'] = sigDatas
self.plotOI(0,len(sigDatas))
if main:
for sig in datas:
self.addSig(sig,main)
self.sigData[sig] = datas[sig]
self.sigPlots[sig].setData(np.append(datas[sig],0), pen=self.sigColor[sig][0], name=sig)
else:
for sig in datas:
self.addSig(sig,main)
self.subSigData[sig] = datas[sig]
self.subSigPlots[sig].setData(np.append(datas[sig],0), pen=self.subSigColor[sig][0], name=sig)
#----------------------------------------------------------------------
def plotMark(self):
"""显示开平仓信号"""
# 检查是否有数据
if len(self.datas)==0:
return
for arrow in self.arrows:
self.pwKL.removeItem(arrow)
for curve in self.curves:
self.pwKL.removeItem(curve)
# 画买卖信号
lastbk_x=-1 #上一个买开的x
lastbk_y=-1 #上一个买开的y
lastsk_x=-1 #上一个卖开的x
lastsk_y=-1 #上一个卖开的y
for i in range(len(self.listSig_deal_DIRECTION)):
# 无信号
if cmp(self.listSig_deal_DIRECTION[i] , '-')== 0 or cmp(self.listSig_deal_OFFSET[i] , '-') == 0:
continue
# 买开信号
elif cmp(self.listSig_deal_DIRECTION[i] , '多')==0 and cmp(self.listSig_deal_OFFSET[i] , '开仓')==0 :
arrow = pg.ArrowItem(pos=(i, self.datas[i]['low']), size=7,tipAngle=55,tailLen=3,tailWidth=4, angle=90, brush=(255, 0, 0),pen=({'color': "r", 'width': 1}))
lastbk_x = i
lastbk_y = self.datas[i]['close']
# 卖平信号
elif cmp(self.listSig_deal_DIRECTION[i] , '空')==0 and cmp(self.listSig_deal_OFFSET[i] , '平仓')==0 :
arrow = pg.ArrowItem(pos=(i, self.datas[i]['high']),size=7,tipAngle=55,tailLen=3,tailWidth=4 ,angle=-90, brush=(0, 0, 0),pen=({'color': "g", 'width': 1}))
if lastbk_x !=-1:
curve = pg.PlotCurveItem(x=np.array([lastbk_x,i]),y=np.array([lastbk_y,self.datas[i][self.SP_signal]]),name='duo',pen=({'color': "r", 'width': 3}))
self.pwKL.addItem(curve)
self.curves.append(curve)
lastbk_x = -1
# 卖开信号
elif cmp(self.listSig_deal_DIRECTION[i] , '空')==0 and cmp(self.listSig_deal_OFFSET[i] , '开仓')==0 :
arrow = pg.ArrowItem(pos=(i, self.datas[i]['high']),size=7,tipAngle=55,tailLen=3,tailWidth=4,angle=-90, brush=(0, 255, 0),pen=({'color': "g", 'width': 1}))
lastsk_x = i
lastsk_y = self.datas[i]['close']
# 买平信号
elif cmp(self.listSig_deal_DIRECTION[i] , '多')==0 and cmp(self.listSig_deal_OFFSET[i] , '平仓')==0 :
arrow = pg.ArrowItem(pos=(i, self.datas[i]['low']),size=7,tipAngle=55,tailLen=3,tailWidth=4 ,angle=90, brush=(0, 0, 0),pen=({'color': "r", 'width': 1}))
if lastsk_x !=-1:
curve = pg.PlotCurveItem(x=np.array([lastsk_x,i]),y=np.array([lastsk_y,self.datas[i][self.BP_signal]]),pen=({'color': "g", 'width': 3}))
self.pwKL.addItem(curve)
self.curves.append(curve)
lastsk_x = -1
self.pwKL.addItem(arrow)
self.arrows.append(arrow)
#----------------------------------------------------------------------
def plotIndex_LIMIT (self):
"""画指标"""
# 检查是否有数据
if len(self.KLINE_SHORT_TERM_LIST_LIMIT)==0 :
self.refresh()
return
for arrow in self.KLINE_SHORT_TERM_LIST_LIMIT_arrows:
self.pwKL.removeItem(arrow)
for curves in self.KLINE_SHORT_TERM_LIST_LIMIT_curves:
self.pwKL.removeItem(curves)
for i in range(len(self.KLINE_SHORT_TERM_LIST_LIMIT)):
if self.KLINE_SHORT_TERM_LIST_LIMIT[i] == 1:
arrow = pg.ArrowItem(pos=(i, self.datas[i]['low']), size=7,tipAngle=55,tailLen=3,tailWidth=4, angle=90, brush=(34, 139, 34),pen=({'color': "228B22", 'width': 1}))
self.pwKL.addItem(arrow)
self.KLINE_SHORT_TERM_LIST_LIMIT_arrows.append(arrow)
if self.KLINE_SHORT_TERM_LIST_LIMIT[i] == 2:
arrow = pg.ArrowItem(pos=(i, self.datas[i]['high']),size=7,tipAngle=55,tailLen=3,tailWidth=4 ,angle=-90, brush=(34, 139, 34),pen=({'color': "228B22", 'width': 1}))
self.pwKL.addItem(arrow)
self.KLINE_SHORT_TERM_LIST_LIMIT_arrows.append(arrow)
last_x=-1 #上一个x
last_y=-1 #上一个y
last_v=-1
for i in range(len(self.KLINE_SHORT_TERM_LIST_LIMIT)):
if self.KLINE_SHORT_TERM_LIST_LIMIT[i] != 0 :
if last_x!=-1 and last_y!=-1 and last_v!=self.KLINE_SHORT_TERM_LIST_LIMIT[i] and\
((last_v == 1 and self.KLINE_SHORT_TERM_LIST_LIMIT[i] == 2) and self.KLINE_LOW[last_x]<self.KLINE_HIGH[i]) or\
((last_v == 2 and self.KLINE_SHORT_TERM_LIST_LIMIT[i] == 1) and self.KLINE_HIGH[last_x]>self.KLINE_LOW[i]):
curve = pg.PlotCurveItem(x=np.array([last_x,i]),y=np.array([last_y,self.datas[i]['low'] if self.KLINE_SHORT_TERM_LIST_LIMIT[i]==1 else self.datas[i]['high']]),name='duo',pen=({'color': "228B22", 'width': 1}))
self.pwKL.addItem(curve)
self.KLINE_SHORT_TERM_LIST_LIMIT_curves.append(curve)
last_x =i
if self.KLINE_SHORT_TERM_LIST_LIMIT[i] ==1 :
last_y=self.datas[i]['low']
elif self.KLINE_SHORT_TERM_LIST_LIMIT[i] ==2 :
last_y=self.datas[i]['high']
last_v=self.KLINE_SHORT_TERM_LIST_LIMIT[i]
#----------------------------------------------------------------------
def plotIndex_ALL (self):
"""画指标"""
# 检查是否有数据
if len(self.KLINE_SHORT_TERM_LIST_ALL)==0 :
self.refresh()
return
for arrow in self.KLINE_SHORT_TERM_LIST_ALL_arrows:
self.pwKL.removeItem(arrow)
for curves in self.KLINE_SHORT_TERM_LIST_ALL_curves:
self.pwKL.removeItem(curves)
for i in range(len(self.KLINE_SHORT_TERM_LIST_ALL)):
if self.KLINE_SHORT_TERM_LIST_ALL[i] == 1:
arrow = pg.ArrowItem(pos=(i, self.datas[i]['low']), size=7,tipAngle=55,tailLen=3,tailWidth=4, angle=90, brush=(225, 0, 225),pen=({'color': "FF00FF", 'width': 1}))
self.pwKL.addItem(arrow)
self.KLINE_SHORT_TERM_LIST_ALL_arrows.append(arrow)
if self.KLINE_SHORT_TERM_LIST_ALL[i] == 2:
arrow = pg.ArrowItem(pos=(i, self.datas[i]['high']),size=7,tipAngle=55,tailLen=3,tailWidth=4 ,angle=-90, brush=(225, 0, 225),pen=({'color': "FF00FF", 'width': 1}))
self.pwKL.addItem(arrow)
self.KLINE_SHORT_TERM_LIST_ALL_arrows.append(arrow)
last_x=-1 #上一个x
last_y=-1 #上一个y
last_v=-1
for i in range(len(self.KLINE_SHORT_TERM_LIST_ALL)):
if self.KLINE_SHORT_TERM_LIST_ALL[i] != 0 :
if last_x!=- 1 and last_y!=-1 and \
((last_v == 1 and self.KLINE_SHORT_TERM_LIST_ALL[i] == 2) and self.KLINE_LOW[last_x]<self.KLINE_HIGH[i]) or \
((last_v == 2 and self.KLINE_SHORT_TERM_LIST_ALL[i] == 1) and self.KLINE_HIGH[last_x]>self.KLINE_LOW[i]) or \
((last_v == 1 and self.KLINE_SHORT_TERM_LIST_ALL[i] == 1)) or \
((last_v == 2 and self.KLINE_SHORT_TERM_LIST_ALL[i] == 2)) :
curve = pg.PlotCurveItem(x=np.array([last_x,i]),y=np.array([last_y,self.datas[i]['low'] if self.KLINE_SHORT_TERM_LIST_ALL[i]==1 else self.datas[i]['high']]),name='duo',pen=({'color': "FF00FF", 'width': 1}))
self.pwKL.addItem(curve)
self.KLINE_SHORT_TERM_LIST_ALL_curves.append(curve)
last_x =i
if self.KLINE_SHORT_TERM_LIST_ALL[i] ==1 :
last_y=self.datas[i]['low']
elif self.KLINE_SHORT_TERM_LIST_ALL[i] ==2 :
last_y=self.datas[i]['high']
last_v=self.KLINE_SHORT_TERM_LIST_ALL[i]
#----------------------------------------------------------------------
def plotIndex_FIRST (self):
"""画指标"""
# 检查是否有数据
if len(self.KLINE_SHORT_TERM_LIST_FIRST)==0 :
self.refresh()
return
for arrow in self.KLINE_SHORT_TERM_LIST_FIRST_arrows:
self.pwKL.removeItem(arrow)
for curves in self.KLINE_SHORT_TERM_LIST_FIRST_curves:
self.pwKL.removeItem(curves)
for i in range(len(self.KLINE_SHORT_TERM_LIST_FIRST)):
if self.KLINE_SHORT_TERM_LIST_FIRST[i] == 1:
arrow = pg.ArrowItem(pos=(i, self.datas[i]['low']), size=7,tipAngle=55,tailLen=3,tailWidth=4, angle=90, brush=(225, 255, 0),pen=({'color': "FFFF00", 'width': 1}))
self.pwKL.addItem(arrow)
self.KLINE_SHORT_TERM_LIST_FIRST_arrows.append(arrow)
if self.KLINE_SHORT_TERM_LIST_FIRST[i] == 2:
arrow = pg.ArrowItem(pos=(i, self.datas[i]['high']),size=7,tipAngle=55,tailLen=3,tailWidth=4 ,angle=-90, brush=(225, 255, 0),pen=({'color': "FFFF00", 'width': 1}))
self.pwKL.addItem(arrow)
self.KLINE_SHORT_TERM_LIST_FIRST_arrows.append(arrow)
last_x=-1 #上一个x
last_y=-1 #上一个y
last_v=-1
for i in range(len(self.KLINE_SHORT_TERM_LIST_FIRST)):
if self.KLINE_SHORT_TERM_LIST_FIRST[i] != 0 :
if last_x!=-1 and last_y!=-1 and last_v!=self.KLINE_SHORT_TERM_LIST_FIRST[i] and\
((last_v == 1 and self.KLINE_SHORT_TERM_LIST_FIRST[i] == 2) and self.KLINE_LOW[last_x]<self.KLINE_HIGH[i]) or\
((last_v == 2 and self.KLINE_SHORT_TERM_LIST_FIRST[i] == 1) and self.KLINE_HIGH[last_x]>self.KLINE_LOW[i]):
curve = pg.PlotCurveItem(x=np.array([last_x,i]),y=np.array([last_y,self.datas[i]['low'] if self.KLINE_SHORT_TERM_LIST_FIRST[i]==1 else self.datas[i]['high']]),name='duo',pen=({'color': "FFFF00", 'width': 1}))
self.pwKL.addItem(curve)
self.KLINE_SHORT_TERM_LIST_FIRST_curves.append(curve)
last_x =i
if self.KLINE_SHORT_TERM_LIST_FIRST[i] ==1 :
last_y=self.datas[i]['low']
elif self.KLINE_SHORT_TERM_LIST_FIRST[i] ==2 :
last_y=self.datas[i]['high']
last_v=self.KLINE_SHORT_TERM_LIST_FIRST[i]
#----------------------------------------------------------------------
def plot_WAIBAORI(self):
"""画外包日箭头"""
# 检查是否有数据
if len(self.KLINE_WAIBAORI)==0 :
self.refresh()
return
for arrow in self.KLINE_WAI_BAO_RI_arrows:
self.pwKL.removeItem(arrow)
for i in range(len(self.KLINE_WAIBAORI)):
if self.KLINE_WAIBAORI[i] == 1:
arrow = pg.ArrowItem(pos=(i, self.datas[i]['low']-100), size=7,tipAngle=55,tailLen=3,tailWidth=4, angle=90, brush=(255, 255, 0),pen=({'color': "FF0000", 'width': 1}))
self.pwKL.addItem(arrow)
self.KLINE_WAI_BAO_RI_arrows.append(arrow)
#----------------------------------------------------------------------
def plot_GJR_BUY(self):
"""画攻击日买入箭头"""
# 检查是否有数据
if len(self.KLINE_GJR_BUY)==0 :
self.refresh()
return
for arrow in self.KLINE_GJR_BUY_arrows:
self.pwKL.removeItem(arrow)
for i in range(len(self.KLINE_GJR_BUY)):
if self.KLINE_GJR_BUY[i] == 1:
arrow = pg.ArrowItem(pos=(i, self.datas[i]['low']-50), size=7,tipAngle=55,tailLen=3,tailWidth=4, angle=90, brush=("B03060"),pen=({'color': "B03060", 'width': 1}))
self.pwKL.addItem(arrow)
self.KLINE_GJR_BUY_arrows.append(arrow)
#----------------------------------------------------------------------
def plot_GJR_SELL(self):
"""画攻击日卖出箭头"""
# 检查是否有数据
if len(self.KLINE_GJR_SELL)==0 :
self.refresh()
return
for arrow in self.KLINE_GJR_SELL_arrows:
self.pwKL.removeItem(arrow)
for i in range(len(self.KLINE_GJR_SELL)):
if self.KLINE_GJR_SELL[i] == 1:
arrow = pg.ArrowItem(pos=(i, self.datas[i]['high']+50), size=7,tipAngle=55,tailLen=3,tailWidth=4, angle=-90, brush=("C0FF3E"),pen=({'color': "C0FF3E", 'width': 1}))
self.pwKL.addItem(arrow)
self.KLINE_GJR_SELL_arrows.append(arrow)
#----------------------------------------------------------------------
def plot_after_runStrategy(self):
"""执行策略之后,根据显示状态重画其他指标"""
if self.KLINE_show ==True:
self.KLINEOI_CLOSE.hide()
else:
self.KLINEOI_CLOSE.show()
if self.MA_LONG_show ==True:
self.MA_LONGOI.show()
else:
self.MA_LONGOI.hide()
if self.MA_SHORT_show ==True:
self.MA_SHORTOI.show()
else:
self.MA_SHORTOI.hide()
if not self.SHORT_TERM_SHOW_FIRST :
for arrow in self.KLINE_SHORT_TERM_LIST_FIRST_arrows:
arrow.show()
for curve in self.KLINE_SHORT_TERM_LIST_FIRST_curves:
curve.show()
else:
for arrow in self.KLINE_SHORT_TERM_LIST_FIRST_arrows:
arrow.hide()
for curve in self.KLINE_SHORT_TERM_LIST_FIRST_curves:
curve.hide()
if not self.SHORT_TERM_SHOW_LIMIT :
for arrow in self.KLINE_SHORT_TERM_LIST_LIMIT_arrows:
arrow.show()
for curve in self.KLINE_SHORT_TERM_LIST_LIMIT_curves:
curve.show()
else:
for arrow in self.KLINE_SHORT_TERM_LIST_LIMIT_arrows:
arrow.hide()
for curve in self.KLINE_SHORT_TERM_LIST_LIMIT_curves:
curve.hide()
if not self.SHORT_TERM_SHOW_ALL :
for arrow in self.KLINE_SHORT_TERM_LIST_ALL_arrows:
arrow.show()
for curve in self.KLINE_SHORT_TERM_LIST_ALL_curves:
curve.show()
else:
for arrow in self.KLINE_SHORT_TERM_LIST_ALL_arrows:
arrow.hide()
for curve in self.KLINE_SHORT_TERM_LIST_ALL_curves:
curve.hide()
#----------------------------------------------------------------------
def updateAll(self):
"""
手动更新所有K线图形,K线播放模式下需要
"""
datas = self.datas
self.volume.pictrue = None
self.candle.pictrue = None
self.volume.update()
self.candle.update()
def update(view,low,high):
vRange = view.viewRange()
xmin = max(0,int(vRange[0][0]))
xmax = max(0,int(vRange[0][1]))
try:
xmax = min(xmax,len(datas)-1)
except:
xmax = xmax
if len(datas)>0 and xmax > xmin:
ymin = min(datas[xmin:xmax][low])
ymax = max(datas[xmin:xmax][high])
view.setRange(yRange = (ymin,ymax))
else:
view.setRange(yRange = (0,1))
update(self.pwKL.getViewBox(),'low','high')
update(self.pwVol.getViewBox(),'volume','volume')
#----------------------------------------------------------------------
def plotAll(self,redraw=True,xMin=0,xMax=-1):
"""
重画所有界面
redraw :False=重画最后一根K线; True=重画所有
xMin,xMax : 数据范围
"""
xMax = len(self.datas)-1 if xMax < 0 else xMax
#self.countK = xMax-xMin
#self.index = int((xMax+xMin)/2)
self.pwOI.setLimits(xMin=xMin,xMax=xMax)
self.pwKL.setLimits(xMin=xMin,xMax=xMax)
self.pwVol.setLimits(xMin=xMin,xMax=xMax)
self.plotKline(redraw,xMin,xMax) # K线图
self.plot_startdate(self.start_date[1])
self.plot_enddate(self.end_date[1])
self.plotVol(redraw,xMin,xMax) # K线副图,成交量
self.plotOI(0,len(self.datas)) # K线副图,持仓量
self.refresh()
#----------------------------------------------------------------------
def restart_program(self):
python = sys.executable
os.execl(python, python, * sys.argv)
#----------------------------------------------------------------------
def refresh(self):
"""
刷新三个子图的现实范围
"""
datas = self.datas
minutes = int(self.countK/2)
xmin = max(0,self.index-minutes)
try:
xmax = min(xmin+2*minutes,len(self.datas)-1) if self.datas else xmin+2*minutes
except:
xmax = xmin+2*minutes
self.pwOI.setRange(xRange = (xmin,xmax))
self.pwKL.setRange(xRange = (xmin,xmax))
self.pwVol.setRange(xRange = (xmin,xmax))
#----------------------------------------------------------------------
# 快捷键与鼠标相关
#----------------------------------------------------------------------
def onNxt(self):
"""跳转到下一个开平仓点"""
if len(self.listSig)>0 and not self.index is None:
datalen = len(self.listSig)
if self.index < datalen-2 : self.index+=1
while self.index < datalen-2 and cmp(self.listSig_deal_DIRECTION[self.index] , '-')== 0:
self.index+=1