### Environment variables and server start Source: https://sinotrade.github.io/upgrade_to_1_5 Provides an example of setting environment variables for API credentials and mode, and starting the Shioaji server. ```bash # .env (in the working directory) SJ_API_KEY=YOUR_API_KEY SJ_SEC_KEY=YOUR_SECRET_KEY SJ_PRODUCTION=false # simulation; set to true for production shioaji server start ``` -------------------------------- ### Getting Started Prompt for New Shioaji Users Source: https://sinotrade.github.io/ai_assistant A comprehensive prompt to guide new users through the Shioaji setup and testing process with AI assistance. ```text I'm new to Shioaji and want to start trading. Please guide me through the complete setup process step by step: 1. How to open a Sinopac account 2. How to sign the API terms of service 3. How to apply for API Key and Secret Key 4. How to complete the simulation mode testing (login test, stock order test, futures order test) 5. How to verify my test passed (signed=True) 6. How to apply for and activate the CA certificate 7. How to switch to production mode Please check my progress at each step and help me troubleshoot any issues. ``` -------------------------------- ### Login using Environment Variables and Server Start Source: https://sinotrade.github.io/tutor/login This example shows how to configure login credentials using a .env file and start the Shioaji server, which automatically handles login. ```shell # .env (in the working directory) should contain: SJ_API_KEY=YOUR_API_KEY # edit it SJ_SEC_KEY=YOUR_SECRET_KEY # edit it SJ_PRODUCTION=true # whether to enter production mode # Start server (auto-reads .env and logs in) shioaji server start ``` -------------------------------- ### Stop Order Setup Source: https://sinotrade.github.io/tutor/advanced/quote_binding Example of setting up a stop order with a contract and order details. ```python contract = api.Contracts.Futures.TXF['TXF202301'] order = api.Order( action='Buy', price=14800, quantity=1, price_type='LMT', order_type='ROD', octype=sj.constant.FuturesOCType.Auto, account=api.futopt_account ) # Stop Order Excecutor soe = StopOrderExcecutor(api) soe.add_stop_order(contract=contract, stop_price=14805, order=order) ``` -------------------------------- ### CLI Example Source: https://sinotrade.github.io/tutor/accounting/account_balance Example of querying account balance with the CLI. ```bash shioaji portfolio balance ``` -------------------------------- ### Install shioaji Command using uv tool Source: https://sinotrade.github.io/env_setup/other Installs the shioaji command-line tool using the uv tool, which is the recommended method. ```bash uv tool install shioaji ``` -------------------------------- ### Bid/Ask Data Output Example Source: https://sinotrade.github.io/upgrade Example output format for bid/ask data. ```text Exchange: Exchange.TSE, BidAsk: BidAsk(code='2330', datetime=datetime.datetime(2021, 7, 2, 13, 17, 29, 726428), bid_price=[Decimal('589'), Decimal('588'), Decimal('587'), Decimal('586'), Decimal('585')], bid_volume=[223, 761, 1003, 809, 1274], diff_bid_vol=[0, 0, 0, 0, 0], ask_price=[Decimal('590'), Decimal('591'), Decimal('592'), Decimal('593'), Decimal('594')], ask_volume=[304, 232, 183, 242, 131], diff_ask_vol=[1, 0, 0, 0, 0], suspend=0, simtrade=0, intraday_odd=0) ``` ```text Topic: QUT/idcdmzpcr01/TSE/2330, Quote: {'AskPrice': [590.0, 591.0, 592.0, 593.0, 594.0], 'AskVolume': [303, 232, 183, 242, 131], 'BidPrice': [589.0, 588.0, 587.0, 586.0, 585.0], 'BidVolume': [224, 762, 1003, 809, 1274], 'Date': '2021/07/02', 'Time': '13:17:26.391840'} ``` -------------------------------- ### Python Login and CA Activation Source: https://sinotrade.github.io/quickstart Example of how to instantiate Shioaji, log in with API keys, and activate CA for production orders using Python. ```python import shioaji as sj # Create Shioaji instance. api = sj.Shioaji() # Login accounts = api.login(api_key="YOUR_API_KEY", secret_key="YOUR_SECRET_KEY") # Activate CA (required before placing orders in production) api.activate_ca( ca_path="your/ca/path/Sinopac.pfx", ca_passwd="YOUR_CA_PASSWORD", person_id="Person of this Ca", ) ``` -------------------------------- ### HTTP Example Source: https://sinotrade.github.io/tutor/accounting/trading_limits Example of how to make a curl request to get trading limits. ```bash curl -X POST http://localhost:8080/api/v1/portfolio/trading_limits \ -H 'Content-Type: application/json' \ -d '{"account_type": "S", "broker_id": "YOUR_BROKER_ID", "account_id": "YOUR_ACCOUNT_ID"}' ``` -------------------------------- ### Install uv on Windows Source: https://sinotrade.github.io/env_setup/python Command to install the 'uv' Python environment manager on Windows systems using PowerShell. ```powershell powershell -c "irm https://astral.sh/uv/install.ps1 | iex" ``` -------------------------------- ### Python Place Order Source: https://sinotrade.github.io/quickstart Example of placing a limit buy order for a stock using Shioaji in Python. ```python contract = api.Contracts.Stocks["2890"] order = sj.StockOrder( action=sj.Action.Buy, price=28, quantity=1, price_type=sj.StockPriceType.LMT, order_type=sj.OrderType.ROD, order_lot=sj.StockOrderLot.Common, order_cond=sj.StockOrderCond.Cash, ) trade = api.place_order(contract, order) ``` -------------------------------- ### Install uv on Linux and MacOS Source: https://sinotrade.github.io/env_setup/python Command to install the 'uv' Python environment manager on Linux and MacOS systems. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Install shioaji command Source: https://sinotrade.github.io/llms-full.txt Installs the shioaji command-line tool for starting the HTTP server. ```bash uv tool install shioaji ``` ```bash curl -fsSL https://raw.githubusercontent.com/sinotrade/shioaji/main/install.sh | sh ``` ```powershell irm https://raw.githubusercontent.com/sinotrade/shioaji/main/install.ps1 | iex ``` -------------------------------- ### Start Jupyter Lab Source: https://sinotrade.github.io/env_setup/python Command to launch Jupyter Lab, with the project environment integrated, using 'uv'. ```bash uv run --with jupyter jupyter lab ``` -------------------------------- ### Example .env file configuration Source: https://sinotrade.github.io/env_setup/other Configuration for the .env file required to run the shioaji server, including API keys, CA path, and production mode settings. ```dotenv # Required SJ_API_KEY=YOUR_API_KEY SJ_SEC_KEY=YOUR_SECRET_KEY # CA activation (required for placing orders in production) SJ_CA_PATH=your/ca/path/Sinopac.pfx SJ_CA_PASSWD=YOUR_CA_PASSWORD # Mode (set to true to enable production; unset or false means simulation) SJ_PRODUCTION=false ``` -------------------------------- ### Tick Data Output Example Source: https://sinotrade.github.io/upgrade Example output format for tick data. ```text Exchange: Exchange.TSE, Tick: Tick(code='2330', datetime=datetime.datetime(2021, 7, 2, 13, 16, 35, 92970), open=Decimal('590'), avg_price=Decimal('589.05'), close=Decimal('590'), high=Decimal('593'), low=Decimal('587'), amount=Decimal('590000'), total_amount=Decimal('8540101000'), volume=1, total_volume=14498, tick_type=1, chg_type=4, price_chg=Decimal('-3'), pct_chg=Decimal('-0.505902'), trade_bid_volume=6638, ask_side_total_vol=7860, bid_side_total_cnt=2694, ask_side_total_cnt=2705, closing_oddlot_shares=0, fixed_trade_vol=0, suspend=0, simtrade=0, intraday_odd=0) ``` ```text Topic: MKT/*/TSE/2330, Quote: {'AmountSum': [4739351000.0], 'Close': [596.0], 'Date': '2021/03/30', 'TickType': [2], 'Time': '10:01:33.349431', 'VolSum': [7932], 'Volume': [1]} ``` -------------------------------- ### Example: Place Order (Python) Source: https://sinotrade.github.io/tutor/order/FutureOption Python code example for constructing a futures order object. ```python # contract contract = api.Contracts.Futures.TMF.TMFR1 # order order = sj.FuturesOrder( action=sj.Action.Buy, price=36216, quantity=2, price_type=sj.FuturesPriceType.LMT, order_type=sj.OrderType.ROD, octype=sj.FuturesOCType.Auto, account=api.futopt_account, ) ``` -------------------------------- ### Install shioaji Command on Windows (PowerShell) Source: https://sinotrade.github.io/env_setup/other Installs the shioaji command-line tool on Windows using PowerShell. ```powershell irm https://raw.githubusercontent.com/sinotrade/shioaji/main/install.ps1 | iex ``` -------------------------------- ### CLI Example with Specific Account Source: https://sinotrade.github.io/tutor/accounting/account_balance Example of querying account balance with a specific account using the CLI. ```bash shioaji portfolio balance --account YOUR_BROKER_ID-YOUR_ACCOUNT_ID ``` -------------------------------- ### Install shioaji Command on Linux / MacOS Source: https://sinotrade.github.io/env_setup/other Installs the shioaji command-line tool on Linux or MacOS using a curl script. ```bash curl -fsSL https://raw.githubusercontent.com/sinotrade/shioaji/main/install.sh | sh ``` -------------------------------- ### CLI Tool Installation and Usage Source: https://sinotrade.github.io/ Instructions for installing and using the Shioaji CLI tool. ```bash uv tool install shioaji shioaji --help ``` -------------------------------- ### Python Example Source: https://sinotrade.github.io/tutor/order/FutureOption Example of cancelling an order using the Python API. ```Python api.cancel_order(trade) api.update_status(api.futopt_account) trade ``` -------------------------------- ### Python API Example Source: https://sinotrade.github.io/tutor/accounting/account_balance Example of querying account balance with the Python API. ```python api.account_balance() ``` -------------------------------- ### CLI Example: Fetching Kbars Source: https://sinotrade.github.io/tutor/market_data/historical Example command to fetch Kbar data using the CLI. ```bash shioaji data kbars --code 2330 --start 2026-05-17 --end 2026-05-18 ``` -------------------------------- ### Example Event Output Source: https://sinotrade.github.io/tutor/callback/event_cb An example of the output when a subscription or unsubscription operation is successful. ```text Event code: 16 | Event: Subscribe or Unsubscribe ok ``` -------------------------------- ### Order Event Example Source: https://sinotrade.github.io/tutor/order/order_deal_event/stocks An example of the order callback structure received from the exchange. ```python { 'operation': { 'op_type': 'New', 'op_code': '00', 'op_msg': '' }, 'order': { 'id': '348d1c6a', 'seqno': '351522', 'ordno': 'Y1S5N', 'account': { 'account_type': 'S', 'person_id': '', 'broker_id': 'YOUR_BROKER_ID', 'account_id': 'YOUR_ACCOUNT_ID', 'signed': True, 'username': '' }, 'action': 'Buy', 'price': 27.0, 'quantity': 1, 'order_type': 'ROD', 'price_type': 'LMT', 'order_cond': 'Cash', 'order_lot': 'Common', 'custom_field': '' }, 'status': { 'id': '348d1c6a', 'exchange_ts': 1779331286.678, 'modified_price': 0.0, 'cancel_quantity': 0, 'order_quantity': 1, 'web_id': '137' }, 'contract': { 'exchange': 'TSE', 'code': '2890', 'security_type': 'STK', 'symbol': '', 'name': '', 'currency': 'TWD' } } ``` -------------------------------- ### Deal Event Example Source: https://sinotrade.github.io/tutor/order/order_deal_event/stocks An example of the deal callback structure received upon successful matching. ```python { 'trade_id': '9c6ae2eb', 'seqno': '269866', 'ordno': 'IN497', 'exchange_seq': '669915', 'broker_id': 'YOUR_BROKER_ID', 'account_id': 'YOUR_ACCOUNT_ID', 'action': 'Buy', 'code': '2890', 'order_cond': 'Cash', 'order_lot': 'IntradayOdd', 'price': 267.5, 'quantity': 3, 'web_id': '137', 'custom_field': 'test', 'ts': 1673577256.354 } ``` -------------------------------- ### HTTP API Example Source: https://sinotrade.github.io/tutor/accounting/account_balance Example of querying account balance with the HTTP API. ```http curl -X POST http://localhost:8080/api/v1/portfolio/account_balance \ -H 'Content-Type: application/json' \ -d '{}' ``` -------------------------------- ### Example: Update Price (Python) Source: https://sinotrade.github.io/tutor/order/Stock Python code example demonstrating how to update an order's price using the `update_order` function and then checking the status. ```python api.update_order(trade=trade, price=27.2) api.update_status(api.stock_account) trade ``` -------------------------------- ### CLI Login and CA Activation using .env Source: https://sinotrade.github.io/quickstart Demonstrates how to use a .env file for Shioaji credentials and start the server for automatic login and CA activation via CLI. ```bash # .env (placed in the working directory) should contain: # SJ_API_KEY=YOUR_API_KEY # SJ_SEC_KEY=YOUR_SECRET_KEY # SJ_CA_PATH=your/ca/path/Sinopac.pfx # SJ_CA_PASSWD=YOUR_CA_PASSWORD # Start server (automatically reads .env, performs login and CA activation) shioaji server start # Check status shioaji server check ``` -------------------------------- ### Python API Example (Stock) Source: https://sinotrade.github.io/tutor/accounting/position Example of using `list_position_detail` to get stock position details. ```python api.list_position_detail(account=api.stock_account, detail_id=0) ``` -------------------------------- ### CLI Login and CA Activation with verification Source: https://sinotrade.github.io/quickstart Shows how to start the Shioaji server using .env credentials and verify login status using curl. ```bash # .env (placed in the working directory) should contain: # SJ_API_KEY=YOUR_API_KEY # SJ_SEC_KEY=YOUR_SECRET_KEY # SJ_CA_PATH=your/ca/path/Sinopac.pfx # SJ_CA_PASSWD=YOUR_CA_PASSWORD # Start server shioaji server start # Check accounts (verify login) curl http://localhost:8080/api/v1/auth/accounts ``` -------------------------------- ### Order Response Example Source: https://sinotrade.github.io/tutor/order/FutureOption An example of a JSON response for an order, showing various fields like status code, order quantity, and deals. ```json { "status_code": "0000", "web_id": "Z", "order_ts": 1779187550.0, "msg": "", "modified_ts": 1779187550.0, "modified_price": 36216.0, "order_quantity": 2, "deal_quantity": 0, "cancel_quantity": 0, "deals": [] } ] } ``` -------------------------------- ### Get Reserve Stock Summary - HTTP Example Source: https://sinotrade.github.io/tutor/order/Reserve cURL command to get the reserve stock summary. ```shell curl -X POST http://localhost:8080/api/v1/order/stock_reserve_summary \ -H 'Content-Type: application/json' \ -d '{ "account": { "broker_id": "YOUR_BROKER_ID", "account_id": "YOUR_ACCOUNT_ID" } }' ``` -------------------------------- ### Execute 'version' Command Source: https://sinotrade.github.io/tutor/prepare/example_testing_flow Demonstrates how to execute the newly added 'version' command to view the Shioaji version. ```bash uv run version ``` -------------------------------- ### Get Reserve Stock Summary - Python Example Source: https://sinotrade.github.io/tutor/order/Reserve Python code to get the reserve stock summary. ```python resp = api.stock_reserve_summary(account=api.stock_account) resp ``` -------------------------------- ### Execute 'stock_testing' Command Source: https://sinotrade.github.io/tutor/prepare/example_testing_flow Demonstrates how to run the 'stock_testing' command to initiate the stock ordering test. ```bash uv run stock_testing ``` -------------------------------- ### Python API Example with Specific Account Source: https://sinotrade.github.io/tutor/accounting/account_balance Example of querying account balance with a specific account using the Python API. ```python api.account_balance(account=api.stock_account) ``` -------------------------------- ### Python API Example (Futures and Options) Source: https://sinotrade.github.io/tutor/accounting/position Example of using `list_position_detail` to get futures and options position details. ```python api.list_position_detail(account=api.futopt_account, detail_id=0) ``` -------------------------------- ### Clone the Project Repository Source: https://sinotrade.github.io/tutor/prepare/example_testing_flow Clones the sj-trading-demo project from GitHub to set up the environment. ```bash git clone https://github.com/Sinotrade/sj-trading-demo.git cd sj-trading-demo ``` -------------------------------- ### Python code for 'hello' entry point Source: https://sinotrade.github.io/env_setup/python Python code for the 'hello' entry point, which includes functions to initialize the Shioaji API client. ```python import shioaji as sj def hello(): get_shioaji_client() def get_shioaji_client() -> sj.Shioaji: api = sj.Shioaji() print("Shioaji API created") return api ``` -------------------------------- ### HTTP API Example with Specific Account Source: https://sinotrade.github.io/tutor/accounting/account_balance Example of querying account balance with a specific account using the HTTP API. ```http curl -X POST http://localhost:8080/api/v1/portfolio/account_balance \ -H 'Content-Type: application/json' \ -d '{"account_type": "S", "broker_id": "YOUR_BROKER_ID", "account_id": "YOUR_ACCOUNT_ID"}' ``` -------------------------------- ### CLI Subscribe Example Source: https://sinotrade.github.io/tutor/market_data/streaming/futures Example of subscribing to real-time tick data for a futures contract using the command-line interface. ```bash shioaji data stream --code TXFR1 --security-type FUT --quote-type tick # Press Ctrl+C to stop; the CLI will unsubscribe automatically ``` -------------------------------- ### Get Earmarking Detail - cURL Example Source: https://sinotrade.github.io/tutor/order/Reserve cURL command to retrieve earmarking details. ```bash curl -X POST http://localhost:8080/api/v1/order/earmarking_detail \ -H 'Content-Type: application/json' \ -d '{ "account": { "broker_id": "YOUR_BROKER_ID", "account_id": "YOUR_ACCOUNT_ID" } }' ``` -------------------------------- ### Execute 'futures_testing' Command Source: https://sinotrade.github.io/tutor/prepare/example_testing_flow Demonstrates how to run the 'futures_testing' command to initiate the futures ordering test. ```bash uv run futures_testing ``` -------------------------------- ### Get Earmarking Detail - Python Example Source: https://sinotrade.github.io/tutor/order/Reserve Python code to retrieve earmarking details. ```python resp = api.earmarking_detail(account=api.stock_account) resp ``` -------------------------------- ### Execute 'hello' command Source: https://sinotrade.github.io/env_setup/python Command to run the 'hello' script defined in the project's pyproject.toml using 'uv'. ```bash uv run hello ``` -------------------------------- ### List Accounts (HTTP) Source: https://sinotrade.github.io/tutor/login Example of listing accounts using an HTTP GET request. ```shell curl http://localhost:8080/api/v1/auth/accounts ``` -------------------------------- ### CLI Place Order Source: https://sinotrade.github.io/quickstart Command-line interface for placing a limit buy order for a stock. ```bash shioaji order place --code 2890 --action buy --price 28 --quantity 1 \ --price-type lmt --order-type rod --order-lot common --order-cond cash ``` -------------------------------- ### Example: Update Price (Python) Source: https://sinotrade.github.io/tutor/order/FutureOption Python code demonstrating how to update an order's price using `api.update_order` and then fetching the updated trade information. ```python api.update_order(trade=trade, price=36220) api.update_status(api.futopt_account) trade ``` -------------------------------- ### Get Futures Order Status (Python) Source: https://sinotrade.github.io/tutor/order/UpdateStatus Example of retrieving the status of futures orders using the sinotrade Python API. ```python api.update_status(api.futopt_account) api.list_trades() ``` -------------------------------- ### Place Stock Order with CLI Source: https://sinotrade.github.io/tutor/order/Stock Example of placing a buy order for a stock using the Shioaji CLI. ```bash shioaji order place \ --code 2890 \ --action buy \ --price 27.1 \ --quantity 2 \ --price-type lmt \ --order-type rod \ --order-lot common \ --order-cond cash \ --account YOUR_BROKER_ID-YOUR_ACCOUNT_ID ``` -------------------------------- ### Python Data Subscription Source: https://sinotrade.github.io/quickstart Example of subscribing to stock data (tick and bid/ask quotes) for a specific contract using Shioaji in Python. ```python api.subscribe(api.Contracts.Stocks["2330"], quote_type="tick") api.subscribe(api.Contracts.Stocks["2330"], quote_type="bid_ask") ``` -------------------------------- ### Create Project Environment with uv Source: https://sinotrade.github.io/env_setup/python Commands to initialize a new Python project named 'sj-trading' using 'uv', setting it up for package management, application development, and Git version control, and then navigating into the project directory. ```bash uv init sj-trading --package --app --vcs git cd sj-trading ``` -------------------------------- ### Add Stock Testing File Source: https://sinotrade.github.io/tutor/prepare/example_testing_flow Adds the `testing_flow.py` file to `src/sj_trading` with content for stock testing. ```python import shioaji as sj from shioaji.constant import Action, StockPriceType, OrderType import os def testing_stock_ordering(): # Login to the testing environment api = sj.Shioaji(simulation=True) accounts = api.login( api_key=os.environ["API_KEY"], secret_key=os.environ["SECRET_KEY"], ) # Show all available accounts print(f"Available accounts: {accounts}") api.activate_ca( ca_path=os.environ["CA_CERT_PATH"], ca_passwd=os.environ["CA_PASSWORD"], ) # Prepare the Contract for Ordering # Use 2890 Fubon Financial as an example contract = api.Contracts.Stocks["2890"] print(f"Contract: {contract}") # Create an Order for Ordering order = sj.order.StockOrder( action=Action.Buy, # Buy price=contract.reference, # Buy at the reference price quantity=1, # Order quantity price_type=StockPriceType.LMT, # Limit price order order_type=OrderType.ROD, # Effective for the day account=api.stock_account, # Use the default account ) print(f"Order: {order}") # Send the order trade = api.place_order(contract=contract, order=order) print(f"Trade: {trade}") # Update the status api.update_status() print(f"Status: {trade.status}") ``` -------------------------------- ### Add project environment to Jupyter kernel Source: https://sinotrade.github.io/env_setup/python Command to install the current project's Python environment as a Jupyter kernel named 'sj-trading'. ```bash uv run ipython kernel install --user --name=sj-trading ``` -------------------------------- ### Standalone Installer - Linux / macOS Source: https://sinotrade.github.io/ Commands to install the Shioaji standalone installer on Linux or macOS for stable or prerelease versions. ```bash # Stable curl -fsSL https://raw.githubusercontent.com/sinotrade/shioaji/main/install.sh | sh # Prerelease curl -fsSL https://raw.githubusercontent.com/sinotrade/shioaji/main/install.sh | CHANNEL=prerelease sh ``` -------------------------------- ### Add Shioaji Version Information Source: https://sinotrade.github.io/tutor/prepare/example_testing_flow Adds a function to `src/sj_trading/__init__.py` to display the Shioaji version. ```python def show_version() -> str: print(f"Shioaji Version: {sj.__version__}") return sj.__version__ ``` -------------------------------- ### Standalone Installer - Windows (PowerShell) Source: https://sinotrade.github.io/ Commands to install the Shioaji standalone installer on Windows using PowerShell for stable or prerelease versions. ```powershell # Stable irm https://raw.githubusercontent.com/sinotrade/shioaji/main/install.ps1 | iex # Prerelease $env:CHANNEL="prerelease"; irm https://raw.githubusercontent.com/sinotrade/shioaji/main/install.ps1 | iex ``` -------------------------------- ### List Stock Orders with CLI Source: https://sinotrade.github.io/tutor/order/Stock Example of listing stock orders using the Shioaji CLI. ```bash shioaji order list ``` -------------------------------- ### Python Example Source: https://sinotrade.github.io/tutor/accounting/trading_limits Example of how to call the trading_limits function in Python. ```python api.trading_limits(account=api.stock_account) ``` -------------------------------- ### cURL Example Source: https://sinotrade.github.io/tutor/order/FutureOption Example of cancelling an order using a cURL request. ```Shell curl -X POST http://localhost:8080/api/v1/order/cancel_order \ -H 'Content-Type: application/json' \ -d '{ "trade_id": "YOUR_TRADE_ID" }' ``` -------------------------------- ### Bid/Ask Data - Traditional Way Source: https://sinotrade.github.io/upgrade Example of handling incoming bid/ask data using a traditional callback function registration. ```python from shioaji import BidAskSTKv1, Exchange def quote_callback(exchange: Exchange, bidask:BidAskSTKv1): print(f"Exchange: {exchange}, BidAsk: {bidask}") api.quote.set_on_bidask_stk_v1_callback(quote_callback) ``` ```python def quote_callback(topic: str, quote: dict): print(f"Topic: {topic}, Quote: {quote}") api.quote.set_quote_callback(quote_callback) ``` -------------------------------- ### Add Shioaji API to Project Source: https://sinotrade.github.io/env_setup/python Command to add the 'shioaji' Python package as a dependency to the current project using 'uv'. ```bash uv add shioaji ``` -------------------------------- ### Place Buy Order (Python) Source: https://sinotrade.github.io/tutor/order/FutureOption Example of creating and placing a buy order for futures or options with specific parameters. ```Python order = api.Order( action=sj.constant.Action.Buy, price=14400, quantity=2, price_type=sj.constant.FuturesPriceType.LMT, order_type=sj.constant.OrderType.ROD, octype=sj.constant.FuturesOCType.Auto, account=api.futopt_account ) ``` -------------------------------- ### Shioaji initialization (version < 1.0) Source: https://sinotrade.github.io/upgrade The `backend` argument was present in versions prior to 1.0. ```python sj.Shioaji( backend: str = 'http', simulation: bool = False, proxies: Dict[str, str] = {}, currency: str = 'NTD', ) ``` -------------------------------- ### Buy Order Example (Python) Source: https://sinotrade.github.io/tutor/order/Stock Python code to construct a buy order with specified parameters like price, quantity, and order types. ```Python order = api.Order( price=12, quantity=1, action=sj.constant.Action.Buy, price_type=sj.constant.StockPriceType.LMT, order_type=sj.constant.OrderType.ROD, order_lot=sj.constant.StockOrderLot.Common, custom_field="test", account=api.stock_account ) ``` -------------------------------- ### Python Example Usage Source: https://sinotrade.github.io/tutor/accounting/profit_loss Example of calling the list_profit_loss function in Python. ```python api.list_profit_loss(api.stock_account, '2026-05-01', '2026-05-21') ``` -------------------------------- ### List Accounts (Shioaji Auth CLI) Source: https://sinotrade.github.io/tutor/login Example of listing accounts using the `shioaji auth accounts` command. ```shell shioaji auth accounts ``` -------------------------------- ### Add 'stock_testing' Command to Project Source: https://sinotrade.github.io/tutor/prepare/example_testing_flow Configures `pyproject.toml` to add a 'stock_testing' command that executes the stock ordering test. ```toml [project.scripts] stock_testing = "sj_trading.testing_flow:testing_stock_ordering" ``` -------------------------------- ### HTTP Example: Basic Usage Source: https://sinotrade.github.io/tutor/accounting/settlements Example of a basic HTTP POST request for settlements. ```http curl -X POST http://localhost:8080/api/v1/portfolio/settlements \ -H 'Content-Type: application/json' \ -d '{}' ``` -------------------------------- ### Python Example: With Specific Account Source: https://sinotrade.github.io/tutor/accounting/settlements Example of calling the settlements API with a specific account. ```python api.settlements(account=api.stock_account) ``` -------------------------------- ### Python Example: Convert to DataFrame Source: https://sinotrade.github.io/tutor/accounting/settlements Example of converting settlements data to a polars DataFrame. ```python import polars as pl settlements = api.settlements() df = pl.DataFrame(s.dict() for s in settlements) df ``` -------------------------------- ### Python API for Placing an Order Source: https://sinotrade.github.io/tutor/prepare/terms Example of placing an order using the Shioaji Python API. ```python trade = api.place_order(contract, order) trade ``` -------------------------------- ### Add 'version' Command to Project Source: https://sinotrade.github.io/tutor/prepare/example_testing_flow Configures the `pyproject.toml` file to include a 'version' command that calls the `show_version` function. ```toml [project.scripts] version = "sj_trading:show_version" ``` -------------------------------- ### Python Package Installation Source: https://sinotrade.github.io/ Instructions for installing the Shioaji Python package using uv or pip. ```bash # uv (recommended) uv add shioaji # pip pip install shioaji ``` -------------------------------- ### Example: Update Price (HTTP) Source: https://sinotrade.github.io/tutor/order/Stock HTTP request example for updating an order's price. ```http curl -X POST http://localhost:8080/api/v1/order/update_price \ -H 'Content-Type: application/json' \ -d '{ "trade_id": "YOUR_TRADE_ID", "price": 27.2 }' ``` -------------------------------- ### CLI Command Example Source: https://sinotrade.github.io/tutor/market_data/snapshot Fetches market data snapshots using the Shioaji command-line interface. ```bash shioaji data snapshots --codes 2330,2317 ``` -------------------------------- ### cURL Request Example Source: https://sinotrade.github.io/tutor/accounting/profit_loss Example of making a cURL request to the profit_loss endpoint. ```bash curl -X POST http://localhost:8080/api/v1/portfolio/profit_loss \ -H 'Content-Type: application/json' \ -d '{"account_type": "S", "begin_date": "2026-05-01", "end_date": "2026-05-21", "broker_id": "YOUR_BROKER_ID", "account_id": "YOUR_ACCOUNT_ID"}' ``` -------------------------------- ### Add Futures Testing Content Source: https://sinotrade.github.io/tutor/prepare/example_testing_flow Adds content to `src/sj_trading/testing_flow.py` for testing futures ordering. ```python from shioaji.constant import ( FuturesPriceType, FuturesOCType, ) def testing_futures_ordering(): # Login to the testing environment api = sj.Shioaji(simulation=True) accounts = api.login( api_key=os.environ["API_KEY"], secret_key=os.environ["SECRET_KEY"], ) # Show all available accounts print(f"Available accounts: {accounts}") api.activate_ca( ca_path=os.environ["CA_CERT_PATH"], ca_passwd=os.environ["CA_PASSWORD"], ) # Get the contract for ordering # Use TXFR1 as an example contract = api.Contracts.Futures["TXFR1"] print(f"Contract: {contract}") # Create an Order for Ordering order = sj.order.FuturesOrder( action=Action.Buy, # Buy price=contract.reference, # Buy at the reference price quantity=1, # Order quantity price_type=FuturesPriceType.LMT, # Limit price order order_type=OrderType.ROD, # Effective for the day octype=FuturesOCType.Auto, # Auto select new close account=api.futopt_account, # Use the default account ) print(f"Order: {order}") # Send the order trade = api.place_order(contract=contract, order=order) print(f"Trade: {trade}") # Update the status api.update_status() print(f"Status: {trade.status}") ``` -------------------------------- ### Shioaji initialization (version >= 1.0) Source: https://sinotrade.github.io/upgrade The `backend` argument has been removed in version 1.0. ```python import shioaji as sj sj.Shioaji? ``` -------------------------------- ### Convert to DataFrame (polars example) Source: https://sinotrade.github.io/tutor/accounting/position Example of converting stock positions to a polars DataFrame. ```python import polars as pl positions = api.list_positions(account=api.stock_account) df = pl.DataFrame(p.dict() for p in positions) df ``` -------------------------------- ### Python Example: Basic Usage Source: https://sinotrade.github.io/tutor/accounting/settlements Example of calling the settlements API without specific parameters. ```python api.settlements() ``` -------------------------------- ### Query All Contracts Source: https://sinotrade.github.io/tutor/contract Example of how to query all available contracts using the Python SDK. ```python api.Contracts ``` -------------------------------- ### Example Combo Order (Python) Source: https://sinotrade.github.io/tutor/order/Combo Example of creating a combo contract and order in Python. ```python # Contract (short straddle: same expiry, same strike, sell call + sell put) call = api.Contracts.Options.TXO.get("TXO20260527000C") put = api.Contracts.Options.TXO.get("TXO20260527000P") combo_contract = sj.ComboContract( legs=[ sj.ComboBase.from_contract(call, action=sj.Action.Sell), sj.ComboBase.from_contract(put, action=sj.Action.Sell), ] ) # Order order = sj.ComboOrder( action=sj.Action.Sell, price=1, quantity=1, price_type=sj.FuturesPriceType.LMT, order_type=sj.OrderType.IOC, octype=sj.FuturesOCType.New, account=api.futopt_account, ) ``` -------------------------------- ### Deal Callback (pre-v1.0) Source: https://sinotrade.github.io/upgrade Example of an OrderState.TFTDeal callback structure. ```json OrderState.TFTDeal { 'trade_id': '12ab3456', 'exchange_seq': '123456', 'broker_id': 'your_broker_id', 'account_id': 'your_account_id', 'action': , 'code': '2890', 'order_cond': , 'order_lot': , 'price': 12, 'quantity': 10, 'web_id': '137', 'custom_field': 'test', 'ts': 1583828972 } ``` -------------------------------- ### Attention Stocks - HTTP Request Example Source: https://sinotrade.github.io/tutor/market_data/disposition_attention Example HTTP request for attention stocks. ```http curl http://localhost:8080/api/v1/data/regulatory_notice ```