How can I update a custom graphic item (in pyqtgraph) whenever a COM event occurs?

让人想犯罪 __ 提交于 2019-12-02 11:50:20

问题


I made a program that receives every transaction information of crude oil futures in real time. Basically, OnReceiveRealData executes when a transaction is executed and calls real_get method. In the method, current time, price and volume data are collected and a dictionary is made with them. There are more methods to make OHLC format data from this real time streaming data, but the point of my question is how to update a custom graphic item(a candlestick plot) whenever real_get method is called?

class COM_Receiver(QAxWidget):
    def __init__(self):
        super().__init__()
        self._create_com_instance()

        self.list_items = ['CLF18']

        self.OnReceiveRealData.connect(self.real_get)
        self.OnEventConnect.connect(self._event_connect)

    def _create_com_instance(self):
        self.setControl("KFOPENAPI.KFOpenAPICtrl.1")

    def _event_connect(self, err_code):
        if err_code == 0:
            print("connected")
            self.real_set()
        else:
            print("disconnected")
        self.login_event_loop.exit()

    def connect(self):
        self.dynamicCall("CommConnect(1)")
        self.login_event_loop = QEventLoop()                                   
        self.login_event_loop.exec_()

    def real_set(self):
        self.dynamicCall("SetInputValue(str, str)", "itemCode", ';'.join(self.list_items))
        ret = self.dynamicCall("CommRqData(str, str, str, str)", "itemCurrent", "opt10005", "", "1001")

    def real_get(self, code, realtype, realdata):
        if realtype == 'itemCurrent':
            eventTime = ( datetime.utcnow() + timedelta(hours=2) )
            currentPrice = self.dynamicCall("GetCommRealData(str, int)", "itemCurrent", 140)
            currentVolume = self.dynamicCall("GetCommRealData(str, int)", "itemCurrent", 15)

            dic_current = {'eventTime':eventTime, 'currentPrice':currentPrice, 'currentVolume':currentVolume}  

            self.make_ohlc(self.plt, dic_current)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    c = COM_Receiver()
    c.connect()

    sys.exit(app.exec_())

I referred to this article(The fastest way to add a new data bar with pyqtgraph) and realized that I could update candlesticks without removing and creating a CandlestickItem() instance whenever new data is received(which is how I do it now and it consumes a lot of resources).

I tried making a CandlestickItem() instance and updating it with set_data method in the article, however, it doesn't work well and deosn't show updated candlesticks unless I click the chart(plt = pg.plot()). That is, if I leave the program for about 10 minutes, the chart doesn't show any difference, but once I click the chart, it shows all new candlesticks for the last 10 minutes at once. I want it to show new candlesticks in real time, even when I don't click the chart continuously.

How could I update a custom graphic item whenever real_get method is called by OnReceiveRealData event in COM_Receiver class? I think item.set_data(data=dic_current) should be run in real_get method, but what I have tried so far doesn't work as what I expect.

The source below is the whole source of the candlestick example from the article.

import pyqtgraph as pg
from pyqtgraph import QtCore, QtGui
import random

## Create a subclass of GraphicsObject.
## The only required methods are paint() and boundingRect() 
## (see QGraphicsItem documentation)
class CandlestickItem(pg.GraphicsObject):
    def __init__(self):
        pg.GraphicsObject.__init__(self)
        self.flagHasData = False

    def set_data(self, data):
        self.data = data  ## data must have fields: time, open, close, min, max
        self.flagHasData = True
        self.generatePicture()
        self.informViewBoundsChanged()

    def generatePicture(self):
        ## pre-computing a QPicture object allows paint() to run much more quickly, 
        ## rather than re-drawing the shapes every time.
        self.picture = QtGui.QPicture()
        p = QtGui.QPainter(self.picture)
        p.setPen(pg.mkPen('w'))
        w = (self.data[1][0] - self.data[0][0]) / 3.
        for (t, open, close, min, max) in self.data:
            p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
            if open > close:
                p.setBrush(pg.mkBrush('r'))
            else:
                p.setBrush(pg.mkBrush('g'))
            p.drawRect(QtCore.QRectF(t-w, open, w*2, close-open))
        p.end()

    def paint(self, p, *args):
        if self.flagHasData:
            p.drawPicture(0, 0, self.picture)

    def boundingRect(self):
        ## boundingRect _must_ indicate the entire area that will be drawn on
        ## or else we will get artifacts and possibly crashing.
        ## (in this case, QPicture does all the work of computing the bouning rect for us)
        return QtCore.QRectF(self.picture.boundingRect())

app = QtGui.QApplication([])

data = [  ## fields are (time, open, close, min, max).
    [1., 10, 13, 5, 15],
    [2., 13, 17, 9, 20],
    [3., 17, 14, 11, 23],
    [4., 14, 15, 5, 19],
    [5., 15, 9, 8, 22],
    [6., 9, 15, 8, 16],
]
item = CandlestickItem()
item.set_data(data)

plt = pg.plot()
plt.addItem(item)
plt.setWindowTitle('pyqtgraph example: customGraphicsItem')


def update():
    global item, data
    data_len = len(data)
    rand = random.randint(0, len(data)-1)
    new_bar = data[rand][:]
    new_bar[0] = data_len
    data.append(new_bar)
    item.set_data(data)
    app.processEvents()  ## force complete redraw for every plot

timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(100)

## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

来源:https://stackoverflow.com/questions/47361222/how-can-i-update-a-custom-graphic-item-in-pyqtgraph-whenever-a-com-event-occur

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!