Reconnect
The following is a simple demonstration that automatically reconnects the trading socket when a disconnection event is detected using a callback:
- Python
- Node.js
- C#
from fubon_neo.sdk import FubonSDK
import threading
# === Add Your Login Information ===
USER_ID = "ID"
USER_PW = "Trade Password"
CERT_PATH = "Certificate File Location"
CERT_PW = "Certificate Password"
# --- If you want also to reconnect the marketdata WebSocket, you can implement it here ---
def handle_marketdata_ws_disconnect(code, msg):
print(f"[Marketdata WS] Reconnection, reason: {code}, {msg}")
# === Global process lock to prevent multiple triggerings ===
relogin_lock = threading.Lock()
# === Initiate a FubonNeo SDK instnace ===
sdk = FubonSDK()
accounts = None # To store account information after login successfully
# === Order and other callback functions(to be implemented) ===
def on_order(code, msg): pass
def on_order_changed(code, msg): pass
def on_filled(code, msg): pass
def re_login():
"""
When connection dropped, reconnect and log in, and reset all callback functions.
Use the process lock to prevent multiple triggerings.
"""
if not relogin_lock.acquire(blocking=False):
print("[Reconnect] In progress, ignore this call")
return
try:
global accounts, sdk
print("[Reconnect] Try to log out before reconnecting...")
try:
sdk.logout()
except Exception as e:
print("[Reconnect] Exception while logging out:", e)
try:
sdk = FubonSDK()
accounts = sdk.login(USER_ID, USER_PW, CERT_PATH, CERT_PW)
except Exception as e:
print("[Reconnect] Exception while logging in:", e)
return
if accounts.is_success:
print("[Reconnect] Login successfully, reset all callback functions")
# IMPORTANT: Please remeber to register all callback functions again!
sdk.set_on_event(on_event)
sdk.set_on_order(on_order)
sdk.set_on_order_changed(on_order_changed)
sdk.set_on_filled(on_filled)
# Implement the marketdata reconnection here if needed
handle_marketdata_ws_disconnect(-9000, "Auto-reconnect")
else:
print("[Reconnect] Reconnection failed")
finally:
relogin_lock.release()
def on_event(code, content):
"""
FubonNeo SDK's event callback
"""
print("[Event] Code:", code, "| Content:", content)
if code == "300":
print("[Event] Connection dropped(Code 300), start reconnecting ...")
re_login()
# === Login and register callback functions ===
accounts = sdk.login(USER_ID, USER_PW, CERT_PATH, CERT_PW)
if accounts.is_success:
print("[Main] Login successful, registering callbacks ...")
sdk.set_on_event(on_event)
sdk.set_on_order(on_order)
sdk.set_on_order_changed(on_order_changed)
sdk.set_on_filled(on_filled)
# Can set different account(if choices are available)
acc = accounts.data[0] if hasattr(accounts, "data") else None
else:
print("[Main] Login failed!")
# === Example: Simulate reconnecting event to test the program ===
on_event("300", "Test: WebSocket connection dropped")
on_event("300", "Test:Trigger the relogin again to test the process lock")
# --- End of The Example ---
const { FubonSDK } = require('fubon-neo');
// === Add Your Login Information ===
const USER_ID = "ID";
const USER_PW = "Trade Password";
const CERT_PATH = "Certificate File Location";
const CERT_PW = "Certificate Password";
// === Global process lock (flag) to prevent multiple triggerings ===
let reloginLock = false;
// === Initiate a FubonNeo SDK instnace===
let sdk = new FubonSDK();
let accounts = null; // To store account information after login successfully
// === Order and other callback functions(to be implemented) ===
function onOrder(code, msg) {}
function onOrderChanged(code, msg) {}
function onFilled(code, msg) {}
// --- If you want also to reconnect the marketdata WebSocket, you can implement it here ---
function handleMarketdataWsDisconnect(code, msg) {
console.log(`[Marketdata WS] Reconnection, reason: ${code}, ${msg}`);
}
function reLogin() {
// Use the flag to prevent multiple triggering
if (reloginLock) {
console.log("[Reconnect] In progress, ignore this call");
return;
}
reloginLock = true;
console.log("[Reconnect] Try to log out before reconnecting..");
try {
// Cancel callback funtion registration
sdk.setOnEvent(() => {});
sdk.setOnOrder(() => {});
sdk.setOnOrderChanged(() => {});
sdk.setOnFilled(() => {});
sdk.logout(); // It is ok for logout error, reconnecting anyway
} catch (e) {
console.log("[Reconnect] Exception while logging out:", e);
}
try {
// Re-initialize a SDK instnace
sdk = new FubonSDK();
accounts = sdk.login(USER_ID, USER_PW, CERT_PATH, CERT_PW);
} catch (e) {
console.log("[Reconnect] Exception while logging in:", e);
reloginLock = false;
return;
}
if (accounts && accounts.isSuccess) {
console.log("[Reconnect] Login successfully, reset all callback functions");
# IMPORTANT: Please remeber to register all callback functions again!
sdk.setOnEvent(onEvent);
sdk.setOnOrder(onOrder);
sdk.setOnOrderChanged(onOrderChanged);
sdk.setOnFilled(onFilled);
// Implement the marketdata reconnection here if needed
handleMarketdataWsDisconnect(-9000, "Auto-reconnect");
} else {
console.log("[Reconnect] Reconnection failed");
}
reloginLock = false;
}
function onEvent(code, content) {
// FubonNeo SDK's event callback
console.log("[Event] Code:", code, "| Content:", content);
if (code === "300") {
console.log("[Event] Connection dropped(Code 300), start reconnecting ...");
reLogin();
}
}
// === Login and register callback functions ===
accounts = sdk.login(USER_ID, USER_PW, CERT_PATH, CERT_PW);
if (accounts && accounts.isSuccess) {
console.log("[Main] Login successful, registering callbacks ...");
sdk.setOnEvent(onEvent);
sdk.setOnOrder(onOrder);
sdk.setOnOrderChanged(onOrderChanged);
sdk.setOnFilled(onFilled);
// Can set different account(if choices are available)
let acc = (accounts.data && accounts.data.length > 0) ? accounts.data[0] : null;
} else {
console.log("[Main] Login failed!");
}
// === Example: Simulate reconnecting event to test the program ===
Promise.all([
Promise.resolve().then(() => onEvent("300", "Test: WebSocket connection dropped")),
]);
// --- End of The Example ---
using System;
using System.Threading;
using FubonNeo.Sdk;
class Program
{
// === Add Your Login Information ===
static string USER_ID = "ID";
static string USER_PW = "Trade Password";
static string CERT_PATH = "Certificate File Location";
static string CERT_PW = "Certificate Password";
// === Global process lock to prevent multiple triggerings ===
static object reloginLock = new object();
static bool isReloginRunning = false;
// === Initiate a FubonSDK instnace ===
static FubonSDK sdk = new FubonSDK();
static dynamic accounts = null; // # To store account information after login successfully
// === Order and other callback functions(to be implemented)===
static void OnOrder(string code, OrderResult data) { }
static void OnOrderChanged(string code, OrderResult data) { }
static void OnFilled(string code, FilledData data) { }
// --- If you want also to reconnect the marketdata WebSocket, you can implement it here ---
static void HandleMarketdataWsDisconnect(int code, string msg)
{
Console.WriteLine($"[Marketdata WS] Reconnection, reason: {code}, {msg}");
}
static void ReLogin()
{
// Use the process lock and the flag to prevent multiple triggerings
lock (reloginLock)
{
if (isReloginRunning)
{
Console.WriteLine("[Reconnect] In progress, ignore this call");
return;
}
isReloginRunning = true;
}
try
{
Console.WriteLine("[Reconnect] Try to log out before reconnecting...");
try
{
sdk.Logout();
}
catch (Exception e)
{
Console.WriteLine("[Reconnect] Exception while logging out:" + e.Message);
}
try
{
sdk = new FubonSDK();
accounts = sdk.Login(USER_ID, USER_PW, CERT_PATH, CERT_PW);
}
catch (Exception e)
{
Console.WriteLine("[Reconnect] Exception while logging in:" + e.Message);
return;
}
if (accounts != null && accounts.isSuccess)
{
Console.WriteLine("[Reconnect] Login successfully, reset all callback functions");
// IMPORTANT: Please remeber to register all callback functions again!
sdk.OnEvent = OnEvent;
sdk.OnOrder = OnOrder;
sdk.OnOrderChanged = OnOrderChanged;
sdk.OnFilled = OnFilled;
// Implement the marketdata reconnection here if needed
HandleMarketdataWsDisconnect(-9000, "Auto-reconnect");
}
else
{
Console.WriteLine("[Reconnect] Reconnection failed");
}
}
finally
{
lock (reloginLock)
{
isReloginRunning = false;
}
}
}
static void OnEvent(string code, string content)
{
Console.WriteLine("[Event] Code: " + code + " | Content: " + content);
if (code == "300")
{
Console.WriteLine("[Event] Connection dropped(Code 300), start reconnecting ...");
ReLogin();
}
}
static void Main(string[] args)
{
// === Login and register callback functions ===
accounts = sdk.Login(USER_ID, USER_PW, CERT_PATH, CERT_PW);
if (accounts != null && accounts.isSuccess)
{
Console.WriteLine("[Main] Login successful, registering callbacks ...");
sdk.OnEvent = OnEvent;
sdk.OnOrder = OnOrder;
sdk.OnOrderChanged = OnOrderChanged;
sdk.OnFilled = OnFilled;
// Can set different account(if choice available)
var acc = (accounts.data != null && accounts.data.Count > 0) ? accounts.data[0] : null;
}
else
{
Console.WriteLine("[Main] Login failed!");
}
// === Example: Simulate reconnecting event to test the program ===
OnEvent("300", "Test: WebSocket connection dropped");
OnEvent("300", "Test:Trigger the relogin again to test the process lock");
// Pause the main program and wait for user's command
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}