shioaji Documentation

repository·master·Indexed 19 days ago

https://github.com/sinotrade/shioaji

A cross-language, cross-platform trading API provided by Sinopac for accessing Taiwan financial markets, including stocks, futures, and options. It features native Python bindings, a Go client, and an HTTP-based REST API. The toolkit includes a CLI for server management and market data queries, support for real-time streaming via SSE, and capabilities for order placement, account balance tracking, and portfolio management.

Tokens
104.2K
Snippets
280
Records
351
Agent score
65%

What's inside shioaji

  1. Overview of Accounting API methods

    master

    Shioaji provides several methods to query account-related information including balances, margins, positions, profit/loss, settlements, and trading limits.

    Python MethodDescriptionHTTP Path
    account_balance()Stock account balancePOST /api/v1/portfolio/account_balance
    margin()Futures margin infoPOST /api/v1/portfolio/margin
    list_positions()Unrealized positionsPOST /api/v1/portfolio/position_unit
    list_position_detail()Position detailsPOST /api/v1/portfolio/position_detail
    list_profit_loss()Realized P&LPOST /api/v1/portfolio/profit_loss
    list_profit_loss_detail()P&L detailsPOST /api/v1/portfolio/profit_loss_detail
    list_profit_loss_summary()P&L summaryPOST /api/v1/portfolio/profitloss_sum
    list_settlements()Settlement (legacy format)POST /api/v1/portfolio/settlement
    settlements()Settlement list (new format)POST /api/v1/portfolio/settlements
    trading_limits()Trading limitsPOST /api/v1/portfolio/trading_limits
  2. Overview of the Shioaji CLI

    master

    The shioaji binary is a dual-purpose tool that functions as both a command-line client and a daemon server.

    • Command-line client: Used for querying market data, placing orders, and managing portfolios.
    • Daemon server: Started via shioaji server start, it hosts the HTTP API.

    All data-path commands (such as auth, data, order, etc.) communicate with the daemon via HTTP. On Unix systems, the CLI prefers using Unix Domain Sockets (UDS) for communication. If no daemon is currently running, the CLI will attempt to auto-start one using the ensure_daemon mechanism.

    shioaji [OPTIONS] <COMMAND>
  3. Overview of Reserve Orders (預收券款)

    master

    Reserve orders allow users to reserve shares or earmark funds for stocks under disposition, attention, or warning status. All reserve operations belong to the order domain.

    Service Hours: 8:00 - 14:30 on trading days.

    Key Operations:

    • Stock Reserve Summary: Query available stocks for reserve and current reserved amounts.
    • Stock Reserve Detail: Query details of already-reserved stocks.
    • Reserve Stock: Reserve a specific number of shares for a disposition stock.
    • Earmarking Detail: Query details of earmarked funds.
    • Reserve Earmarking: Reserve specific funds for a stock.
  4. Overview of the Shioaji HTTP API

    master

    The Shioaji HTTP API allows any language or platform to trade Taiwan markets via REST endpoints and real-time SSE streaming. It is started using the shioaji server start command.

    Key features include:

    • RESTful JSON endpoints: For all trading operations.
    • Server-Sent Events (SSE): For real-time market data and order events.
    • OpenAPI 3.0: Includes a Scalar documentation UI and an openapi.json schema.
    • Built-in Dashboard: For monitoring.
    • Custom App Hosting: Ability to upload and host your own web applications.
    • Standard features: CORS support, gzip compression, request logging, and panic recovery.

    Default Base URL: http://127.0.0.1:8080
    API Prefix: /api/v1/

  5. Manage Watchlists in Shioaji

    master

    Shioaji provides CRUD (Create, Read, Update, Delete) operations for managing saved watchlists. Watchlists are supplemental to the main trading workflow and are used to store collections of contracts (stocks, futures, options, etc.).

    Interface Options

    • Python API: Use the shioaji library methods for programmatic control. Methods return Watchlist objects or list[Watchlist] containing Python contract objects.
    • CLI: Use the shioaji watchlist <SUBCOMMAND> command.
    • HTTP API: Direct access to /api/v1/watchlist endpoints.

    Summary of Operations

    TaskPython MethodCLI CommandHTTP Method
    List allfetch_watchlists()watchlist listGET /api/v1/watchlist
    Get oneget_watchlist(group_id)watchlist show --id <ID>GET /api/v1/watchlist/{id}
    Createcreate_watchlist(name, contracts)watchlist create --name <NAME>POST /api/v1/watchlist
    Deletedelete_watchlist(group_id)watchlist delete --id <ID>DELETE /api/v1/watchlist/{id}
    Sync (Replace)sync_watchlist(group_id, contracts)watchlist sync --id <ID>PUT /api/v1/watchlist/{id}
    Add Contractswatchlist_add_contract(group_id, contracts)watchlist add --id <ID>POST /api/v1/watchlist/{id}/contracts
    Remove Contractswatchlist_delete_contract(group_id, contracts)watchlist remove --id <ID>DELETE /api/v1/watchlist/{id}/contracts
  6. Overview of Streaming Market Data mechanisms

    master

    Shioaji provides real-time market data through two primary mechanisms:

    1. Python callbacks: Direct function callbacks used with Shioaji (synchronous) and ShioajiAsync (asynchronous) instances.
    2. SSE (Server-Sent Events): HTTP streaming via a built-in server, which allows access from any programming language.

    Available Quote Types:

    • Tick: Trade-by-trade data.
    • BidAsk: Order book data (5 levels).
    • Quote: Aggregated quote data.
    • KBar: Real-time 1-minute bars (available for stocks only).
  7. Overview of Shioaji Trading API access layers

    master

    Shioaji is a cross-language, cross-platform trading API for Taiwan financial markets (TWSE/TPEX/TAIFEX). It provides three distinct access layers depending on your programming language and performance requirements:

    1. Python: Native PyO3 bindings (import shioaji) providing both synchronous and asynchronous support for maximum performance.
    2. CLI: A command-line tool (shioaji) used for server management, executing trades, and querying market data.
    3. HTTP API + SSE: A RESTful API and Server-Sent Events (SSE) streaming service running at localhost:8080. This layer allows any language (JS/TS, Go, C/C++, C#, Rust, Java/Kotlin) to interact with the markets via standard HTTP requests and real-time streams.
  8. Recommended Project Layout for Shioaji Go clients

    master

    When organizing a Go project that consumes the Shioaji HTTP API, the following structure is recommended to separate transport logic from trading strategies:

    my-trading-app/
    ├── cmd/app/main.go               # Entry point
    ├── pkg/shioaji/
    │   ├── client.go                  # API client implementation
    │   ├── types.go                   # Type definitions (structs)
    │   └── stream.go                  # SSE streaming logic
    ├── strategies/
    │   └── example.go                 # User trading logic/strategies
    └── go.mod
  9. Handling pre-market reservation orders

    master

    Pre-market reservation orders do not trigger order or deal callbacks immediately. They are released at 08:30 on each trading day, at which point callbacks are triggered.

    If you do not receive a callback before 08:30, do not assume failure. Instead, verify the order/trade state using list_trades() or the /api/v1/order/trades endpoint. For HTTP clients in production, ensure POST /api/v1/auth/subscribe_trade has been called for the specific account.

  10. How Contract V2 works (Mental Model)

    master

    Contract V2 separates lightweight identity records from heavy, type-specific detail records to optimize performance and memory usage.

    • Base Contract: A lightweight record identifying a product via security_type, region, exchange, code, and optional target_code. Use this for orders, quote subscriptions, snapshots, ticks, and K-bars.
    • Info: A detailed, typed record (e.g., StockInfo, FuturesInfo) containing descriptive fields like reference, multiplier, tick_rule, or limits. Fetch this only when your application needs specific rules or metadata.

    Key Behaviors:

    • Lazy Loading: Login does not download all product details. Data is downloaded and cached (memory/disk) only upon the first lookup of a specific dataset or shard.
    • Automatic Updates: When a contract update event occurs, Shioaji marks the affected cache as dirty. The next time you access that contract, it is refreshed lazily. You do not need to manually reload files or install callbacks in Python.
    • Lookup Strategy: Choose the narrowest lookup possible for your task (e.g., use get() for a specific code, or list() for a type).
    import shioaji as sj
    
    api = sj.Shioaji()
    api.login(api_key="YOUR_KEY", secret_key="YOUR_SECRET")
    
    # Use Base for operations
    base = api.contracts.get("2330")
    
    # Use Info for metadata/rules
    info = api.contracts.info(base)
    print(info.reference)
  11. Understand order_deal_event and event payloads

    master

    Shioaji uses order_deal_event to push active order and deal events (accepted, updated, cancelled, or filled) immediately after actions like place_order, update_order, or cancel_order.

    Key distinctions:

    • order_deal_event: Real-time active pushes. Use these for live trading logic.
    • order_deal_records: Historical/reconciliation queries. Use these for auditing or recovery.
    • Race Condition: Deal events (fills) may arrive before order events due to exchange message priority. Always match events using order.id or status.id against the deal's trade_id.
    • Success Check: For order operations, check if operation.op_code == "00". Any other value indicates failure, and the error details are in operation.op_msg.
    | Event state | Meaning | Python callback payload | HTTP SSE payload |
    |-------------|---------|-------------------------|-----------------|
    | `OrderState.StockOrder` / `SORDER` | Stock order accepted/updated/cancelled | dict-like event with `operation`, `order`, `status`, `contract` | `{"state":"StockOrder","data":{"StockOrder":{...}}}` |
    | `OrderState.StockDeal` / `SDEAL` | Stock deal / partial fill / fill | dict-like event with `trade_id`, `seqno`, `ordno`, `exchange_seq`, `broker_id`, `account_id`, `action`, `code`, `order_cond`, `order_lot`, `price`, `quantity`, `web_id`, `custom_field`, `ts` | `{"state":"StockDeal","data":{"StockDeal":{...}}}` |
    | `OrderState.FuturesOrder` / `FORDER` | Futures/options order accepted/updated/cancelled | dict-like event with `operation`, `order`, `status`, `contract` | `{"state":"FuturesOrder","data":{"FuturesOrder":{...}}}` |
    | `OrderState.FuturesDeal` / `FDEAL` | Futures/options deal / partial fill / fill | dict-like event with `trade_id`, `seqno`, `ordno`, `exchange_seq`, `broker_id`, `account_id`, `action`, `code`, `price`, `quantity`, `subaccount`, `security_type`, `delivery_month`, `full_code`, `strike_price`, `option_right`, `market_type`, `combo`, `ts` | `{"state":"FuturesDeal","data":{"FuturesDeal":{...}}}` |
  12. Guidelines for using Shioaji references and documentation

    master

    When implementing Shioaji, follow these rules to ensure technical accuracy:

    • Use Functional References: For specific endpoint payloads, request fields, or response schemas, always consult the matching functional reference.
    • Avoid Cross-Layer Inference: Do not assume that Python attribute names match HTTP/SSE field names. Other languages (JS, Go, Rust, etc.) must use the specific HTTP/SSE response shapes defined in the API documentation, not the Python object structures.
    • Handle Errors Correctly: If an HTTP response contains success=false, an error code, or an operation status/message, you must branch your logic based on that field. Note that empty lists or PendingSubmit statuses are not necessarily final failure or success signals; check the functional reference for the specific state machine logic.