開始使用
元富行情 WebSocket API 提供台股即時行情服務。透過 WebSocket API 可以滿足您想要接收即時行情的需求。
使用 SDK
元富行情 WebSocket API 提供 Python 、 Node.js 您可以透過以下方式存取 WebSocket API :
訂閱WebSocket Callback 方法獲得下方Callback訊息。
- Python
- Node.js
from masterlink_sdk import MasterLinkSDK
def handle_message(message):
print(message)
sdk = MasterlinkSDK()
accounts = sdk.login("Your ID", "Your password", "Your cert path", "Your cert password") # 需登入後,才能取得行情權限
sdk.init_realtime(accounts[0]) # 建立行情連線
futopt = sdk.marketdata.websocket_client.futopt
futopt.on('message', handle_message)
futopt.connect()
const { MasterlinkSDK } = require('masterlink');
const sdk = new MasterlinkSDK();
const accounts = sdk.login("Your ID", "Your password", "Your cert path", "Your cert password");
sdk.initRealtime(accounts[0]); // 建立行情連線
const futopt = sdk.marketdata.webSocketClient.futopt;
futopt.connect()
futopt.on("message", (message) => {
const data = JSON.parse(message);
console.log(data);
});
身份驗證
當驗證成功後,會收到以下訊息:
{
"event": "authenticated",
"data": {
"message": "Authenticated successfully"
}
}
若驗證失敗,則收到以下訊息:
{
"event": "error",
"data": {
"message": "Invalid authentication credentials"
}
}
Heartbeat
每隔 30 秒 WebSocket server 會送出一個 heartbeat 訊息:
{
"event": "heartbeat",
"data": {
"time": "<Timestamp>"
}
}
Ping/Pong
SDK每五秒,將自動發送ping到server中, 也可自行發送ping ,另外額外自訂 state
(state 為optioanal參數) :
- Python
- Node.js
futopt.ping({
'state' : '<ANY>'
})
futopt.ping({state:'<ANY>'});
WebSocket Server 會回應以下訊息 (若 ping 未送 state
則不會有該欄位):
{
"event": "pong",
"data": {
"time": "<TIMESTAMP>",
"state": "<ANY>"
}
}
Channels
元富行情 WebSocket API 目前提供以下可訂閱頻道:
trades
- 接收訂閱期權商品最新成交資訊books
- 接收訂閱期權商品最新最佳五檔委買委賣資訊
訂閱頻道
要訂閱一個頻道可用下方範例進行訂閱:
- Python
- Node.js
futopt.subscribe({
"channel" : "<CHANNEL_NAME>",
"symbol" : "<SYMBOL_ID>"
#"afterHours" : True 若要訂閱夜盤行情,可再額外加入此參數
})
futopt.subscribe({
channel: '<CHANNEL_NAME>',
symbol: '<SYMBOL_ID>',
//afterHours : true 若要訂閱夜盤行情,可再額外加入此參數
});
訂閱成功後,會收到以下事件回應:
{
"event": "subscribed",
"data": {
"id": "<CHANNEL_ID>",
"channel": "<CHANNEL_NAME>",
"symbol": "<SYMBOL_ID>"
}
}
支援訂閱同頻道的多檔股票:
- Python
- Node.js
futopt.subscribe({
"channel" : "<CHANNEL_NAME>",
"symbols" : ["<SYMBOL_ID>","<SYMBOL_ID>"]
#"afterHours" : True 若要訂閱夜盤行情,可再額外加入此參數
})
futopt.subscribe({
channel: '<CHANNEL_NAME>',
symbols: ['<SYMBOL_ID>','<SYMBOL_ID>']
//afterHours : true 若要訂閱夜盤行情,可再額外加入此參數
});
訂閱成功後,會收到以下事件回應:
{
"event": "subscribed",
"data": [
{
"id": "<CHANNEL_ID>",
"channel": "<CHANNEL_NAME>",
"symbol": "<SYMBOL_ID_1>"
},
{
"id": "<CHANNEL_ID>",
"channel": "<CHANNEL_NAME>",
"symbol": "<SYMBOL_ID_2>"
}
]
}
取消訂閱
要取消頻道可用下方範例進行取消:
- Python
- Node.js
futopt.unsubscribe({
'id':'<CHANNEL_ID>'
})
futopt.unsubscribe({
id : '<CHANNEL_ID>'
});
取消訂閱成功後,會收到以下事件回應:
{
"event": "unsubscribed",
"data": {
"id": "<CHANNEL_ID>"
}
}
支援取消訂閱多個頻道:
- Python
- Node.js
futopt.unsubscribe({
'ids':['<CHANNEL_ID>','<CHANNEL_ID>']
})
futopt.unsubscribe({
ids : ['<CHANNEL_ID>','<CHANNEL_ID>']
});
取消訂閱成功後,會收到以下事件回應:
{
"event": "unsubscribed",
"data": [
{
"id": "<CHANNEL_ID_1>"
},
{
"id": "<CHANNEL_ID_2>"
}
]
}
錯誤處理
當您所訂閱或處理的WebSocket Callback有異常時,您可補充處理錯誤訊息如下 :
- Python
- Node.js
def handle_connect():
print('market data connected')
def handle_disconnect(code, message):
print(f'market data disconnect: {code}, {message}')
def handle_error(error):
print(f'market data error: {error}')
futopt.on("connect", handle_connect)
futopt.on("disconnect", handle_disconnect)
futopt.on("error", handle_error)
futopt.on("connect", (message) => {
const connect_msg = JSON.parse(message);
console.log(connect_msg);
});
futopt.on("disconnect", (message) => {
console.log(message);
});
futopt.on("error", (message) => {
const err_msg = JSON.parse(message);
console.log(err_msg);
});
斷線重連
以下將用簡單範例,利用上述定義之錯誤處理方法,接收到斷線事件,程式自動進行連線
- Python
- Node.js
def handle_disconnect(code, message):
print(f'market data disconnect: {code}, {message}')
futopt.connect()
print("Reconnected Succuess")
print("Resubscribe")
futopt.subscribe({ # 重新訂閱您已訂閱過的Channel與Symbol
'channel': '<CHANNEL_NAME>',
'symbol': '<SYMBOL_ID>'
})
futopt.on("disconnect", (message) => {
console.log(message);
futopt.connect()
console.log("Reconnected Succuess");
futopt.subscribe({ channel: '<CHANNEL_NAME>', symbol: '<SYMBOL_ID>' }); //重新訂閱您已訂閱過的Channel與Symbol
});