Biblioteca de classes de desenho da versão Python (compatível 2/3)

Autora:Sonhos pequenos, Data: 2017-04-10 17:20:26
Tags:FerramentaPythonGráfico

Simplificou a lógica das linhas de gráficos de estratégia, permitindo que as funções que já estão envelopadas sejam chamadas diretamente

  • Suporte para desenhar linhas múltiplas
  • Suporte para K-string
  • Suporte para flag miniaturizado
  • Você também pode adicionar mais suporte para gráficos.

Funcionalidade equivalente à versão JS

Transporte para a versão JS da biblioteca de linhas gráficas

Se tiver alguma dúvida, entre em contato com o pequeno sonho 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)



Relacionados

Mais.

churchillxyOlá, quando eu uso o PlotFlag, muitas vezes eu perco a bandeira já pintada depois de refrescar a página, por favor, há alguma solução?

churchillxyPode-se juntar várias k-strings em um gráfico? Por exemplo: k-string de btc + k-string de ETH

m0606Parece ser uma biblioteca de linhas gráficas compatível com dois terços do Python.

LWC87Professor, você tem alguma instrução sobre como usar esta função de modelo, porque os parâmetros não funcionam?

HaorenVocê pode encontrar um gráfico personalizado? Junte várias linhas k em um ícone; por exemplo: linha de preço btc + linha de preço ltc + linha de preço eth + linha de preço multicurrency combinada etc, apenas algumas linhas em um gráfico, assim como várias linhas de preço comuns no gráfico k, todas mostradas no mesmo gráfico

LogaGlória!

Sonhos pequenosO problema é que não é possível passar erros em alguns parâmetros.

churchillxyO problema foi resolvido, o número de títulos é limitado, o texto pode ser rico, não pode ser invertido, obrigado.

Sonhos pequenosA marca que foi desenhada, que não deveria ser perdida, que foi desenhada, que você não pode alterar, não vai mudar, é fixa.

Sonhos pequenosNo gráfico acima, você marca apenas o número de dados exibidos em cada divisão de página no FMZ. Se um gráfico tiver 100.000 dados, você configura aqui que cada divisão de página exiba 10.000 dados, e esses 100.000 dados serão exibidos em 10 páginas separadas.

churchillxyQual é o limite de dados por página aqui? Como é que os meus dados excedem esse limite? /upload/asset/245f7442dfa3212019b47.png

Sonhos pequenosA biblioteca de linhas pode ser desenhada com a última biblioteca de linhas multicartográficas.

Sonhos pequenosA função principal no modelo é um exemplo de uso, veja aqui.

Sonhos pequenosObrigado pelo apoio! Se você tiver alguma dúvida, deixe um comentário^^