This release is a pre-release and may not be stable for production use.
fugle-marketdata
Fugle market data REST and WebSocket client for Python, powered by a Rust core through PyO3.
Installation
pip install --pre fugle-marketdata # 3.x pre-release
Wheels are published for CPython 3.8+ (abi3) on Linux glibc (x86_64, aarch64), macOS (x86_64, arm64) and Windows x64.
Development Build
# Create virtual environment
python -m venv .venv
source .venv/bin/activate
# Install maturin
pip install maturin
# Build and install in development mode
cd py
maturin develop
Release Build From Source
maturin build --release
pip install target/wheels/fugle_marketdata-*.whl
Quick Start
REST API
from fugle_marketdata import RestClient, MarketDataError
# Create client with API key
client = RestClient(api_key="your-api-key")
# Get stock quote
quote = client.stock.intraday.quote("2330")
print(f"TSMC Price: {quote['closePrice']}")
print(f"Change: {quote['change']}")
print(f"Volume: {quote['total']['tradeVolume']}")
# Get stock ticker info
ticker = client.stock.intraday.ticker("2330")
print(f"Name: {ticker['name']}")
# Get intraday candles (5-minute)
candles = client.stock.intraday.candles("2330", timeframe="5")
for candle in candles['data'][:3]:
print(f" {candle['time']}: O={candle['open']} H={candle['high']} L={candle['low']} C={candle['close']}")
# Get recent trades
trades = client.stock.intraday.trades("2330")
for trade in trades['data'][:5]:
print(f" Price: {trade['price']}, Size: {trade['size']}")
# FutOpt (futures/options) data
futopt_quote = client.futopt.intraday.quote("TXFC4")
print(f"Futures Price: {futopt_quote['closePrice']}")
WebSocket Streaming
from fugle_marketdata import WebSocketClient
import time
# Create WebSocket client
ws = WebSocketClient(api_key="your-api-key")
# --- Callback Mode ---
def on_message(msg):
"""Handle incoming messages"""
if msg.get('event') == 'data':
channel = msg.get('channel')
symbol = msg.get('symbol')
data = msg.get('data', {})
print(f"[{channel}] {symbol}: {data}")
def on_connect():
print("Connected!")
def on_disconnect(code, reason):
print(f"Disconnected: {code} - {reason}")
def on_error(message, code):
print(f"Error [{code}]: {message}")
# Register callbacks
stock = ws.stock
stock.on("message", on_message)
stock.on("connect", on_connect)
stock.on("disconnect", on_disconnect)
stock.on("error", on_error)
# Connect and subscribe
stock.connect()
stock.subscribe("trades", "2330")
stock.subscribe("books", "2330")
# Keep running for 10 seconds
time.sleep(10)
# Disconnect
stock.disconnect()
# --- Iterator Mode ---
ws2 = WebSocketClient(api_key="your-api-key")
stock2 = ws2.stock
stock2.connect()
stock2.subscribe("trades", "2330")
# Iterate over messages
for msg in stock2.messages():
print(msg)
# Add break condition as needed
Authentication
Three authentication methods are supported:
from fugle_marketdata import RestClient
# 1. API Key (most common)
client = RestClient(api_key="your-api-key")
# 2. Bearer Token
client = RestClient(bearer_token="your-bearer-token")
# 3. SDK Token
client = RestClient(sdk_token="your-sdk-token")
Configuration
Reconnection Config
Auto-reconnect is on by default: after an unexpected drop the client
reconnects with exponential backoff, without an attempt limit (waits capped
at max_delay_ms), and subscribes again. Pass reconnect to tune it:
from fugle_marketdata import WebSocketClient, ReconnectConfig
# Create custom reconnect configuration
reconnect = ReconnectConfig(
max_attempts=10,
initial_delay_ms=2000,
max_delay_ms=120000
)
ws = WebSocketClient(api_key="your-key", reconnect=reconnect)
# Turn auto-reconnect off
ws = WebSocketClient(api_key="your-key", reconnect=ReconnectConfig.disabled())
ReconnectConfig Options:
enabled(bool): Whether auto-reconnect is enabled (default: True)max_attempts(int): Maximum reconnection attempts; 0 means unlimited (default: 0). With a limit, theerrorcallback reports code 3005 once the last attempt failsinitial_delay_ms(int): Initial delay for exponential backoff (default: 1000ms, min: 100ms)max_delay_ms(int): Maximum delay cap (default: 60000ms)
Health Check Config
Liveness detection is on by default: when no inbound frame (data, heartbeat or
pong) arrives within heartbeat_timeout_ms, the connection is declared dead
and auto-reconnect takes over. The server sends a heartbeat every 30 seconds.
from fugle_marketdata import WebSocketClient, HealthCheckConfig
# Longer timeout
health_check = HealthCheckConfig(heartbeat_timeout_ms=60000)
ws = WebSocketClient(api_key="your-key", health_check=health_check)
# Turn liveness detection off
ws = WebSocketClient(api_key="your-key", health_check=HealthCheckConfig(enabled=False))
# Confirm with a ping before disconnecting; know within 10 seconds
ws = WebSocketClient(api_key="your-key",
health_check=HealthCheckConfig(probe_enabled=True,
idle_probe_after_ms=5000,
probe_timeout_ms=5000))
# Round trip on demand, in milliseconds (default timeout 5000)
latency = ws.stock.measure_latency()
With probe_enabled, a silent connection is asked before it is declared dead:
after idle_probe_after_ms of silence one ping is sent, and only if nothing
arrives within probe_timeout_ms is the connection declared dead. The defaults
keep detection at 35 seconds and send no ping while the server's heartbeat is on
time, so turning on probe_enabled alone only removes false disconnects caused
by a late heartbeat.
HealthCheckConfig Options:
enabled(bool): Whether health check is enabled (default: True)heartbeat_timeout_ms(int): Maximum gap between inbound frames before the connection is declared dead (default: 35000ms, min: 5000ms). Does not apply whenprobe_enabledis True.probe_enabled(bool): Confirm with a ping before declaring the connection dead (default: False). Detection isidle_probe_after_ms + probe_timeout_ms.idle_probe_after_ms(int): Silence before the ping (default: 30000ms, the server's heartbeat period; min: 5000ms). Below 30000 a ping is sent in every gap between heartbeats while no data flows.probe_timeout_ms(int): Wait for any inbound frame after the ping (default: 5000ms, min: 1000ms)
Probing does not detect a half-open connection (the server still sends, our writes no longer arrive). See docs/configuration.md for the trade-offs and the server cost of short probe intervals.
Combined Configuration
from fugle_marketdata import WebSocketClient, ReconnectConfig, HealthCheckConfig
reconnect = ReconnectConfig(max_attempts=10, initial_delay_ms=2000)
health_check = HealthCheckConfig(heartbeat_timeout_ms=60000)
ws = WebSocketClient(
api_key="your-key",
reconnect=reconnect,
health_check=health_check
)
API Reference
RestClient
Stock Intraday Methods
client.stock.intraday.quote(symbol) # Real-time quote
client.stock.intraday.ticker(symbol) # Symbol information
client.stock.intraday.candles(symbol, timeframe="1") # OHLCV candles
client.stock.intraday.trades(symbol) # Trade history
client.stock.intraday.volumes(symbol) # Volume by price
FutOpt Intraday Methods
client.futopt.intraday.quote(symbol) # Real-time quote
client.futopt.intraday.ticker(symbol) # Contract information
client.futopt.intraday.candles(symbol, timeframe="1") # OHLCV candles
client.futopt.intraday.trades(symbol) # Trade history
client.futopt.intraday.volumes(symbol) # Volume by price
client.futopt.intraday.products(type) # Product listing ("F" or "O")
Query parameters
Every REST method takes the endpoint's query parameters as keyword arguments,
under the 3.x snake_case names, the API's own names as documented on
developer.fugle.tw (the spelling the 2.x SDK used), or the 2.x from_ alias
for the reserved word:
client.stock.intraday.trades("2330", limit=5, sort="asc", is_trial=True)
client.stock.intraday.trades("2330", limit=5, sort="asc", isTrial=True) # same call
client.stock.intraday.ticker("2330", odd_lot=True)
client.stock.intraday.ticker("2330", type="oddlot") # same call
client.stock.technical.sma("2330", from_date="2026-08-01", to_date="2026-09-10", period=5)
client.stock.technical.sma("2330", from_="2026-08-01", to="2026-09-10", period=5) # same call
A keyword the endpoint does not take raises TypeError naming the accepted
ones, and so does one parameter given under two spellings. Values are sent as
given and the server reports a bad value, except the two switches behind a
boolean keyword: type must be "oddlot" and session "afterhours" /
"regular", or ValueError.
Type checkers (mypy, pyright) only know the snake_case keywords: the stubs
list them and no **kwargs, so isTrial= or from_= is flagged even though
it works at runtime. Use the snake_case names in code you type-check; the
other spellings are a runtime compatibility layer for 2.x call sites.
WebSocketClient
Properties
ws.stock # Access StockWebSocketClient
ws.futopt # Access FutOptWebSocketClient
StockWebSocketClient / FutOptWebSocketClient Methods
client.connect() # Connect to server
client.disconnect() # Disconnect from server
client.is_connected() # Check connection status
client.is_closed() # Check if client is closed
client.subscribe(channel, symbol) # Subscribe to channel
client.unsubscribe(subscription_id) # Unsubscribe by server ID (or ids=[...])
client.unsubscribe(channel=channel, symbol=symbol) # Unsubscribe by subscribe() arguments
client.subscriptions() # List active subscriptions
client.on(event, callback) # Register event callback (not async def)
client.off(event) # Unregister callback
client.messages() # Get message iterator
Event Types
| Event | Callback Signature | Description |
|---|---|---|
message |
fn(msg: dict) |
Incoming data message |
connect |
fn() |
Connection established |
disconnect |
fn(code: int, reason: str) |
Connection closed |
error |
fn(err: WebSocketError) |
Error occurred (err.args == (message, code)) |
messages_dropped |
fn(dropped: int, total: int) |
Messages dropped because you fell behind (at most once per second, and before disconnect) |
Callback Exceptions
An exception raised in a callback does not stop the connection or later
callbacks. It is passed to the error callbacks as a WebSocketError with
code 3004, err.event (the event whose callback raised, e.g. "message"),
err.count and the original exception as err.__cause__:
def on_error(err):
if err.code == 3004:
print(f"{err.event} callback failed {err.count}x:", repr(err.__cause__))
The first failure is reported at once, later ones at most once per second,
each report counting the failures since the previous one; failures after the
last report are not reported on their own. Without an error callback, or
when it raises too, the failure goes to sys.unraisablehook (printed with its
traceback by default). KeyboardInterrupt, SystemExit and other
BaseExceptions that are not Exceptions are only printed that way.
Callbacks run on the SDK's thread and must be regular functions: on()
raises TypeError for an async def callback, and a callback that returns a
coroutine is reported as a failure. Use async for msg in stock.messages()
in asyncio code.
Message Queue
ws = WebSocketClient(
api_key="key",
message_overflow="drop_newest", # default; or "unbounded"
message_buffer=4096, # unread messages held (default 4096)
)
ws.stock.on("messages_dropped", lambda dropped, total: print(dropped, total))
ws.stock.messages_dropped_total() # this connection's drops; still readable after disconnect()
With "drop_newest", while message_buffer messages are unread (your
message callback or iterator is behind), new messages are dropped, counted
and reported through messages_dropped. "unbounded" never drops; memory
grows for as long as you lag.
Channels
| Channel | Description |
|---|---|
trades |
Real-time trade executions |
candles |
Candlestick updates |
books |
Order book (5 levels) |
aggregates |
Aggregated market data |
indices |
Index values (stock only) |
MessageIterator
# Get iterator from connected client
messages = stock.messages()
# Iterate (blocking): yields messages only, stops once the connection is gone
for msg in messages:
print(msg)
# Async iteration
async for msg in stock.messages():
print(msg)
# Manual iteration
msg = next(messages) # Blocking until a message arrives
msg = messages.try_recv() # Non-blocking, returns None if no message
msg = messages.recv_timeout(5.0) # Timeout in seconds
Iteration never yields None and does not end while no data arrives; it
raises StopIteration / StopAsyncIteration once the connection is gone. A
blocked for loop still reacts to Ctrl+C. messages(timeout_ms=...) is
deprecated and ignored. For periodic work while no data arrives, use
message callbacks or async for alongside other tasks.
Messages go to message callbacks when any are registered as they arrive,
otherwise to the iterator. The iterator holds at most 4096 unread messages;
while it does, lifecycle callbacks (disconnect, reconnect, …) that follow
those messages wait until you read or call disconnect(). Every wait releases
the GIL.
Error Handling
All API errors raise MarketDataError (or a subclass):
from fugle_marketdata import RestClient, MarketDataError
client = RestClient(api_key="invalid-key")
try:
quote = client.stock.intraday.quote("2330")
except MarketDataError as e:
print(f"Error [{e.code}] {e.source_kind}: {e.message}")
if e.status is not None:
print(e.status, e.body, e.headers.get("retry-after"))
Every exception carries the same fields as the other languages:
| Attribute | Type | |
|---|---|---|
code |
int |
Error code (table below); also args[1] |
source_kind |
str |
"network", "protocol", "auth", "rate_limit" or "client" |
message |
str |
Human-readable message; also args[0] and str(e) |
status |
int | None |
HTTP status |
body |
str | None |
Raw HTTP response body (REST) |
request_id |
str | None |
x-request-id response header |
headers |
dict[str, str] |
HTTP response headers, lowercase names (REST; else empty) |
status_code and response_text remain as aliases of status and body
for code written against the 2.4.1 FugleAPIError. The WebSocket error
callback receives a WebSocketError with these fields, whose args stay
(message, code). See the
error reference for all languages.
Error Codes
| Code | Error Type | Description |
|---|---|---|
| 1001 | InvalidSymbol | Invalid or unsupported symbol |
| 1002 | DeserializationError | JSON parsing failed |
| 1003 | RuntimeError | Internal runtime error |
| 1004 | ConfigError | Configuration error |
| 1005 | InvalidParameter | Invalid or missing parameter (including an unknown WebSocket channel) |
| 2001 | ConnectionError | Network connection failed |
| 2002 | AuthError | Authentication failed |
| 2003 | ApiError | API returned error response |
| 2010 | ClientClosed, ConnectionAborted | Client has been closed, or connect() / connect_async() was given up because disconnect() was called before the connection was established (raised as WebSocketError, message Connection aborted: …) |
| 3001 | TimeoutError | Operation timed out |
| 3002 | WebSocketError | WebSocket connect, read or write failed |
| 3003 | HeartbeatTimeout | No inbound WebSocket frame within the heartbeat window |
| 3004 | CallbackFailed | A WebSocket callback raised an exception (error callback only) |
| 3005 | ReconnectFailed | Reconnection failed after the last attempt (error callback only) |
| 9999 | Other | Unexpected error |
| -1 | ThreadPanic | A WebSocket worker thread panicked (error callback only) |
Examples
Full REST Example
from fugle_marketdata import RestClient, MarketDataError
import os
def main():
api_key = os.environ.get("FUGLE_API_KEY")
if not api_key:
print("Set FUGLE_API_KEY environment variable")
return
client = RestClient(api_key=api_key)
try:
# Stock data
print("=== Stock Market Data ===")
quote = client.stock.intraday.quote("2330")
print(f"TSMC Quote: {quote['closePrice']}")
ticker = client.stock.intraday.ticker("2330")
print(f"Ticker: {ticker['name']}")
candles = client.stock.intraday.candles("2330", timeframe="5")
print(f"Candles: {len(candles['data'])} entries")
# FutOpt data
print("\n=== FutOpt Market Data ===")
products = client.futopt.intraday.products("F")
print(f"Futures products: {len(products['data'])}")
except MarketDataError as e:
print(f"Error [{e.args[1]}]: {e.args[0]}")
if __name__ == "__main__":
main()
Full WebSocket Example
from fugle_marketdata import WebSocketClient, MarketDataError
import os
import time
def main():
api_key = os.environ.get("FUGLE_API_KEY")
if not api_key:
print("Set FUGLE_API_KEY environment variable")
return
ws = WebSocketClient(api_key=api_key)
stock = ws.stock
message_count = 0
def on_message(msg):
nonlocal message_count
message_count += 1
if msg.get('event') == 'data':
print(f"[{message_count}] {msg.get('channel')}: {msg.get('symbol')}")
def on_connect():
print("Connected!")
def on_error(message, code):
print(f"Error [{code}]: {message}")
stock.on("message", on_message)
stock.on("connect", on_connect)
stock.on("error", on_error)
try:
stock.connect()
stock.subscribe("trades", "2330")
stock.subscribe("books", "2330")
print("Listening for 10 seconds...")
time.sleep(10)
print(f"\nReceived {message_count} messages")
print(f"Subscriptions: {stock.subscriptions()}")
except MarketDataError as e:
print(f"Error [{e.args[1]}]: {e.args[0]}")
finally:
if stock.is_connected():
stock.disconnect()
print("Done")
if __name__ == "__main__":
main()
Requirements
- Python 3.8+
- Rust toolchain (for building from source)
- maturin (for development builds)
License
MIT
Metadata
Release files for fugle-marketdata 3.0.0rc5
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Built distributions (wheels)
Total release size: 16.0 MB
Release files / fugle_marketdata-3.0.0rc5-cp38-abi3-win_amd64.whl
| Download URL | fugle_marketdata-3.0.0rc5-cp38-abi3-win_amd64.whl |
|---|---|
| Size | 3.0 MB |
| Tags | CPython 3.8 Windows x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
689fa13f34a280f87a297c9830d7e3226ecfd716eb09d1c12da2042b7fc74e1a
|
|
BLAKE2b-256 checksum How to use checksums |
6f530efd886982ea53ce8a3cb5007fcf1f9ecc1c70e4c1bed027a5f393fa622a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 18, 2026.
Transparency logRelease files / fugle_marketdata-3.0.0rc5-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
| Download URL | fugle_marketdata-3.0.0rc5-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl |
|---|---|
| Size | 3.3 MB |
| Tags | CPython 3.8 Linux glibc 2.17+ x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
f8015c18fba13918eab9207964f9cab7e482d29de429a957ef9cbec017564a92
|
|
BLAKE2b-256 checksum How to use checksums |
d8197ef05f94b9564be6c20dddfba77b985b74e773f1b6fcfa15606bf6a645bc
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 18, 2026.
Transparency logRelease files / fugle_marketdata-3.0.0rc5-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
| Download URL | fugle_marketdata-3.0.0rc5-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl |
|---|---|
| Size | 3.5 MB |
| Tags | CPython 3.8 Linux glibc 2.17+ ARM64 abi3 |
|
SHA-256 checksum How to use checksums |
277b21abff652a581831aa0451f134eba0920ec1b38a040cd7e07b8b59e4c85e
|
|
BLAKE2b-256 checksum How to use checksums |
47fc708d908ba1df0cf754c5c2682881f082bb2d7889e6ea0ba7bcd5c1b0127c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 18, 2026.
Transparency logRelease files / fugle_marketdata-3.0.0rc5-cp38-abi3-macosx_11_0_arm64.whl
| Download URL | fugle_marketdata-3.0.0rc5-cp38-abi3-macosx_11_0_arm64.whl |
|---|---|
| Size | 3.1 MB |
| Tags | CPython 3.8 abi3 macOS 11.0+ ARM64 |
|
SHA-256 checksum How to use checksums |
7799d7a130395c9ab66f3d3d48465a1e80edb46eef038d0f27da791944d1a9e4
|
|
BLAKE2b-256 checksum How to use checksums |
5d786245f694d11199e4a766f55838fe8b6082d527521a28322a3a9331bd1111
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 18, 2026.
Transparency logRelease files / fugle_marketdata-3.0.0rc5-cp38-abi3-macosx_10_12_x86_64.whl
| Download URL | fugle_marketdata-3.0.0rc5-cp38-abi3-macosx_10_12_x86_64.whl |
|---|---|
| Size | 3.1 MB |
| Tags | CPython 3.8 abi3 macOS 10.12+ x86-64 |
|
SHA-256 checksum How to use checksums |
9ed79c23b9f58792284f150a05fd346efad75baacd89c606b2e53319f63e5543
|
|
BLAKE2b-256 checksum How to use checksums |
d6e73d40d58c7692884524eecac732bac5b2cd60d0e9235e0802e295878f52d6
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 18, 2026.
Transparency logSecurity for fugle-marketdata 3.0.0rc5
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
All 5 files in this release have been uploaded with provenance metadata.
Attestation for fugle_marketdata-3.0.0rc5-cp38-abi3-win_amd64.whl
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 18, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.