以下內容,都是 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
api = sj.Shioaji()
api.login(person_id="帳號", passwd="密碼")
today = dt.date.today()
df_min = pd.DataFrame(
index=pd.date_range(
start=dt.datetime(*(today.year, today.month, today.day, 8, 45)),
end=dt.datetime(*(today.year, today.month, today.day, 13, 45)),
freq='1T'),
columns=['open', 'high', 'low', 'close'],
dtype=float,
)
# ohlc: open high low close
def init_ohlc_chart():
global ohlc_chart
sc = bq.LinearScale()
dt_scale = bq.DateScale()
ax_x = bq.Axis(label="datetime", scale=dt_scale)
ax_y = bq.Axis(lable="price", scale=sc, orientation="vertical", tick_format="0.0f")
# 建立標記
ohlc_chart = bq.OHLC(
x=df_min.index,
y=df_min.dropna().values,
marker='candle',
scales={ 'x': dt_scale, 'y': sc },
format='ohlc',
opcities=[0.85 for _ in df_min.index],
display_legend=True,
labels=['台積電']
)
fig = bq.Figure(axes=[ax_x, ax_y], marks=[ohlc_chart])
return fig
def proc_ohlc_data(quote_msg, new_deal_price):
global df_min
ts = pd.Timestamp("{Date} {Time}".format(**quote_msg)).replace(second=0, microsecond=0)
df_min.loc[ts, 'open'] = new_deal_price if np.isnan(df_min.loc[ts, 'open']) else df_min.loc[ts, 'open']
df_min.loc[ts, 'high'] = new_deal_price if np.isnan(df_min.loc[ts, 'high']) else df_min.loc[ts, 'high']
df_min.loc[ts, 'low'] = new_deal_price if np.isnan(df_min.loc[ts, 'low']) else df_min.loc[ts, 'low']
df_min.loc[ts, 'close'] = new_deal_price
def update_ohlc_chart():
global ohlc_chart
with ohlc_chart.hold_sync():
ohlc_chart.x = df_min.dropna().index
ohlc_chart.y = df_min.dropna().values
@sj.on_quote
def quote_callback(topic, quote_msg):
global new_deal_price
print(topic, quote_msg)
proc_ohlc_data(quote_msg, new_deal_price)
update_ohlc_chart()
@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)
init_ohlc_chart()
因為我是在盤後才跑這個程式,所以沒有辦法取得即資料,所以暫時不確定以上的程式能不能正確運行,之後如果有機會在交易時間跑的話,會再驗證,如果有問題的話,會再修改。
另外,我自己用 api.ticks() 的方法,把當天的 ticks 資料抓下來再去進行繪制,我想應該和最後的結果是一樣的吧
ticks2330 = api.ticks(stock2330)
dt_index = list(map(lambda x:dt.datetime.utcfromtimestamp(x/1000000000), ticks2330.ts))
print(df_min)
prevTime = ""
open_price = 0
high_price = 0
low_price = 0
close_price = 0
for i in range(len(dt_index)):
currTime = dt_index[i].strftime("%Y-%m-%d %H:%M:00")
if currTime != prevTime:
open_price = ticks2330.close[i]
high_price = ticks2330.close[i]
low_price = ticks2330.close[i]
close_price = ticks2330.close[i]
prevTime = currTime
else:
high_price = max(high, ticks2330.close[i])
low_price = min(low, ticks2330.close[i])
close_price = ticks2330.close[i]
df_min.loc[currTime, "open"] = open_price
df_min.loc[currTime, "high"] = high_price
df_min.loc[currTime, "low"] = low_price
df_min.loc[currTime, "close"] = close_price
init_ohlc_chart()