SuperAPI AI Directory

neoapi-python

Coding & development

View repository

Updated 10-15 21:37

About this skill

NeoAPI Python

Overview

This skill teaches AI coding agents to use Fubon Neo Python SDK for Taiwan stockssecurities tradingandmarket dataaccess. Applicable to Python 3.12–3.13, SDK >= 2.x (avoid 3.14). Default SDK ~2.2.7 unless the user specifies otherwise.

TL;DR — three major workflows:

  1. Login → sdk.login(ID, PWD, cert, cert_pwd) get account list
  2. Place order → construct Order(...) → sdk.stock.place_order(acc, order)
  3. Market data → sdk.init_realtime() → sdk.marketdata.rest_client.stock.intraday.*

Shioaji migration routing

When the user asks to migrate or port existing Shioaji code, keep the tone practical and neutral: help them translate working code safely; do not frame the answer as a broker comparison. Load references/migration-shioaji.md first, then add the narrow reference below when needed.

Migration task Load / check
Login / CA / account selection references/migration-shioaji.md + official login docs
Stock order placement references/migration-shioaji.md + references/implementation-practices.md
Modify / cancel / status tracking references/migration-shioaji.md + references/response-shapes.md
Quantity or lot-size confusion references/migration-shioaji.md (Neo quantity is shares)
Test vs production behavior references/test-environment.md
WebSocket / callback migration references/migration-shioaji.md + references/examples-guidance.md

Common Mistakes

Incorrect Correct approach
pip install fubon-neo SDK is not on PyPI; it must be downloaded fromthe official pagedownload .whl install
In the test environment, use intraday.quote to determine the orderable price The test environment should use sdk.stock.query_symbol_quote(acc, symbol)
SDK >= 2.2.1 still uses FubonSDK() initialization Must use FubonSDK(30, 2) (or include url= parameter)
After placing an order, the deleted order cannot be found The deleted order is still in get_order_results with status=30
After logging in, directly use sdk.marketdata.rest_client Must first call sdk.init_realtime()
user_def string is too long 10 characters or fewer is recommended; longer strings will be truncated
Using SDK v2 on Python 3.14 SDK v2 only supports 3.12–3.13
Quantity is filled in as "lots" rather than "shares" FubonNeo quantities are always inshares(1 lot = 1000 shares)
WebSocket on_message directly get message["price"] The message is an envelope structure; trading data is in message["data"] inside, and you must first check message["event"] == "data"

Public Docs Access

Usage Cheat Sheet

Quickstart (Trading)

from fubon_neo.sdk import FubonSDK, Order, Mode
from fubon_neo.constant import BSAction, MarketType, PriceType, TimeInForce, OrderType

# Init & Login
sdk = FubonSDK()  # Use FubonSDK(30, 2) if on SDK 2.2.1+
accounts = sdk.login("ID", "PWD", "C:/path/to/cert.pfx", "CertPWD")
acc = accounts.data[0]  # Pick stock account

# Place Order (Buy 1000 shares of 2330 at Limit 580)
# Keyword form recommended (matches official docs); positional form also works.
order = Order(
    buy_sell=BSAction.Buy,
    symbol="2330",
    quantity=1000,
    market_type=MarketType.Common,
    price_type=PriceType.Limit,
    time_in_force=TimeInForce.ROD,
    order_type=OrderType.Stock,
    price="580"
)
res = sdk.stock.place_order(acc, order)
print(f"Order: {res.data.order_no}")

Critical Constants

Category Class Common Values
Action BSAction .Buy, .Sell
Price PriceType .Limit (limit order), .Market (market order), .Reference (reference price)
Time TimeInForce .ROD (valid on the day), .IOC (immediate or cancel), .FOK (fill or kill)
Market MarketType .Common (full lot), .IntradayOdd (intraday odd lot), .Odd (after-hours odd lot)
Order OrderType .Stock (cash stock), .MarginTrading (margin), .ShortSelling (short sale)

Validating Prices

Real-time quotes (intraday.quote) may differ from valid order prices (especially in Test Env).

  • For Orders: Always check sdk.stock.query_symbol_quote(acc, symbol).
    • Use limit_up_price / limit_down_price from this result for placing limit orders.
    • This source reflects the order system's view of validity.
  • For Display: Use sdk.marketdata.rest_client.stock.intraday.quote(symbol).

Rate Limits (Summary)

  • REST: 300 req/min (IP-based).
  • WebSocket: 200 subscriptions per connection.

SDK Version Compatibility

SDK Version Python Constructor Notes
>= 2.2.6 3.12–3.13 FubonSDK(30, 2) Order placement errors throw FugleAPIError
2.2.1–2.2.5 3.12–3.13 FubonSDK(30, 2) The error is in the response object
<= 2.2.0 3.12–3.13 FubonSDK() No positional arguments
1.3.1–1.x 3.8–3.12 FubonSDK() Minimum test environment requirement

The test environment always adds url="wss://neoapitest.fbs.com.tw/TASP/XCPXWS" parameter.

Workflow Decision Tree

需求是什麼?
├── 交易(Trading)
│   ├── 下單 / 改單 / 刪單
│   │   ├── 測試環境?→ FubonSDK(30, 2, url=test_url) + query_symbol_quote 取價格
│   │   └── 正式環境?→ FubonSDK(30, 2) + intraday.ticker 取漲跌停
│   ├── 查詢帳務 → sdk.stock.get_order_results / get_inventories
│   └── 當沖(Day Trade)→ 見下方「當沖」章節
├── 行情(Market Data)
│   ├── 即時快照 → HTTP: intraday.quote(成交)/ intraday.ticker(參考價/漲跌停)
│   ├── 歷史資料 → HTTP: historical
│   └── 即時串流 → WebSocket: sdk.init_realtime() + subscribe
└── 環境確認
    ├── SDK 版本 → 見上方「版本相容性」
    ├── 安裝方式 → 官方 .whl(非 PyPI)
    └── 文件查詢 → references/doc-index.md

Trading Workflow

  • Start from docs/trading/prepare and docs/trading/quickstart for setup.
  • Use Python library references under docs/trading/library/python/ for exact function names, parameters, and return types.
  • Typical flow: login (password or API key) → place/modify/cancel order → query order/account info → logout.
  • Always mention rate limits when relevant (docs/trading/trade-rate-limit).

Market Data Workflow

  • Decide on HTTP vs WebSocket:
    • HTTP API for snapshots, intraday, historical.
    • WebSocket API for real-time streams.
  • Use docs/market-data/http-api/getting-started and docs/market-data/websocket-api/getting-started.
  • Mention connection setup and rate limits when relevant.
  • To use sdk.marketdata.rest_client, call sdk.init_realtime() after login.
  • For limit-up/limit-down prices in market data, use intraday.ticker (not intraday.quote).
  • Trading hours reference (Taiwan cash equities): references/twse-trading-hours.md (Asia/Taipei)

Day Trading

Taiwan stock day trading is divided into:

  • Buy first, then sell(cash stock day trading - buy): first use BSAction.Buy to place an order, then on the same day use BSAction.Sell to sell. Use OrderType.Stock。
  • Sell first, then buy(cash stock day trading - sell/margin short day trading): first sell short on margin, then buy back on the same day. Use OrderType.ShortSelling。

Key determination

  • Use intraday.ticker returned by canDayTrade / canBuyDayTrade field to confirm whether the target can be day traded (a quick flag on the market data side).
  • If you want to more precisely determine whether "buy first, then sell" vs "sell first, then buy" can be done, it is recommended to check the trading side's status bitmask:
    • Sources are commonly found in:
      • sdk.stock.query_symbol_quote(acc, symbol) returned data.status
      • sdk.stock.daytrade_and_stock_info(acc, symbol) returned data.status(some wrappers call it disposition_status)
    • bitmask definitions (sum):
      • 1: short selling on a downtick is allowed
      • 2: securities lending short selling on a downtick is allowed
      • 4: buy-first daytrade allowed
      • 8: sell-first daytrade / daytrade short allowed
    • For determination, use bitwise operations, do not use >=:
def decode_daytrade_status(status: int) -> dict[str, bool]:
    return {
        "can_short_sell_below_flat": bool(status & 1),
        "can_borrow_sell_below_flat": bool(status & 2),
        "can_daytrade_buy_first": bool(status & 4),
        "can_daytrade_sell_first": bool(status & 8),
    }

# examples
# status=15 -> all True (1+2+4+8)
# status=3  -> only the first two True (1+2)
# status=8  -> sell-first daytrade only
  • Position close-out (offset): before market close, offset with a reverse order for an equal number of shares.

Conditional order day trading

SDK >= 2.2.4 supports conditional order day trading (search llms-full.txt for ConditionDayTrade or "day trading conditional order"), and can set stop-loss and take-profit for automatic buyback.

Reference implementation

Futures & Options

This skill currently focuses primarily on **Stock** trading and market data. The SDK supports futures/options accounts (account_type == "futopt"), but this skill does not yet cover the corresponding order/market data APIs. For futures conditional order descriptions, search llms-full.txt for "futures conditional order". Community contributions to futures/options workflows are welcome.

Examples

  • Use references/examples-guidance.md to map SDK calls to docs and avoid common modification pitfalls.

Testing / Sandbox

  • Official test bundle: https://www.fbs.com.tw/TradeAPI_SDK/sample_code/test_environment.zip

  • Use SDK v1.3.1+ and the test URL wss://neoapitest.fbs.com.tw/TASP/XCPXWS.

  • SDK v2.2.0 and earlier: FubonSDK(url=...)

  • SDK v2.2.1 and later: FubonSDK(30, 2, url=...) (30/2 are reference values).

  • Test credentials: ID from certificate; login password and cert password are 12345678.

  • See references/test-environment.md for operational notes (trading hours, shared account caveats).

  • Python SDK is downloaded from the official site (not PyPI); install the wheel locally.

  • Skill validation checklist: references/skill-tests.md.

  • Local integrated runner (maintainer-only; may be absent in some distributed skill copies): .test/test_runner.py

    • If present, it can run:
      • --suite smoke: basic login + market/trade sanity checks
      • --suite complex: multi-symbol marketdata + dual-order lifecycle + callback coverage
      • --suite all: full coverage (includes complex checks)
    • If it is missing, use the minimal smoke snippet below (login → logout; no orders).

Minimal smoke (test env, no orders):

from fubon_neo.sdk import FubonSDK
import os

URL = os.getenv("NEOAPI_TEST_URL", "wss://neoapitest.fbs.com.tw/TASP/XCPXWS")
# SDK v2.2.1+: use FubonSDK(30, 2, url=...)
sdk = FubonSDK(30, 2, url=URL)

accounts = sdk.login(
    os.getenv("NEOAPI_TEST_ID"),
    os.getenv("NEOAPI_TEST_PASSWORD"),
    os.getenv("NEOAPI_TEST_CERT_PATH"),
    os.getenv("NEOAPI_TEST_CERT_PASSWORD"),
)
print("login_ok=", bool(getattr(accounts, "is_success", True)))

sdk.logout()
  • For limit-down/limit-up in test env, prefer sdk.stock.query_symbol_quote (test environment data). intraday.quote uses market data (prod) and may differ.

SDK Install (Quick Note)

  • Python SDK is not on PyPI. Download the wheel from the official page and install locally.
  • SDK >= v2 works on Python 3.12–3.13 (avoid 3.14 for now).

Real-time trade report + Safe-net Readback

For live or latency-sensitive trading systems, treat filled callbacks as the primary fill source and get_order_results as a periodic reconciliation safe-net.

  • Register callbacks before login/re-login when possible:
    • sdk.set_on_order(on_order) for order acknowledgements (OrderResult)
    • sdk.set_on_order_changed(on_order_changed) for modify/cancel reports (OrderResult)
    • sdk.set_on_filled(on_filled) for execution fills (FilledData)
    • sdk.set_on_event(on_event) for connection/re-login events
  • Compute entry/exit average from execution data, not from submitted order price:
    • preferred: FilledData.filled_avg_price
    • otherwise aggregate filled_price * filled_qty across fills
    • reconciliation fallback: OrderResult.filled_money / filled_qty from sdk.stock.get_order_results(acc)
  • Never use submitted limit price (price, after_price, limit-up/down) as P/L entry price fallback. If fill price is missing, mark the position as unresolved and reconcile.
  • Run get_order_results periodically (for example every ~30 seconds) to detect missed callbacks and reconcile filled_qty, filled_money, and status.
  • Reconcile records by order_no + seq_no when available; include filled_no for idempotent fill dedupe.
  • Record a fill_source in receipts/state, such as active_filled_callback or order_results_readback, so operators can tell whether the low-latency path or the safe-net supplied the fill.

Implementation Patterns

For production-tested patterns, see references/implementation-practices.md. Key topics:

  • SDK Manager: Connection lifecycle, auto-reconnect, graceful termination
  • WebSocket: Multi-connection load balancing (200 symbols/connection limit)
  • Async Patterns: ThreadPoolExecutor for blocking calls, per-symbol locking
  • Error Handling: FugleAPIError compatibility for old/new SDK versions
  • Order Placement: Order creation, placement, and fill handling
  • Strategy Patterns: Tick-to-decision pipeline, stop loss, position sizing
  • Error & Status Codes: Order status codes, HTTP errors, common rejection reasons

References

  • Doc index: references/doc-index.md
  • Implementation practices: references/implementation-practices.md
  • Response shapes: references/response-shapes.md
  • Source docs (maintainers): docs/ and i18n/en/docusaurus-plugin-content-docs/current

When code or docs need updating, mirror changes in the English localization if the content is user-facing.