파이썬 버전 드로잉 클래스 라이브러리 (2/3)

저자:작은 꿈, 날짜: 2017-04-10 17:20:26
태그:도구파이썬차트

전략 그래프 그림 줄의 논리를 단순화하여 포장된 함수를 직접 호출할 수 있습니다.

  • 여러 줄을 그리는 것을 지원합니다.
  • K줄 지도를 지원합니다.
  • 플래그 소형 아이콘 지원
  • 더 많은 그래픽을 지원할 수도 있습니다.

JS 버전과 동일한 기능

JS 버전으로 이식

궁금한 사항은 소아몽 359706687에 문의하십시오.


# Python 2/3 兼容版本
import time
chart = None
series = []
labelIdx = {}
preBarTime = 0
preFlagTime = 0
preDotTime = {}

cfg = {
    "tooltip" : {
        "xDateFormat" : "%Y-%m-%d %H:%M:%S, %A"
    },
    "legend" : {
        "enabled" : True
    },
    "plotOptions" : {
        "candlestick" : {
            "color" : "#d75442",
            "upColor" : "#6ba583"
        }
    },
    "rangeSelector" : {
        "buttons" : [{
            "type" : "hour",
            "count" : 1,
            "text" : "1h",
        }, {
            "type" : 'hour',
            "count" : 3,
            "text" : "3h"
        }, {
            "type" : "hour",
            "count" : 8,
            "text" : "8h"
        }, {
            "type" : "all",
            "text" : "All"
        }],
        "selected" : 2,
        "inputEnabled" : True
    },
    "series" : series,
}

def GetCfg():
    global cfg
    return cfg

# 画水平线
def PlotHLine(value = None, label = None, color = None, style = None):
    global cfg, chart
    if ("yAxis" in cfg) == False :
        cfg.setdefault("yAxis", {"plotLines" : []})
    elif ("plotLines" in cfg["yAxis"]) == False :
        cfg["yAxis"].setdefault("plotLines", [])
    
    obj = {
        "value" : value,
        "color" : color or "red",
        "width" : 2,
        "dashStyle" : style or "Solid",
        "label" : {
            "text" : label or "",
            "align" : "center"
        }
    }
    found = False
    for i in range(len(cfg["yAxis"]["plotLines"])) : 
        if cfg["yAxis"]["plotLines"][i]["label"]["text"] == label : 
            cfg["yAxis"]["plotLines"][i] = obj
            found = True
    if not found :
        cfg["yAxis"]["plotLines"].append(obj)
    if not chart :
        chart = Chart(cfg)
        chart.update(cfg)    # 更新图表
    else :
        chart.update(cfg)

# 画K线
def PlotRecords(records, title = None):
    global labelIdx, series, preBarTime, chart
    if not chart :
        chart = Chart(cfg)
        chart.reset()
    if ("candlestick" in labelIdx) == False : 
        cfg["__isStock"] = True
        seriesIdx = len(series)
        series.append({
            "type" : "candlestick",
            "name" : "" if title == None else title,
            "id" : "primary",
            "data" : []
            })
        chart.update(cfg)
        labelIdx.setdefault("candlestick", seriesIdx)
    else :
        seriesIdx = labelIdx["candlestick"]
    if isinstance(records, dict) and ("Time" in records) == True :
        Bar = records
        if Bar["Time"] == preBarTime :
            chart.add(seriesIdx, [Bar["Time"], Bar["Open"], Bar["High"], Bar["Low"], Bar["Close"]], -1)
        elif Bar["Time"] > preBarTime : 
            preBarTime = Bar.Time
            chart.add(seriesIdx, [Bar["Time"], Bar["Open"], Bar["High"], Bar["Low"], Bar["Close"]])    
    else :
        for i in range(len(records)) :
            if records[i]["Time"] == preBarTime :
                chart.add(seriesIdx, [records[i]["Time"], records[i]["Open"], records[i]["High"], records[i]["Low"], records[i]["Close"]], -1)
            elif records[i]["Time"] > preBarTime :
                preBarTime = records[i]["Time"]
                chart.add(seriesIdx, [records[i]["Time"], records[i]["Open"], records[i]["High"], records[i]["Low"], records[i]["Close"]])
    return chart

# 画指标线
def PlotLine(label, dot, Ntime = None):
    global labelIdx, chart, series, preDotTime
    if not chart :
        cfg.setdefault("xAxis", {
            "type" : "datetime"
            })
        chart = Chart(cfg)
        chart.reset()
    if (label in labelIdx) == False :
        seriesIdx = len(series)
        preDotTime.setdefault(str(seriesIdx), 0)
        labelIdx[label] = seriesIdx
        series.append({
            "type" : "line",
            "yAxis" : 0,
            "showInLegend" : True,
            "name" : label,
            "data" : [],
            "tooltip" : {"valueDecimals" : 5}
            })
        chart.update(cfg)
    else :
        seriesIdx = labelIdx[label]
    if Ntime == None :
        Ntime = _N(time.time() * 1000, 0)
    if preDotTime[str(seriesIdx)] != Ntime :
        preDotTime[str(seriesIdx)] = Ntime
        chart.add(seriesIdx, [Ntime, dot])
    else :
        chart.add(seriesIdx, [Ntime, dot], -1)
    return chart

# 画标记
def PlotFlag(time, text, title, shape = "", color = ""):
    global chart, cfg, labelIdx, preFlagTime
    if not chart :
        chart = Chart(cfg)
        chart.reset()
    label = "flag"
    if (label in labelIdx) == False : 
        seriesIdx = len(series)
        labelIdx[label] = seriesIdx
        series.append({
            "type" : "flags",
            "onSeries" : "primary",
            "data" : []
            })
        chart.update(cfg)
    else :
        seriesIdx = labelIdx[label]
    obj = {
        "x" : time,
        "color" : color,
        "shape" : shape,
        "title" : title,
        "text" : text
    }
    if preFlagTime != time : 
        preFlagTime = time
        chart.add(seriesIdx, obj)
    else :
        chart.add(seriesIdx, obj, -1)
    return chart

# 设置图表标题
def PlotTitle(title, chartTitle = None):
    global cfg
    if ("subtitle" in cfg) == True : 
        cfg["subtitle"] = {"text" : title}
    else :
        cfg.setdefault("subtitle", {"text" : title})
    if chartTitle != None :
        if (title in cfg) == True :
            cfg["title"] = {"text" : chartTitle}
        else :
            cfg.setdefault("title", {"text" : chartTitle})
    if chart :
        chart.update(cfg)

# 导出函数
ext.GetCfg = GetCfg
ext.PlotHLine = PlotHLine
ext.PlotRecords = PlotRecords
ext.PlotLine = PlotLine
ext.PlotFlag = PlotFlag
ext.PlotTitle = PlotTitle

# 测试代码
def main():
    isFirst = True
    while True:
        records = exchange.GetRecords()
        if records and len(records) > 0 :
            ext.PlotRecords(records, "BTC")
            if isFirst :
                ext.PlotFlag(records[-1]["Time"], "Start", "S")
                isFirst = False
                ext.PlotHLine(records[-1]["Close"], "Close")
        ticker = exchange.GetTicker()
        if ticker :
            ext.PlotLine("Last", ticker.Last)
            ext.PlotLine("buy", ticker.Buy + 10)
            ext.PlotTitle("Last" + str(ticker.Last))
        Sleep(60000)



관련

더 많은

처칠시안녕하세요, 제가 플롯 플래그를 호출할 때 페이지 갱신 후 이미 그려진 플래그가 자주 사라집니다. 이 문제를 해결할 수 있나요?

처칠시예를 들어, BTC의 K줄 + ETH의 K줄

m0606Python의 2/3를 호환하는 그림줄 클래스 라이브러리처럼 보입니다.

LWC87이 템플릿 함수의 사용에 대한 설명이 있나요?

하오렌이 그래프에서 몇 개의 k 라인을 하나의 아이콘으로 묶어 볼 수 있나요? 예를 들어, BTC 가격 라인 + LTC 가격 라인 + Eth 가격 라인 + 다화폐 합성 가격 라인 등, 몇 개의 라인이 하나의 그래프에 있는 것처럼,

로가찬!

작은 꿈, 몇 가지 매개 변수는 잘못 전달되지 않습니다.

처칠시이 문제는 해결되었습니다. 제목의 수는 제한되어 있습니다. 텍스트는 풍부하고 뒤집어 놓을 수 없습니다.

작은 꿈이미 그려진 표지판은 사라지지 않아야 한다고 여겨지고, 이미 그려진 표지판은 당신이 그것을 바꾸지 않으면 변하지 않고 고정되어 있습니다.

작은 꿈이 그래프는 FMZ 페이지에만 표시되는 데이터의 수를 나타냅니다. 그래프에 100,000개의 데이터가 있다면, 여기서는 모든 FMZ 페이지에 10,000개의 데이터를 표시하도록 설정합니다. 이 설정은 FMZ 페이지의 표시에 대한 제어입니다.

처칠시이 페이지에 대한 데이터 제한은 무엇입니까? 이 제한을 초과하면 어떻게 표시해야합니까? /upload/asset/245f7442dfa3212019b47.png

작은 꿈최신의 멀티 그래프로 라인 클래스를 그리면 됩니다. 이 클래스는 단 하나만 그릴 수 있습니다.

작은 꿈템플릿 안의 main 함수는 사용 예제입니다.

작은 꿈감사합니다. 궁금한 점이 있다면 댓글을 달아주세요^^