iT邦幫忙

2021 iThome 鐵人賽

DAY 12
0
永豐金融APIs

永豐金融APIs - 從零開始到放棄!?系列 第 12

繪圖 - 即時成交資料

以下內容,都是 shioaji 的官網文件的內容,只是加了一些我自己的理解,感謝永豐提供這麼完整的 sample code

繪圖會用到 numpy, pandas, bqplot...等套件,如果之前沒有安裝,可以先行安裝

pip install numpy pandas bqplot
  • 引用套件
import json
import datetime as dt
import numpy as np
import pandas as pd
import bqplot as bq
import shioaji as sj
  • 登入 shioaji
api = sj.Shioaji()
api.login(person_id="帳號", passwd="密碼")
  • 建立表格的資料集
ask_bid_period_length = 500
ask_bid_static = np.zeros((6, ask_bid_period_length))
ask_deal_count = 0
bid_deal_count = 0


tick_plot_length = 150
new_index = 0
new_vol = 1

data_in = np.random.rand(2)
data_inner = np.random.rand(2)
data_outer = np.random.rand(4)
  • 建立繪圖的方法
def pie_chart():
    global data_in, data_inner, data_outer
    global pie_outer, pie_inner, pie_in
    outer_pie_radius = [180, 150]
    inner_pie_radius = [100, 70]
    in_pie_radius = [50, 10]

    pie_outer = bq.Pie(
        size = data_outer,
        display_labels = "outside",
        apply_clip = False,
        radius = outer_pie_radius[0],
        inner_radius = outer_pie_radius[1],
        display_values = True,
        values_format = '.0%',
        colors = ['red', 'limegreen', 'red', 'limegreen'],
        labels = ['大單委賣成交', '大單委買成交', '小單委賣成交', '小單委買成交']
    )
    
    pie_inner = bq.Pie(
        size = data_inner,
        display_labels = 'inside',
        apply_clip = False,
        radius = inner_pie_radius[0],
        inner_radius = inner_pie_radius[1],
        display_value = True,
        values_format = '.0%',
        colors = ['red', 'limegreen'],
        labels = ['賣成筆', '買成筆']
    )
    
    pie_in = bq.Pie(
        size = data_in,
        display_labels = 'inside',
        radius = in_pie_radius[0],
        inner_radius = inner_pie_radius[1],
        display_values = True,
        values_format = '.0%',
        colors = ['limegreen', 'red'],
        labels = ['賣成口', '買成口']
    )
    
    fig = bq.Figure(
        marks = [pie_outer, pie_inner, pie_in],
        animation_duration = 1000,
    )
    
    return fig
  • 建立資料處理方法
def proc_ask_bid_staticdata(topic, quote_msg, vol_threshold):
    global ask_bid_static
    global small_bid_deal_volsum, ask_deal_count, bid_deal_count
    ask_volsum = quote_msg.get('TradeAskVolSum', 0)
    bid_volsum = quote_msg.get('TradeBidVolSum', 0)
    new_vol = quote_msg.get('Volume', [0,])[-1]
    
    ask_bid_static[:, :-1] = ask_bid_static[:, 1:]
    if new_askbid_color_data == 1:
        ask_deal_count += 1
        ask_bid_static[4][-1] = 1
        ask_bid_static[5][-1] = 0
        if new_vol >= vol_threshold:
            ask_bid_static[0][-1] = new_vol
        else:
            ask_bid_static[1][-1] = new_vol
    elif new_askbid_color_data == 2:
        bid_deal_count += 1
        ask_bid_static[5][-1] = 1
        ask_bid_static[4][-1] = 0
        if new_vol >= vol_threshold:
            ask_bid_static[2][-1] = new_vol
        else:
            ask_bid_static[3][-1] = new_vol
    
    ask_bid_static_sum = ask_bid_static.sum(axis=1)
    data_outer = ask_bid_static_sum[:4]
    data_inner = ask_bid_static_sum[4:]
    data_in = np.array([ask_volsum, bid_volsum])
  • 建立圖表更新方法
def update_pie_chart(update_freq):
    global pie_outer, pie_inner, pie_in

    if (new_index % update_freq) == 0 and new_index >= tick_plot_length:
        with pie_outer.hold_sync() and pie_inner.hold_sync() and pie_in.hold_sync():
            pie_outer.sizes = data_outer / data_outer.sum()
            pie_inner.sizes = data_inner / data_inner.sum()
            pie_in.sizes = data_in / data_in.sum()
  • 建立取得價格後的回呼方法
@sj.on_qoute
def qoute_callback(topic, quote_msg):
    global tick_plot_length
    global pie_outer, pie_inner, pie_in
    global new_index, new_vol
    global large_ask_deal_volsum, small_ask_deal_volsum, large_bid_deal_volsum
    global large_bid_deal_volsum, ask_deal_count, bid_deal_count
    global ask_bid_static
    vol_threshold = 10

    if topic.startswith('L'):
        proc_ask_bid_staticdata(topic, quote_msg, vol_threshold)
        update_pie_chart(update_freq=1)
  • 建立 solace 事件回呼方法
@sj.on_event
def event_callback(resp_code, event_code, event):
    print("Response Code: {} | Event Code: {} | Event: {}".format(resp_code, event_code, event))
  • 設定回呼方法
api.quote.set_callback(quote_callback)
api.quote.set_event_callback(event_callback)
  • 繪圖
pie_chart()
  • 訂閱報價
stock2330 = api.Contracts.Stocks["2330"]
api.quote.subscribe(stock2330, quote_type="bidask")

因為我是在盤後才跑這個程式,所以沒有辦法取得即資料,所以暫時不確定以上的程式能不能正確運行,之後如果有機會在交易時間跑的話,會再驗證,如果有問題的話,會再修改。


上一篇
繪圖 - 即時 tick 資料
下一篇
LineBot - 申請
系列文
永豐金融APIs - 從零開始到放棄!?30

尚未有邦友留言

立即登入留言