forked from Skinok/backtrader-pyqt-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfinplotWindow.py
353 lines (262 loc) · 12.6 KB
/
finplotWindow.py
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
import sys, os
from pyqtgraph.graphicsItems.LegendItem import LegendItem
from indicators import ichimoku
sys.path.append('../finplot')
import finplot as fplt
import backtrader as bt
from pyqtgraph import mkColor, mkBrush
class FinplotWindow():
def __init__(self, dockArea, dockChart, interface):
self.dockArea = dockArea
self.dockChart = dockChart
self.interface = interface
self.IndIchimokuActivated = False
self.IndRSIActivated = False
self.IndStochasticActivated = False
self.IndMAActivated = False
self.IndVolumesActivated = False
pass
#########
# Prepare the plot widgets
#########
def createPlotWidgets(self):
# fin plot
self.ax0, self.ax1, self.ax2, self.axPnL = fplt.create_plot_widget(master=self.dockArea, rows=4, init_zoom_periods=200)
self.dockArea.axs = [self.ax0, self.ax1, self.ax2, self.axPnL]
self.dockChart.addWidget(self.ax0.ax_widget, 1, 0, 1, 1)
self.dockChart.addWidget(self.ax1.ax_widget, 2, 0, 1, 1)
self.dockChart.addWidget(self.ax2.ax_widget, 3, 0, 1, 1)
self.interface.strategyResultsUI.ResultsTabWidget.widget(1).layout().addWidget(self.axPnL.ax_widget)
#self.dockChart.addWidget(self.axPnL.ax_widget, 4, 0, 1, 1)
self.ax1.ax_widget.hide()
self.ax2.ax_widget.hide()
self.axPnL.ax_widget.hide()
pass
def drawCandles(self):
fplt.candlestick_ochl(self.data['Open Close High Low'.split()], ax=self.ax0)
#self.hover_label = fplt.add_legend('', ax=self.ax0)
#fplt.set_time_inspector(self.update_legend_text, ax=self.ax0, when='hover', data=data)
#fplt.add_crosshair_info(self.update_crosshair_text, ax=self.ax0)
# Inside plot widget controls
#self.createControlPanel(self.ax0.ax_widget)
pass
#########
# Draw orders on charts (with arrows)
#########
def drawOrders(self, orders = None):
# Orders need to be stuied to know if an order is an open or a close order, or both...
# It depends on the order volume and the currently opened positions volume
currentPositionSize = 0
open_orders = []
if orders != None:
self.orders = orders
if hasattr(self,"orders"):
for order in self.orders:
##############
# Buy
##############
if order.isbuy():
direction = "buy"
# Tracer les traites allant des ouvertures de positions vers la fermeture de position
if currentPositionSize < 0:
# Réduction, cloture, ou invertion de la position
if order.size == abs(currentPositionSize): # it's a buy so order.size > 0
# Cloture de la position
last_order = open_orders.pop()
posOpen = (bt.num2date(last_order.executed.dt),last_order.executed.price)
posClose = (bt.num2date(order.executed.dt), order.executed.price)
color = "#555555"
if order.executed.pnl > 0:
color = "#30FF30"
elif order.executed.pnl < 0:
color = "#FF3030"
fplt.add_line(posOpen, posClose, color, 2, style="--", ax = self.ax0 )
elif order.size > abs(currentPositionSize):
# Fermeture de la position précédente + ouverture d'une position inverse
pass
elif order.size < abs(currentPositionSize):
# Réduction de la position courante
pass
elif currentPositionSize > 0:
# Augmentation de la postion
# on enregistre la position pour pouvoir tracer un trait de ce point vers l'ordre de cloture du trade.
open_orders.append(order)
else:
# Ouverture d'une nouvelle position
open_orders.append(order)
pass
##############
# Sell
##############
elif order.issell():
direction = "sell"
if currentPositionSize < 0:
# Augmentation de la postion
# on enregistre la position pour pouvoir tracer un trait de ce point vers l'ordre de cloture du trade.
open_orders.append(order)
elif currentPositionSize > 0:
# Réduction, cloture, ou invertion de la position
if abs(order.size) == abs(currentPositionSize): # it's a buy so order.size > 0
# Cloture de la position
last_order = open_orders.pop()
posOpen = (bt.num2date(last_order.executed.dt),last_order.executed.price)
posClose = (bt.num2date(order.executed.dt), order.executed.price)
color = "#555555"
if order.executed.pnl > 0:
color = "#30FF30"
elif order.executed.pnl < 0:
color = "#FF3030"
fplt.add_line(posOpen, posClose, color, 2, style="--" )
pass
elif order.size > abs(currentPositionSize):
# Réduction de la position courante
pass
elif order.size < abs(currentPositionSize):
# Fermeture de la position précédente + ouverture d'une position inverse
pass
else:
# Ouverture d'une nouvelle position
open_orders.append(order)
pass
else:
print("Unknown order")
# Cumul des positions
currentPositionSize += order.size
# Todo: We could display the size of the order with a label on the chart
fplt.add_order(bt.num2date(order.executed.dt), order.executed.price, direction, ax=self.ax0)
pass
#########
# Finplot configuration functions : maybe it should be in a different file
#########
def update_legend_text(self, x, y, ax, data):
row = data.loc[data.TimeInt==x]
# format html with the candle and set legend
fmt = '<span style="color:#%s">%%.5f</span>' % ('0f0' if (row.Open<row.Close).all() else 'd00')
rawtxt = '<span style="font-size:13px">%%s %%s</span> O%s C%s H%s L%s' % (fmt, fmt, fmt, fmt)
self.hover_label.setText(rawtxt % ("EUR", "M15", row.Open, row.Close, row.High, row.Low))
pass
def update_crosshair_text(self,x, y, xtext, ytext):
ytext = '%s (Close%+.2f)' % (ytext, (y - self.data.iloc[x].Close))
return xtext, ytext
def activateDarkMode(self, activated):
'''Digs into the internals of finplot and pyqtgraph to change the colors of existing
plots, axes, backgronds, etc.'''
# first set the colors we'll be using
if activated:
fplt.foreground = '#777'
fplt.background = '#19232D'
fplt.candle_bull_color = fplt.candle_bull_body_color = '#0b0'
fplt.candle_bear_color = '#a23'
volume_transparency = '6'
else:
fplt.foreground = '#444'
fplt.background = fplt.candle_bull_body_color = '#fff'
fplt.candle_bull_color = '#380'
fplt.candle_bear_color = '#c50'
volume_transparency = 'c'
fplt.volume_bull_color = fplt.volume_bull_body_color = fplt.candle_bull_color + volume_transparency
fplt.volume_bear_color = fplt.candle_bear_color + volume_transparency
fplt.cross_hair_color = fplt.foreground+'8'
fplt.draw_line_color = '#888'
fplt.draw_done_color = '#555'
#pg.setConfigOptions(foreground=fplt.foreground, background=fplt.background)
# control panel color
#if ctrl_panel is not None:
# p = ctrl_panel.palette()
# p.setColor(ctrl_panel.darkmode.foregroundRole(), pg.mkColor(fplt.foreground))
# ctrl_panel.darkmode.setPalette(p)
# window background
for win in fplt.windows:
for ax in win.axs:
ax.ax_widget.setBackground(fplt.background)
ax.vb.background.setBrush(mkBrush(fplt.background))
# axis, crosshair, candlesticks, volumes
axs = [ax for win in fplt.windows for ax in win.axs]
vbs = set([ax.vb for ax in axs])
axs += fplt.overlay_axs
axis_pen = fplt._makepen(color=fplt.foreground)
for ax in axs:
ax.axes['left']['item'].setPen(axis_pen)
ax.axes['left']['item'].setTextPen(axis_pen)
ax.axes['bottom']['item'].setPen(axis_pen)
ax.axes['bottom']['item'].setTextPen(axis_pen)
if ax.crosshair is not None:
ax.crosshair.vline.pen.setColor(mkColor(fplt.foreground))
ax.crosshair.hline.pen.setColor(mkColor(fplt.foreground))
ax.crosshair.xtext.setColor(fplt.foreground)
ax.crosshair.ytext.setColor(fplt.foreground)
for item in ax.items:
if isinstance(item, fplt.FinPlotItem):
isvolume = ax in fplt.overlay_axs
if not isvolume:
item.colors.update(
dict(bull_shadow = fplt.candle_bull_color,
bull_frame = fplt.candle_bull_color,
bull_body = fplt.candle_bull_body_color,
bear_shadow = fplt.candle_bear_color,
bear_frame = fplt.candle_bear_color,
bear_body = fplt.candle_bear_color))
else:
item.colors.update(
dict(bull_frame = fplt.volume_bull_color,
bull_body = fplt.volume_bull_body_color,
bear_frame = fplt.volume_bear_color,
bear_body = fplt.volume_bear_color))
item.repaint()
pass
#############
# Indicators
#############
def resetPlots(self):
# Entirely reset graph
if (hasattr(self,"ax0")):
self.ax0.reset()
self.ax0.overlay().reset()
if (hasattr(self,"ax1")):
self.ax1.reset()
if (hasattr(self,"ax2")):
self.ax2.reset()
if (hasattr(self,"axPnL")):
self.axPnL.reset()
pass
def setChartData(self, data):
self.data = data
pass
def updateChart(self):
# Entirely reset graph
self.resetPlots()
if (hasattr(self,"data")):
# Start plotting indicators
if self.IndIchimokuActivated:
self.ichimoku_indicator = ichimoku.Ichimoku(self.data)
self.ichimoku_indicator.draw(self.ax0)
# Finally draw candles
self.drawCandles()
# Draw orders
self.drawOrders()
if self.IndVolumesActivated:
fplt.volume_ocv(self.data['Open Close Volume'.split()], ax=self.ax0.overlay())
# Refresh view : auto zoom
fplt.refresh()
pass
def setIndicator(self, indicatorName, activated):
if (indicatorName == "Ichimoku"):
self.IndIchimokuActivated = activated
if (indicatorName == "Volumes"):
self.IndVolumesActivated = activated
self.updateChart()
pass
#############
# Show finplot Window
#############
def show(self):
#qt_exec create a whole qt context : we dont need it here
fplt.show(qt_exec=False)
pass
def drawPnL(self, pln_data):
self.axPnL.reset()
fplt.plot(pln_data['time'], pln_data['value'], ax = self.axPnL, legend="value")
fplt.plot(pln_data['time'], pln_data['equity'], ax = self.axPnL, legend="equity")
self.axPnL.ax_widget.show()
self.axPnL.show()
pass