Skip to main content

Quick Start

Key takeaways
  • Fubon Market Data WebSocket API provides real-time market data subscriptions.
  • Supports Speed and Normal modes.
  • Login is required before subscribing to channels.
ItemDetails
InterfaceWebSocket API
MarketTaiwan equities
ModesSpeed / Normal
SDKPython / Node.js / C#
SubscriptionConnect then subscribe to channels

Fubon Market Data WebSocket API provides real-time stock market data services for Taiwan. Use WebSocket to receive real-time market data.

Using SDK​

Fubon Market Data WebSocket API provides Python, Node.js, and C# SDKs. You can access the WebSocket API through the following methods:

And subscribe webSocket callback method to receive the callback messages below.

info

WebSocket API provides the low-latency Speed mode and the multi-information Normal mode.

from fubon_neo.sdk import FubonSDK, Mode

def handle_message(message):
print(message)

sdk = FubonSDK()
accounts = sdk.login("Your ID", "Your password", "Your cert path", "Your cert password") # 需登入後,才能取得行情權限

sdk.init_realtime() # Establish market-data
# Offer MarketData Mode , Default : Speed
# sdk.init_realtime(Mode.Speed) or sdk.init_realtime(Mode.Normal)

stock = sdk.marketdata.websocket_client.stock
stock.on('message', handle_message)
stock.connect()

Authenticated​

When the verification is successful, you will receive the following message:

{
"event": "authenticated",
"data": {
"message": "Authenticated successfully"
}
}

When the verification is failed, you will receive the following message:

{
"event": "error",
"data": {
"message": "Invalid authentication credentials"
}
}

Heartbeat​

Every 30 seconds, the WebSocket server will send out a heartbeat message:

{
"event": "heartbeat",
"data": {
"time": "<Timestamp>"
}
}

Ping/Pong​

Every 30 seconds, the SDK will send the following JSON-formatted message to the WebSocket Server, or follow the below example (where state is optional):

stock.ping('<ANY>')

The WebSocket Server will respond with the following message (if ping was sent, the state field will not be present):

{
"event": "pong",
"data": {
"time": "<TIMESTAMP>",
"state": "<ANY>"
}
}

Channels​

The Fubon Market Data WebSocket API currently provides the following subscribable channels:

Subscribe Channel​

Subscribe to a channel, send following example to the WebSocket Server:

stock.subscribe({
"channel" : "<CHANNEL_NAME>",
"symbol" : "<SYMBOL_ID>"
#"intradayOddLot": True Subscribe intradayOdd
})

After a successful subscription, you will receive the following event response:

{
"event": "subscribed",
"data": {
"id": "<CHANNEL_ID>",
"channel": "<CHANNEL_NAME>",
"symbol": "<SYMBOL_ID>"
}
}

Supports the subscription of multiple stocks within the same channel:

stock.subscribe({
"channel" : "<CHANNEL_NAME>",
"symbols" : ["<SYMBOL_ID>","<SYMBOL_ID>"]
#"intradayOddLot": True Subscribe intradayOdd
})

After a successful subscription, you will receive the following event response:

{
"event": "subscribed",
"data": [
{
"id": "<CHANNEL_ID>",
"channel": "<CHANNEL_NAME>",
"symbol": "<SYMBOL_ID_1>"
},
{
"id": "<CHANNEL_ID>",
"channel": "<CHANNEL_NAME>",
"symbol": "<SYMBOL_ID_2>"
}
]
}

Unsubscribe​

Unsubscribe from a subscribed channel, please send the following example to WebSocket Server:

stock.unsubscribe({
'id':'<CHANNEL_ID>'
})

After a successful unsubscription, you will receive the following event response:

{
"event": "unsubscribed",
"data": {
"id": "<CHANNEL_ID>",
"channel" : "<CHANNEL_NAME>",
"symbol" : "<SYMBOL_ID>"
}
}

Supports the unsubscription from multiple channels:

stock.unsubscribe({
'ids':['<CHANNEL_ID>','<CHANNEL_ID>']
})

After a successful unsubscription, you will receive the following event response:

{
"event": "unsubscribed",
"data": [
{
"id": "<CHANNEL_ID_1>",
"channel" : "<CHANNEL_NAME>",
"symbol" : "<SYMBOL_ID>"
},
{
"id": "<CHANNEL_ID_2>",
"channel" : "<CHANNEL_NAME>",
"symbol" : "<SYMBOL_ID>"
}
]
}

Subscriptions​

To list the channels currently subscribed on this connection, use the following example:

stock.subscriptions()

You will receive the following event response:

{
"event": "subscriptions",
"data": [
{
"id": "<CHANNEL_ID>",
"channel": "<CHANNEL_NAME>",
"symbol": "<SYMBOL_ID>"
}
]
}

Error Handle​

When there is an anomaly in the WebSocket callback you subscribed to or processed, you can handle error messages as follows.

The disconnect event fires in two cases: the server closes the connection, or the connection health check times out — when no message of any kind has arrived from the server for roughly 60 seconds, the SDK closes the connection itself and emits this event. How a timeout is reported in each language is noted under its example.

def handle_connect():
print('market data connected')


def handle_disconnect(code, message, *reason): # a health-check-timeout disconnect passes one extra argument
print(f'market data disconnect: {code}, {message}')


def handle_error(error):
print(f'market data error: {error}')

stock.on("connect", handle_connect)
stock.on("disconnect", handle_disconnect)
stock.on("error", handle_error)

On a health-check timeout, disconnect passes one extra argument {'reason': 'health-check-timeout'}; *reason in the handler catches it.

Reconnection​

After a disconnection the SDK neither reconnects on its own nor keeps your subscriptions; your program has to reconnect when it receives the disconnect event and send every subscription again. The following example continues from the login and connection code above: on a disconnect event it reconnects and resubscribes in the background, with a growing delay between attempts (2, 4, 8, 16, 30 seconds) and a limit of 5 attempts, so that a network that has not recovered yet is not flooded with reconnects. Keep one entry per channel in the subscription list and subscribe to several symbols at once with symbols, so the number of subscribe calls after a reconnect equals the number of channels rather than the number of symbols.

# continue after stock = sdk.marketdata.websocket_client.stock; replaces the original stock.connect()
import threading
import time

SUBSCRIPTIONS = [ # one list shared by the first subscription and every resubscription; one entry per channel, several symbols via symbols
{'channel': 'trades', 'symbols': ['2330', '2317']},
]
reconnect_needed = threading.Event()

def handle_disconnect(code, message, *reason): # a health-check-timeout disconnect passes one extra argument; *reason catches it
print(f'market data disconnect: {code}, {message}')
reconnect_needed.set() # notify only; do not reconnect here

def subscribe_all():
for params in SUBSCRIPTIONS:
stock.subscribe(params)

def connect_with_timeout(seconds=10):
# connect() never returns while the network is down; run it in a thread with a timeout
result = {}
def run():
try:
stock.connect()
except Exception as error:
result['error'] = error
worker = threading.Thread(target=run, daemon=True)
worker.start()
worker.join(seconds)
if worker.is_alive():
raise TimeoutError('connect timeout')
if 'error' in result:
raise result['error']

def reconnect_loop():
retries = 0
while reconnect_needed.wait():
reconnect_needed.clear()
retries += 1
if retries > 5:
print('Reconnect failed 5 times, please check the network')
return
time.sleep(min(2 ** retries, 30)) # wait 2, 4, 8, 16, 30 seconds before retrying
try:
stock.disconnect() # reset the connection state first, otherwise connect() will not reconnect
connect_with_timeout()
subscribe_all()
retries = 0
print('Reconnected and resubscribed')
except Exception as error:
print(f'Reconnect failed: {error}')
reconnect_needed.set()

stock.on('disconnect', handle_disconnect)
threading.Thread(target=reconnect_loop, daemon=True).start()

stock.connect()
subscribe_all()