-
-
Save yijhan/8ec6d4e05b017e673a4bf1ac72828139 to your computer and use it in GitHub Desktop.
pythonnet clr 操作 skcomapi 範例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 使用 pythonnet 呼叫群益api | |
import clr | |
# AddReference,不用加副檔名 .dll | |
clr.AddReference(r"C:\skcom\CapitalAPI_2.13.41\x64\SKCOMLib") # 使用絕對路徑我個人偏好這個 | |
# 加入參考後,利用 improt SKCOMLib 可以使用群益整個 skcomapi 的功能, | |
import SKCOMLib | |
# 也可以 from SKCOMlib import 部分功能 | |
from SKCOMLib import SKCenterLib, SKReplyLib, SKQuoteLib, SKSTOCKLONG | |
# 推動eventloop用 | |
import time | |
import pythoncom | |
# 使用 skcom 元件 | |
skC = SKCenterLib() | |
skR = SKReplyLib() | |
skQ = SKQuoteLib() | |
##################################################### | |
# Configuration | |
ID = "" | |
PW = "" | |
# 欲報價的商品代號 | |
StockNo = "1101,2330" | |
# working function | |
# resqest stock | |
def request_stock(page, stocks): | |
ncode, _ = skQ.SKQuoteLib_RequestStocks(page, stocks) | |
print(f"Request stock: {stocks}", skC.SKCenterLib_GetReturnCodeMessage(ncode)) | |
##################################################### | |
# Event callback | |
# SKReplyLib 相關 callback | |
def OnReplyMessage(bstrUserID , bstrMessage, sConfirmCode): | |
# 這個一定要,Login 時會檢查 sConfirmCode 是否 == -1 | |
sConfirmCode = -1 | |
print("OnReplyMessage", bstrMessage) | |
return sConfirmCode | |
# SKQuoteLib 相關 | |
def OnConnection(nKind, nCode): | |
"""回報連線報價伺服器狀態 | |
nKind: 3001 連線報價伺服器 | |
3002 離線報價伺服器 | |
3003 連線成功,收到3003後,始可登錄報價商品 | |
""" | |
print(f'skQ_OnConnection nKind= {nKind}', skC.SKCenterLib_GetReturnCodeMessage(nKind)) | |
if nKind == 3003: | |
request_stock(1, StockNo) | |
def OnNotifyQuoteLONG(sMarketNo, nIndex): | |
"""報價""" | |
ts = SKSTOCKLONG() | |
ncode, ts = skQ.SKQuoteLib_GetStockByIndexLONG(sMarketNo, nIndex, ts) | |
print(ts.bstrStockName, "市價", ts.nClose/ 10**ts.sDecimal, "單量", ts.nTickQty) | |
##################################################### | |
# 綁定 event callback,需一個一個綁定,如果有比較快的方法請跟我分享 :) | |
# 請查閱SKCOMapi手冊有哪些 Callback,及相關參數 | |
skR.OnReplyMessage += OnReplyMessage | |
skQ.OnConnection += OnConnection | |
skQ.OnNotifyQuoteLONG += OnNotifyQuoteLONG | |
print("綁定各元件的event callback") | |
#################################################### | |
# Login | |
ncode = skC.SKCenterLib_Login(ID, PW) | |
print("Login", skC.SKCenterLib_GetReturnCodeMessage(ncode)) | |
# EnterMonitor | |
ncode = skQ.SKQuoteLib_LeaveMonitor() | |
ncode = skQ.SKQuoteLib_EnterMonitorLONG() | |
print("EnterMonitor", skC.SKCenterLib_GetReturnCodeMessage(ncode)) | |
# pump events for 30 seconds | |
print("Pumping events for 30s") | |
for i in range(30): | |
pythoncom.PumpWaitingMessages() | |
time.sleep(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment