コード例 #1
0
 def setCandleColors(self, candleSet: QtChart.QCandlestickSet):
     """Sets the candle colors (green and red)
     :param candleSet:  a QCandlestickSet set of candles
     """
     if candleSet.close() < candleSet.open():
         candleSet.setPen(QtGui.QPen(QtCore.Qt.red, 1))
         candleSet.setBrush(QtGui.QBrush(QtCore.Qt.red))
     else:
         candleSet.setPen(QtGui.QPen(QtCore.Qt.green, 1))
         candleSet.setBrush(QtGui.QBrush(QtCore.Qt.black))
コード例 #2
0
ファイル: main.py プロジェクト: edwudw/stocks
    def getStockData(self):
        self.close()
        print("HI")

        self.mainLayout.removeWidget(self.newChartView)
        self.newSeries = QCandlestickSeries()
        self.newSeries.setName("Test Chart 2")

        self.saucePage = urllib.request.urlopen(
            'https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY&symbol='
            + self.stockRequestBox.text() +
            '&interval=1min&apikey=NOC1N35PNDQOFF1A')
        self.output = self.saucePage.read()
        self.webContent = self.output.decode(
            'utf-8')  # Convert from bytes to string

        self.writePage = open(
            'stock.json', 'w'
        )  # Write webContent to a html file because otherwise i can't use readlines()
        self.writePage.write(
            self.webContent)  # It's very efficient code trust me
        self.writePage.close()

        self.sauce = json.load(open('stock.json'))

        # print(sauce["Monthly Time Series"]["2018-01-14 20:23:00"]["1. open"])
        self.openStocks = {}
        for date in self.sauce["Monthly Time Series"]:
            self.openStocks[date] = self.sauce["Monthly Time Series"][date][
                "1. open"]

        self.ordered = collections.OrderedDict(sorted(self.openStocks.items()))
        for k, v in self.ordered.items():
            dateString = k
            dt = datetime.datetime(int(dateString[:4]), int(dateString[5:7]),
                                   int(dateString[8:10]))

            self.newSet = QCandlestickSet((time.mktime(dt.timetuple()) * 1000))
            self.newSet.setOpen(float(v))
            self.newSet.setHigh(
                float(self.sauce["Monthly Time Series"][k]["2. high"]))
            self.newSet.setLow(
                float(self.sauce["Monthly Time Series"][k]["3. low"]))
            self.newSet.setClose(
                float(self.sauce["Monthly Time Series"][k]["4. close"]))
            self.newSeries.append(self.newSet)
        self.newChart = QChart()
        self.newChart.addSeries(self.newSeries)
        self.newChart.setTitle("Test Actual Chart")
        self.newChart.createDefaultAxes()
        self.newChartView = QChartView(self.newChart)
        self.mainLayout.addWidget(self.newChartView)
        self.show()
コード例 #3
0
ファイル: KVLines.py プロジェクト: Tan-zy/Qt5Notebook
    def add_series_values(self, data: pd.DataFrame, is_init=False):
        self._stocks = data
        self._category = self._stocks['trade_date']
        self._count = len(self._category)
        for _, stock in self._stocks.iterrows():
            time_p = datetime.datetime.strptime(stock['trade_date'], '%Y%m%d')
            time_p = float(time.mktime(time_p.timetuple()))
            _set = QCandlestickSet(float(stock['open']), float(stock['high']),
                                   float(stock['low']), float(stock['close']),
                                   time_p, self._series)
            self._series.append(_set)

        if not is_init:
            self._stocks = data
            self._category = self._stocks['trade_date']
            axis_x = self._chart.axisX()
            axis_y = self._chart.axisY()
            axis_x.setCategories(self._category)
            max_p = self._stocks[['high', 'low']].stack().max()
            min_p = self._stocks[['high', 'low']].stack().min()
            axis_y.setRange(min_p * 0.99, max_p * 1.01)
            self._zero_value = (0, self._chart.axisY().min())
            self._max_value = (len(self._chart.axisX().categories()),
                               self._chart.axisY().max())
            # 计算x轴单个cate的宽度,用来处理横线不能画到边界
            self._cate_width = (self._max_point.x() -
                                self._zero_point.x()) / len(self._category)
コード例 #4
0
    def initChart(self):
        self._chart = QChart(title='蜡烛图悬浮提示')
        self._chart.setAnimationOptions(QChart.SeriesAnimations)
        series = QCandlestickSeries()
        series.setIncreasingColor(QColor(Qt.red))
        series.setDecreasingColor(QColor(Qt.green))
        series.setName(self.stocks['name'].iloc[0])
        for _, stock in self.stocks.iterrows():
            time_p = datetime.datetime.strptime(stock['trade_date'], '%Y%m%d')
            time_p = float(time.mktime(time_p.timetuple()))
            _set = QCandlestickSet(float(stock['open']), float(stock['high']), 
                float(stock['low']), float(stock['close']), time_p, series)
            _set.hovered.connect(self.handleBarHoverd)  # 鼠标悬停
            series.append(_set)
        self._chart.addSeries(series)

        self._chart.createDefaultAxes()
        self._chart.setLocalizeNumbers(True)
        axis_x = self._chart.axisX()
        axis_y = self._chart.axisY()
        axis_x.setGridLineVisible(False)
        axis_y.setGridLineVisible(False)
        # axis_y.setLabelFormat("%.2f")
        axis_x.setCategories(self.category)
        max_p = self.stocks[['high', 'low']].stack().max() + 10
        min_p = self.stocks[['high', 'low']].stack().min() - 10
        axis_y.setRange(min_p, max_p)

        # chart的图例
        legend = self._chart.legend()
        # 设置图例由Series来决定样式
        legend.setMarkerShape(QLegend.MarkerShapeFromSeries)

        self.setChart(self._chart)
コード例 #5
0
ファイル: CandleSeries.py プロジェクト: ppaanngggg/FinChart
    def addSeries(
        self,
        _x2idx: typing.Dict,
        _idx2x: list,
        _chart: QChart,
        _axis_x: QValueAxis,
        _axis_y: QValueAxis,
    ):
        series = QCandlestickSeries()
        series.setName(self.name)

        for x, y in zip(self.x_list, self.y_list):
            series.append(QCandlestickSet(*y, _x2idx[x]))
        if self.inc_color is not None:
            series.setIncreasingColor(self.inc_color)
        else:
            series.setIncreasingColor(QColor("#c41919"))
        if self.dec_color is not None:
            series.setDecreasingColor(self.dec_color)
        else:
            series.setDecreasingColor(QColor("#009f9f"))

        _chart.addSeries(series)
        _chart.setAxisX(_axis_x, series)
        _chart.setAxisY(_axis_y, series)

        if self.show_value:
            self.createShow()
コード例 #6
0
    def read_candlestick_set(self):

        line = self.readLine()

        if line.startswith("#") or line is None:
            return None

        (timestamp, open_, high, low,
         close) = line.split(" ")  # SkipEmptyParts\

        candlestickset = QCandlestickSet(float(timestamp))
        candlestickset.setOpen(float(open_))
        candlestickset.setHigh(float(high))
        candlestickset.setLow(float(low))
        candlestickset.setClose(float(close))

        return candlestickset
コード例 #7
0
def plot_candlechart(ohlc_data):
    app = ParaMakerApplication([])
    #app.setStyleSheet("background-color:black;")

    series = QCandlestickSeries()
    series.setBodyOutlineVisible(False)
    series.setDecreasingColor(Qt.red)
    series.setIncreasingColor(Qt.green)

    rsi = qc.QLineSeries()  # 5-days average data line
    rsi.append(QPointF(ohlc_data[300].timestamp, ohlc_data[300].closed))
    rsi.append(QPointF(ohlc_data[700].timestamp, ohlc_data[700].closed))
    #rsi.append(QPointF(ohlc_data[150].timestamp, ohlc_data[100].closed))
    tm = []  # stores str type data
    # in a loop,  series and rsi append corresponding data
    for candle in ohlc_data:
        series.append(
            QCandlestickSet(candle.opened, candle.high, candle.low,
                            candle.closed))
        #rsi.append(QPointF(num, m))
        tm.append(str(candle.timestamp))
        #rsi.append(str(candle.timestamp))

    #rsi_values = calculate_rsi(14, ohlc_data)

    chart = QChart()
    chart.setBackgroundVisible(False)
    chart.setPlotAreaBackgroundVisible(False)
    chart.addSeries(series)  # candle
    chart.addSeries(rsi)  # rsi line

    #chart.axisX(rsi).setRange(ohlc_data[0].timestamp, ohlc_data[-1].timestamp)

    chart.createDefaultAxes()

    axisXRSI = QValueAxis()
    axisYRSI = QValueAxis()
    axisXRSI.setRange(ohlc_data[0].timestamp, ohlc_data[-1].timestamp)
    axisYRSI.setRange(ohlc_data[0].closed, ohlc_data[-1].closed)
    axisXRSI.setGridLineVisible(False)
    axisYRSI.setGridLineVisible(False)

    chart.setAxisX(axisXRSI, rsi)
    chart.setAxisY(axisYRSI, rsi)

    chart.legend().hide()

    chart.axisX(series).setCategories(tm)
    #chart.axisX(series).setGridLineVisible(False)
    #chart.axisY(series).setGridLineVisible(False)
    ###chart.axisX(rsi).setVisible(False)

    chartview = QChartView(chart)
    chartview.setRenderHint(QPainter.Antialiasing)
    ui = ParaMakerWindow()
    ui.setCentralWidget(chartview)
    sys.exit(app.exec_())
コード例 #8
0
    def readCandlestickSet(self):
        line = self.readLine()
        if line.startswith("#") or not line:
            return

        strList = line.split(" ")
        if len(strList) != 5:
            return

        timestamp, _open, high, low, close = [float(v) for v in strList]

        candlestickSet = QCandlestickSet(timestamp)
        candlestickSet.setOpen(_open)
        candlestickSet.setHigh(high)
        candlestickSet.setLow(low)
        candlestickSet.setClose(close)

        return candlestickSet
コード例 #9
0
ファイル: chart.py プロジェクト: sangcle/GreatFirst
 def appendData(self, o, h, l, c):
     if len(self.tm) == self.viewLimit:
         self.priceData.remove(0)
         self.tm.remove(0)
     dt = QDateTime.currentDateTime()
     self.priceData.append(QCandlestickSet(o, h, l, c))
     print(dt.toMSecsSinceEpoch())
     print(type(dt.toMSecsSinceEpoch()))
     self.tm.append(dt.toMSecsSinceEpoch())
     self.__updateAxis()
コード例 #10
0
ファイル: Display.py プロジェクト: loresalm/POTY_2019
 def load_data(self, _data):
     self.data = _data
     # data format [[Open] [High] [Low] [Close] ]
     for i in range(len(self.data[0])):
         self.series.append(
             QCandlestickSet(float(self.data[0][i]), float(self.data[1][i]),
                             float(self.data[2][i]),
                             float(self.data[3][i])))
         self.tm.append(str(i))
         i = i + 1
コード例 #11
0
ファイル: main.py プロジェクト: fMaks/Analizer
def main ():
    if len (sys.argv) < 3:
        print ("файл не задан")
        sys.exit ()

    with open (sys.argv[1], 'rt') as file:
        TicksFile = file.read()
    
    TicksTuple = tuple(TicksFile.split('\n')[:-1])
    
    Bars = (FormBarFrame(TicksTuple, 60))
    with open(sys.argv[1][:-4] + '_' + sys.argv[2] + '.bars', 'wt') as file:
        for i in reversed(Bars):
            file.write("{0} {1} {2} {3} {4} {5} {6}\n".format(str(i[0]), i[1], i[2], i[3], i[4], i[5], i[6]))

    # Вывод графика
    app = QApplication(sys.argv)
    series = QCandlestickSeries()
    series.setDecreasingColor(Qt.red)
    series.setIncreasingColor(Qt.green)

    #ma5 = qc.QLineSeries()  # 5-days average data line
    tm = []  # stores str type data

    # in a loop,  series and ma5 append corresponding data
    #for num, o, h, l, c in Bars:
    for i in range(len(Bars)):
        series.append(QCandlestickSet(Bars[i][1], Bars[i][4], Bars[i][3], Bars[i][2]))
        #ma5.append(QPointF(num, m))
        tm.append(str(Bars[i][0]))

    chart = QChart()

    chart.addSeries(series)  # candle
    #chart.addSeries(ma5)  # ma5 line

    chart.setAnimationOptions(QChart.SeriesAnimations)
    chart.createDefaultAxes()
    chart.legend().hide()

    chart.axisX(series).setCategories(tm)
    #chart.axisX(ma5).setVisible(False)

    chartview = QChartView(chart)
    ui = QMainWindow()
    ui.setGeometry(50, 50, 500, 300)
    ui.setCentralWidget(chartview)
    ui.show()


    sys.exit(app.exec_())
コード例 #12
0
 def appendCandlestickSeriesData(self, ls, dtaware, ope, hig, clo, low):
     x=dtaware2epochms(dtaware)
     ls.append(QCandlestickSet(float(ope), float(hig), float(clo), float(low), x ))
     if self.maxy==None:
         self.maxy=float(hig)
         self.miny=float(low)
         self.maxx=x
         self.minx=x
     if hig>self.maxy:
         self.maxy=float(hig)
     if low<self.miny:
         self.miny=float(low)
     if x>self.maxx:
         self.maxx=x
     if x<self.minx:
         self.minx=x
コード例 #13
0
ファイル: qt5.py プロジェクト: shmeller86/algotrade
    def append_data_and_plot(self, d):
        """Append and update the plot"""
        num, o, h, l, c, m = d

        ax1 = self.chart.axisX(self.ma5)
        ay1 = self.chart.axisY(self.ma5)

        xmin = xmax = num
        ymin = ymax = m

        step = 10
        offset = 100

        for p in self.ma5.pointsVector()[-step:]:
            xmin = min(p.x(), xmin)
            xmax = max(p.x(), xmax)

            ymin = min(p.y(), ymin) - offset
            ymax = max(p.y(), ymax) + offset

        xmin = max(0, xmax - step)

        ax1.setMin(xmin)
        ax1.setMax(xmax)
        ay1.setMin(ymin)
        ay1.setMax(ymax)

        self.ma5.append(QPointF(num, m))
        self.tm.append(str(num))

        self.series.append(QCandlestickSet(o, h, l, c))
        ax2 = self.chart.axisX(self.series)
        ax2.setCategories(self.tm)
        ax2.setMin(str(xmin))
        ax2.setMax(str(xmax))

        ay2 = self.chart.axisY(self.series)
        ay2.setMin(ymin)
        ay2.setMax(ymax)
コード例 #14
0
ファイル: figure.py プロジェクト: wingsof/trader
 def add_volume_data(self, q, volume):
     if self.in_datetime_range(q):
         self.volume_series.append(QCandlestickSet(0, volume, 0, volume, q))
コード例 #15
0
ファイル: main.py プロジェクト: amigons3232/stackoverflow
    (6, 7500, 7590, 7480, 7560, 7512),
    (7, 7560, 7830, 7540, 7800, 7584),
)

app = QApplication(sys.argv)
#
series = QCandlestickSeries()
series.setDecreasingColor(Qt.red)
series.setIncreasingColor(Qt.green)

ma5 = qc.QLineSeries()  # 5-days average data line
tm = []  # stores str type data

# in a loop,  series and ma5 append corresponding data
for num, o, h, l, c, m in data:
    series.append(QCandlestickSet(o, h, l, c))
    ma5.append(QPointF(num, m))
    tm.append(str(num))

chart = QChart()

chart.addSeries(series)  # candle
chart.addSeries(ma5)  # ma5 line

chart.setAnimationOptions(QChart.SeriesAnimations)
chart.createDefaultAxes()
chart.legend().hide()

chart.axisX(series).setCategories(tm)
chart.axisX(ma5).setVisible(False)
コード例 #16
0
ファイル: main.py プロジェクト: edwudw/stocks
    def initUI(self):
        self.mainLayout = QVBoxLayout()
        self.stockFrame = QFrame()
        self.mainLayout.addWidget(self.stockFrame)
        self.mainButton = QPushButton("Push Me!")
        self.mainButton.clicked.connect(self.getStockData)
        self.mainLayout.addWidget(self.mainButton)

        self.stockRequestLayout = QHBoxLayout()
        self.stockRequestedLabel = QLabel("Stock: ")
        self.stockRequestLayout.addWidget(self.stockRequestedLabel)
        self.stockRequestBox = QLineEdit()
        self.stockRequestLayout.addWidget(self.stockRequestBox)

        self.mainLayout.addLayout(self.stockRequestLayout)
        self.setLayout(self.mainLayout)

        self.newSeries = QCandlestickSeries()
        self.newSeries.setName("Test Chart")

        # for i in range(1000):

        #     self.newSet = QCandlestickSet(time.time() * 1000 + (random.randint(-5, 5) * 60000))
        #     self.newSet.setOpen(random.randint(1, 10))
        #     self.newSet.setHigh(random.randint(1, 10))
        #     self.newSet.setLow(random.randint(1, 10))
        #     self.newSet.setClose(random.randint(1, 10))
        #     self.newSeries.append(self.newSet)

        # self.newSet2 = QCandlestickSet()
        # self.newSet2.setOpen(1.00)
        # self.newSet2.setHigh(10.00)
        # self.newSet2.setLow(0.50)
        # self.newSet2.setClose(5.00)
        # self.newSeries.append(self.newSet2)

        self.saucePage = urllib.request.urlopen(
            'https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY&symbol=BHP&apikey=NOC1N35PNDQOFF1A'
        )

        self.output = self.saucePage.read()
        self.webContent = self.output.decode(
            'utf-8')  # Convert from bytes to string

        self.writePage = open(
            'stock.json', 'w'
        )  # Write webContent to a html file because otherwise i can't use readlines()
        self.writePage.write(
            self.webContent)  # It's very efficient code trust me
        self.writePage.close()

        self.sauce = json.load(open('stock.json'))

        # print(sauce["Monthly Time Series"]["2018-01-14 20:23:00"]["1. open"])
        self.openStocks = {}
        for date in self.sauce["Monthly Time Series"]:
            self.openStocks[date] = self.sauce["Monthly Time Series"][date][
                "1. open"]

        self.ordered = collections.OrderedDict(sorted(self.openStocks.items()))
        count = 0
        for k, v in self.ordered.items():
            dateString = k
            dt = datetime.datetime(int(dateString[:4]), int(dateString[5:7]),
                                   int(dateString[8:10]))

            self.newSet = QCandlestickSet((time.mktime(dt.timetuple()) * 1000))
            self.newSet.setOpen(float(v))
            self.newSet.setHigh(
                float(self.sauce["Monthly Time Series"][k]["2. high"]))
            self.newSet.setLow(
                float(self.sauce["Monthly Time Series"][k]["3. low"]))
            self.newSet.setClose(
                float(self.sauce["Monthly Time Series"][k]["4. close"]))
            self.newSeries.append(self.newSet)
            count = count + 1
            # if count > 8:
            #     break

        self.newChart = QChart()
        self.newChart.addSeries(self.newSeries)
        self.newChart.setTitle("Test Actual Chart")
        self.newChart.createDefaultAxes()
        self.newChartView = QChartView(self.newChart)
        self.mainLayout.addWidget(self.newChartView)
        # self.subjectLabel = QLabel()
        # self.subjectLabel.setAlignment(Qt.Qt.AlignCenter)
        # self.mainLayout.addWidget(self.subjectLabel)
        # self.testLabel = QLabel()
        # self.testLabel.setAlignment(Qt.Qt.AlignCenter)
        # self.mainLayout.addWidget(self.testLabel)
        # self.randomButton = QPushButton("Choose")
        # self.randomButton.clicked.connect(self.randomDef)
        # self.mainLayout.addWidget(self.randomButton)
        # self.setLayout(self.mainLayout)
        self.setGeometry(300, 300, 300, 300)
        self.setWindowTitle("Stocks")
        self.show()
コード例 #17
0
    def __drawChart(self):  ##绘制图表
        self.chart.removeAllSeries()  #删除所有序列
        self.chart.setTitle("股票日线图--" + self.ui.tabWidget.tabText(0))

        ## 1. 创建蜡烛图
        seriesCandle = QCandlestickSeries()
        seriesCandle.setName("蜡烛图")
        seriesCandle.setIncreasingColor(Qt.red)  #暴涨
        seriesCandle.setDecreasingColor(Qt.darkGreen)  #暴跌

        visible = self.ui.chkBox_Outline.isChecked()
        seriesCandle.setBodyOutlineVisible(visible)
        seriesCandle.setCapsVisible(self.ui.chkBox_Caps.isChecked())

        self.chart.addSeries(seriesCandle)
        seriesCandle.attachAxis(self.__axisX)
        seriesCandle.attachAxis(self.__axisY)

        seriesCandle.clicked.connect(self.do_candleClicked)
        seriesCandle.hovered.connect(self.do_candleHovered)

        ## 2. 创建MA曲线
        pen = QPen()
        pen.setWidth(2)

        seriesMA1 = QLineSeries()  #不能使用QSplineSeries
        seriesMA1.setName("MA5")
        pen.setColor(Qt.magenta)
        seriesMA1.setPen(pen)
        self.chart.addSeries(seriesMA1)
        seriesMA1.attachAxis(self.__axisX)
        seriesMA1.attachAxis(self.__axisY)

        seriesMA2 = QLineSeries()
        seriesMA2.setName("MA10")
        pen.setColor(Qt.yellow)
        seriesMA2.setPen(pen)
        self.chart.addSeries(seriesMA2)
        seriesMA2.attachAxis(self.__axisX)
        seriesMA2.attachAxis(self.__axisY)

        seriesMA3 = QLineSeries()
        seriesMA3.setName("MA20")
        pen.setColor(Qt.cyan)
        seriesMA3.setPen(pen)
        self.chart.addSeries(seriesMA3)
        seriesMA3.attachAxis(self.__axisX)
        seriesMA3.attachAxis(self.__axisY)

        seriesMA4 = QLineSeries()
        seriesMA4.setName("MA60")
        pen.setColor(Qt.green)  #green
        seriesMA4.setPen(pen)
        self.chart.addSeries(seriesMA4)
        seriesMA4.attachAxis(self.__axisX)
        seriesMA4.attachAxis(self.__axisY)

        ## 3. 填充数据到序列
        dataRowCount = self.itemModel.rowCount()  #数据点个数
        for i in range(dataRowCount):
            dateStr = self.itemModel.item(i, 0).text()  #日期字符串,如"2017/02/03"
            dateValue = QDate.fromString(dateStr, "yyyy/MM/dd")  #QDate
            dtValue = QDateTime(dateValue)  #日期时间 QDateTime
            timeStamp = dtValue.toMSecsSinceEpoch()  #毫秒数

            oneCandle = QCandlestickSet()  #QCandlestickSet
            oneCandle.setOpen(float(self.itemModel.item(i, 1).text()))  #开盘
            oneCandle.setHigh(float(self.itemModel.item(i, 2).text()))  #最高
            oneCandle.setLow(float(self.itemModel.item(i, 3).text()))  #最低
            oneCandle.setClose(float(self.itemModel.item(i, 4).text()))  #收盘
            oneCandle.setTimestamp(timeStamp)  #时间戳
            seriesCandle.append(oneCandle)  #添加到序列

            M1 = float(self.itemModel.item(i, 5).text())
            M2 = float(self.itemModel.item(i, 6).text())
            M3 = float(self.itemModel.item(i, 7).text())
            M4 = float(self.itemModel.item(i, 8).text())

            seriesMA1.append(timeStamp, M1)
            seriesMA2.append(timeStamp, M2)
            seriesMA3.append(timeStamp, M3)
            seriesMA4.append(timeStamp, M4)

    ## 4. 设置坐标轴范围
        minDateStr = self.itemModel.item(0, 0).text()  #日期字符串,如"2017/02/03"
        minDate = QDate.fromString(minDateStr, "yyyy/MM/dd")  #QDate
        minDateTime = QDateTime(minDate)  #最小日期时间,QDateTime

        maxDateStr = self.itemModel.item(dataRowCount - 1,
                                         0).text()  #日期字符串,如"2017/05/03"
        maxDate = QDate.fromString(maxDateStr, "yyyy/MM/dd")
        maxDateTime = QDateTime(maxDate)  #最大日期时间

        self.__axisX.setRange(minDateTime, maxDateTime)  #日期时间范围
        dateFormat = self.ui.comboDateFormat.currentText()  #格式,如"MM-dd"
        self.__axisX.setFormat(dateFormat)  #标签格式

        self.__axisY.applyNiceNumbers()  #自动

        for marker in self.chart.legend().markers():  #QLegendMarker类型列表
            marker.clicked.connect(self.do_LegendMarkerClicked)
コード例 #18
0
ファイル: chart.py プロジェクト: ahribori/pyqt5-playground
    def addCandle(self, open, close, high, low, timestamp):
        candlestickSet = QCandlestickSet()
        candlestickSet.setOpen(open)
        candlestickSet.setClose(close)
        candlestickSet.setHigh(high)
        candlestickSet.setLow(low)
        candlestickSet.setTimestamp(timestamp)

        pen = QPen()
        candlestickSet.setPen(pen)
        self.candleSeries.append(candlestickSet)
コード例 #19
0
ファイル: ViewPair.py プロジェクト: sgiy/crypto-trader
    def draw_chart(self):
        exchange = self._exchange
        market_symbol = self._market_symbol
        interval_name = self._chart_dropdown_interval.currentText()
        lookback_name = self._chart_dropdown_lookback.currentText()
        interval = self._CTMain._settings['Chart Interval'][interval_name]
        lookback = self._CTMain._settings['Chart Lookback Window'][
            lookback_name]

        load_chart = self._CTMain._Crypto_Trader.trader[
            exchange].load_chart_data(market_symbol, interval, lookback)

        self.CandlestickSeries.clear()
        self.VolumeBarSeries.clear()
        ch_min = load_chart[0][3]
        ch_max = load_chart[0][2]
        t_min = load_chart[0][0]
        t_max = load_chart[0][0]
        v_max = load_chart[0][6]

        for point in load_chart:
            candle = CTCandlestickSet(timestamp=point[0] * 1000,
                                      c_open=point[1],
                                      c_high=point[2],
                                      c_low=point[3],
                                      c_close=point[4],
                                      volume=point[5],
                                      base_volume=point[6],
                                      base_curr=self._base_curr,
                                      curr_curr=self._curr_curr,
                                      parent=self)
            self.CandlestickSeries.append(candle)
            ch_min = min(ch_min, point[3])
            ch_max = max(ch_max, point[2])
            t_min = min(t_min, point[0])
            t_max = max(t_max, point[0])
            v_max = max(v_max, point[6])

        min_y = max(0, ch_min - 0.15 * (ch_max - ch_min))
        max_y = ch_max + 0.1 * (ch_max - ch_min)

        max_volume = 0
        for point in load_chart:
            # high = min_y + 0.1 * (max_y - min_y)  * point[6] / v_max
            # low = min_y
            v_low = 0
            v_high = point[6]
            max_volume = max(max_volume, point[6])
            if point[4] >= point[1]:
                v_open = v_low
                v_close = v_high
            else:
                v_open = v_high
                v_close = v_low
            volume_candle = QCandlestickSet(v_open, v_high, v_low, v_close,
                                            point[0] * 1000, self)
            self.VolumeBarSeries.append(volume_candle)

        if not self._chart_view._chart_loaded:
            self._chart_view.chart.addSeries(self.CandlestickSeries)
            self._chart_view_volume.chart().addSeries(self.VolumeBarSeries)
            self._chart_view._chart_loaded = True

        axis_x = QDateTimeAxis()
        axis_x.setFormat("dd-MM-yyyy h:mm")
        axis_x.setRange(datetime.fromtimestamp(int(t_min) - 30 * interval),
                        datetime.fromtimestamp(int(t_max) + 30 * interval))
        self._chart_view.chart.setAxisX(axis_x, self.CandlestickSeries)

        axis_y = QValueAxis()
        axis_y.setRange(min_y, max_y)
        self._chart_view.chart.setAxisY(axis_y, self.CandlestickSeries)

        axis_x2 = QDateTimeAxis()
        axis_x2.setFormat("dd-MM-yyyy h:mm")
        axis_x2.setRange(datetime.fromtimestamp(int(t_min) - 30 * interval),
                         datetime.fromtimestamp(int(t_max) + 30 * interval))
        self._chart_view_volume.chart().setAxisX(axis_x2, self.VolumeBarSeries)

        axis_y2 = QValueAxis()
        axis_y2.setRange(0, max_volume)
        self._chart_view_volume.chart().setAxisY(axis_y2, self.VolumeBarSeries)
コード例 #20
0
ファイル: figure.py プロジェクト: wingsof/trader
 def add_candle_stick(self, q, o, h, l, c):
     if self.in_datetime_range(q):
         self.candle_stick_series.append(QCandlestickSet(o, h, l, c, q))