forked from Skinok/backtrader-pyqt-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
finplotWindow.py
466 lines (350 loc) · 16.4 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
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
import sys, os
from pyqtgraph.graphicsItems.LegendItem import LegendItem
from custom_indicators import ichimoku
from custom_indicators import rsi
from custom_indicators import stochastic
from custom_indicators import stochasticRsi
from custom_indicators import sma
from custom_indicators import ema
sys.path.append('../finplot')
import finplot as fplt
import pandas as pd
import numpy as np
from datetime import datetime as dt
import time as _time
import backtrader as bt
from pyqtgraph import mkColor, mkBrush
def chinese_price_colorfilter(item, datasrc, df):
opencol = df.columns[1]
closecol = df.columns[2]
is_up = df[opencol] <= df[closecol] # open lower than close = goes up
yield item.rowcolors('bear') + [df.loc[is_up, :]]
yield item.rowcolors('bull') + [df.loc[~is_up, :]]
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.IndStochasticRsiActivated = False
self.IndVolumesActivated = False
self.last_ax_data_xtick = []
pass
#########
# Prepare the plot widgets
#########
def createPlotWidgets(self, timeframe):
# fin plot
self.ax0, self.ax_rsi, self.ax_stochasticRsi, self.ax_stochastic, self.axPnL = fplt.create_plot_widget(master=self.dockArea, rows=5, init_zoom_periods=200)
self.dockArea.axs = [self.ax0, self.ax_rsi, self.ax_stochasticRsi, self.ax_stochastic, self.axPnL] # , self.ax_rsi, self.ax2, self.axPnL
self.dockChart.addWidget(self.ax0.ax_widget, 1, 0, 1, 1)
'''
self.dockChart.addWidget(self.ax_rsi.ax_widget, 2, 0, 1, 1)
self.dockChart.addWidget(self.ax2.ax_widget, 3, 0, 1, 1)
'''
self.interface.dock_rsi[timeframe].layout.addWidget(self.ax_rsi.ax_widget)
self.interface.dock_stochasticRsi[timeframe].layout.addWidget(self.ax_stochasticRsi.ax_widget)
self.interface.dock_stochastic[timeframe].layout.addWidget(self.ax_stochastic.ax_widget)
# Ax Profit & Loss
self.interface.strategyResultsUI.ResultsTabWidget.widget(1).layout().addWidget(self.axPnL.ax_widget)
fplt.add_crosshair_info(self.update_crosshair_text, ax=self.ax0)
pass
def drawCandles(self):
fplt.candlestick_ochl(self.data['Open Close High Low'.split()], ax=self.ax0 ) # colorfunc=chinese_price_colorfilter
#self.hover_label = fplt.add_legend('', ax=self.ax0)
#fplt.set_time_inspector(self.update_legend_text, ax=self.ax0, when='hover', data=data)
# Inside plot widget controls
#self.createControlPanel(self.ax0.ax_widget)
pass
def drawSma(self, period, color, width):
self.sma_indicator = sma.Sma(self.data, period)
self.sma_indicator.draw(self.ax0, color, width)
pass
def drawEma(self, period, color, width):
self.ema_indicator = ema.Ema(self.data, period)
self.ema_indicator.draw(self.ax0, color, width)
pass
def drawRsi(self, period, color):
self.rsi_indicator = rsi.Rsi(self.data, period)
self.rsi_indicator.draw(self.ax_rsi, color)
pass
def drawStochastic(self, period, smooth_k, smooth_d):
self.stochastic_indicator = stochastic.Stochastic(self.data, period, smooth_k, smooth_d)
self.stochastic_indicator.draw(self.ax_stochastic)
pass
def drawStochasticRsi(self, period, smooth_k, smooth_d):
self.stochasticRsi_indicator = stochasticRsi.StochasticRsi(self.data, period, smooth_k, smooth_d)
self.stochasticRsi_indicator.draw(self.ax_stochasticRsi)
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():
# 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():
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, ax=self.ax0, 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, order.isbuy(), 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 \n Open: %.5f\n Close: %.5f\n High: %.5f\n Low: %.5f' \
% (ytext, self.data.iloc[x].Open, self.data.iloc[x].Close, self.data.iloc[x].High, self.data.iloc[x].Low)
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['right']['item'].setPen(axis_pen)
ax.axes['right']['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.reset()
if (hasattr(self,"ax1")):
self.ax1.reset()
if (hasattr(self,"ax2")):
self.ax2.reset()
if (hasattr(self,"axPnL")):
self.axPnL.reset()
# Reset overylays too
axs = fplt.overlay_axs
for ax_overlay in axs:
ax_overlay.reset()
pass
def refreshChart(self):
fplt.refresh()
pass
def setChartData(self, data):
self.data = data
def resetChart(self):
# Remove all previous orders arrows and informations
self.orders = []
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)
if self.IndVolumesActivated:
fplt.volume_ocv(self.data['Open Close Volume'.split()], ax=self.ax0.overlay())
# Finally draw candles
self.drawCandles()
# Draw orders
self.drawOrders()
# 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
def _date_str2x(self, ax, date_str):
print(type(ax.getAxis('bottom').vb.datasrc))
print(date_str)
if ax.getAxis('bottom').vb.datasrc is None:
df = self.last_ax_data_xtick
else:
df = ax.getAxis('bottom').vb.datasrc.df
self.last_ax_data_xtick = df
dftime = np.array(df.iloc[:, 0])
lsttime = dftime.tolist()
# print(dftime)
# print(lsttime)
xtime = dt.strptime(date_str, '%Y-%m-%d %H:%M:%S')
xint = int((xtime.timestamp()-_time.timezone)*1e9)
print(xint,lsttime[0])
x = lsttime.index(xint)
return [x]
def zoomTo(self, dateStr1, dateStr2):
for win in fplt.windows:
for ax in win.axs:
# x1 = self._date_str2x(ax, dateStr1)
# x2 = self._date_str2x(ax, dateStr2)
x1 = fplt._dateStr2x(ax, dateStr1)
x2 = fplt._dateStr2x(ax, dateStr2)
# Do not zoom exactly on the trade, so take a little bit before & after
date1 = x1[0]
if date1 > 10:
date1 = date1 - 10
date2 = x2[0] + 10
ax.vb.update_y_zoom(date1,date2)
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['equity'], ax = self.axPnL, legend="equity")
fplt.plot(pln_data['time'], pln_data['value'], ax = self.axPnL, legend="value")
self.axPnL.ax_widget.show()
self.axPnL.show()
pass
def showPnL(self):
self.axPnL.show()
self.axPnL.ax_widget.show()
pass
def hidePnL(self):
self.axPnL.hide()
self.axPnL.ax_widget.hide()
pass