### Installation and Setup Source: https://context7.com/sinotrade/shioaji/llms.txt Instructions on how to install Shioaji and set up the API for trading, including login and CA certificate activation. ```APIDOC ## Installation and Setup Install Shioaji via pip or uv, then initialize the API, log in with API keys, and activate the CA certificate before placing orders. ```python # Install # pip install shioaji # uv add shioaji (recommended) # uv add shioaji --extra speed (C++ speed optimizations) # docker run -it sinotrade/shioaji:latest import os import shioaji as sj from dotenv import load_dotenv load_dotenv() # Load from .env file # Production mode api = sj.Shioaji() # Simulation mode (no real money) # api = sj.Shioaji(simulation=True) accounts = api.login( api_key=os.environ["API_KEY"], secret_key=os.environ["SECRET_KEY"], ) # Activate CA certificate (required for placing orders) api.activate_ca( ca_path=os.environ["CA_CERT_PATH"], # path to Sinopac.pfx ca_passwd=os.environ["CA_PASSWORD"], ) print(f"Logged in. Accounts: {accounts}") print(f"Stock account: {api.stock_account}") print(f"Futures account: {api.futopt_account}") # Logout when done # api.logout() ``` ``` -------------------------------- ### Basic Order Placement Example Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/SKILL.md A simple example demonstrating how to place an order using the Shioaji API. ```python ``` -------------------------------- ### Monitor Multiple Stocks Example Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/WATCHLIST.md Example demonstrating how to create a watchlist for technology stocks and retrieve snapshots for them. ```APIDOC ## Monitor Multiple Stocks ### Description Example demonstrating how to create a watchlist for technology stocks and retrieve snapshots for them. ### Code Example ```python # Create a tech watchlist tech_watchlist = api.create_watchlist( name="Tech Stocks", contracts=[ api.Contracts.Stocks["2330"], # TSMC api.Contracts.Stocks["2454"], # MediaTek api.Contracts.Stocks["2317"], # Hon Hai api.Contracts.Stocks["2308"], # Delta ] ) # Get snapshots for all contracts snapshots = api.snapshots([ api.Contracts.Stocks[c.code] for c in tech_watchlist.contracts if c.security_type == "STK" ]) for snap in snapshots: print(f"{snap.code}: {snap.close} ({snap.change_rate}%)") ``` ``` -------------------------------- ### Install Shioaji using uv Source: https://github.com/sinotrade/shioaji/blob/master/README.md Install Shioaji using the uv package manager. Use the `--extra speed` flag for a potentially faster installation. ```bash uv add shioaji ``` ```bash uv add shioaji --extra speed ``` -------------------------------- ### Install and Initialize Shioaji API Source: https://context7.com/sinotrade/shioaji/llms.txt Install Shioaji using pip or uv. Initialize the API in production or simulation mode, log in with API keys, and activate the CA certificate for order placement. Logout when done. ```python # Install # pip install shioaji # uv add shioaji (recommended) # uv add shioaji --extra speed (C++ speed optimizations) # docker run -it sinotrade/shioaji:latest import os import shioaji as sj from dotenv import load_dotenv load_dotenv() # Load from .env file # Production mode api = sj.Shioaji() # Simulation mode (no real money) # api = sj.Shioaji(simulation=True) accounts = api.login( api_key=os.environ["API_KEY"], secret_key=os.environ["SECRET_KEY"], ) # Activate CA certificate (required for placing orders) api.activate_ca( ca_path=os.environ["CA_CERT_PATH"], # path to Sinopac.pfx ca_passwd=os.environ["CA_PASSWORD"], ) print(f"Logged in. Accounts: {accounts}") print(f"Stock account: {api.stock_account}") print(f"Futures account: {api.futopt_account}") # Logout when done # api.logout() ``` -------------------------------- ### Install Shioaji Python API Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/SKILL.md Install the Shioaji library using pip or uv. For optimized performance, use the '--extra speed' flag with uv. ```bash pip install shioaji ``` ```bash uv add shioaji ``` ```bash uv add shioaji --extra speed ``` ```bash docker run -it sinotrade/shioaji:latest ``` -------------------------------- ### Install python-dotenv Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/PREPARE.md Install the 'python-dotenv' library using uv to enable loading environment variables from a .env file. ```bash uv add python-dotenv ``` -------------------------------- ### Start Jupyter Lab Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/PREPARE.md Launch Jupyter Lab using 'uv run --with jupyter' to start a new session with the configured environment. ```bash # Start Jupyter Lab 啟動 Jupyter Lab uv run --with jupyter jupyter lab ``` -------------------------------- ### Install Shioaji using pip Source: https://github.com/sinotrade/shioaji/blob/master/README.md Install or update the Shioaji library using pip. Use `pip install -U shioaji` for the latest version. ```bash pip install shioaji ``` ```bash pip install -U shioaji ``` -------------------------------- ### Run Project Script Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/PREPARE.md Execute the 'hello' script using 'uv run' to verify the Shioaji installation and API instantiation. ```bash uv run hello ``` -------------------------------- ### Place Stock Order Source: https://context7.com/sinotrade/shioaji/llms.txt Place various types of stock orders (limit, market, odd-lot, margin, day-trade) by creating an `Order` object and associating it with a contract. This example shows the initial setup for placing an order. ```python import shioaji as sj contract = api.Contracts.Stocks["2330"] ``` -------------------------------- ### Subscribe to Watchlist Quotes Example Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/WATCHLIST.md Example showing how to retrieve a watchlist by its ID and subscribe to real-time quotes for its contracts. ```APIDOC ## Subscribe to Watchlist Quotes ### Description Example showing how to retrieve a watchlist by its ID and subscribe to real-time quotes for its contracts. ### Code Example ```python watchlist = api.get_watchlist("watchlist_id") for contract in watchlist.contracts: # Get full contract object if contract.security_type.value == "STK": full_contract = api.Contracts.Stocks[contract.code] elif contract.security_type.value == "FUT": full_contract = api.Contracts.Futures[contract.code] api.quote.subscribe(full_contract) ``` ``` -------------------------------- ### Verify Shioaji Installation Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/PREPARE.md Create a Python function to instantiate the Shioaji API and print its version. This verifies that Shioaji has been installed correctly. ```python import shioaji as sj def hello(): api = sj.Shioaji() print(f"Shioaji Version: {sj.__version__}") print("Shioaji API created successfully!") return api ``` -------------------------------- ### Fetch Contract Snapshots Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/CONTRACTS.md Retrieves real-time snapshots for a given list of contracts. This example shows how to get a snapshot for a single stock contract. ```python # Single contract 單一合約 snapshot = api.snapshots([api.Contracts.Stocks["2330"]]) ``` -------------------------------- ### Combo Strategy Examples Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/ORDERS.md Illustrates creating ComboContract objects for common option strategies like Straddle and Strangle. ```python # Straddle 跨式 (Buy Call + Buy Put same strike) straddle = ComboContract( legs=[ ComboBase( action=sj.constant.Action.Buy, contract=api.Contracts.Options["TXO202401C18000"], ), ComboBase( action=sj.constant.Action.Buy, contract=api.Contracts.Options["TXO202401P18000"], ), ] ) # Strangle 勒式 (Buy OTM Call + Buy OTM Put) strangle = ComboContract( legs=[ ComboBase( action=sj.constant.Action.Buy, contract=api.Contracts.Options["TXO202401C18500"], ), ComboBase( action=sj.constant.Action.Buy, contract=api.Contracts.Options["TXO202401P17500"], ), ] ) ``` -------------------------------- ### Install Shioaji AI Coding Agent Plugins Source: https://github.com/sinotrade/shioaji/blob/master/README.md Install AI coding agent plugins for Shioaji using Claude Code or universal installers like npx. These plugins provide AI-assisted guidance for using the Shioaji API. ```bash claude plugin marketplace add Sinotrade/Shioaji claude plugin install shioaji ``` ```bash npx skills add Sinotrade/Shioaji # skills.sh - 18+ agents npx skillkit install Sinotrade/Shioaji # skillkit - 32+ agents npx openskills install Sinotrade/Shioaji # openskills - universal ``` -------------------------------- ### Implement Rate Limiting for Subscriptions Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/STREAMING.md This example shows how to adhere to rate limits (50 requests per 5 seconds) when subscribing to multiple contracts by introducing a delay. ```python # Limit: 50 requests / 5 seconds # 限制:50 次 / 5 秒 import time for i, contract in enumerate(contracts): api.quote.subscribe(contract, quote_type=sj.constant.QuoteType.Tick) if (i + 1) % 50 == 0: time.sleep(5) ``` -------------------------------- ### Install uv Package Manager Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/PREPARE.md Install the uv package manager using a shell script for Linux/macOS or PowerShell for Windows. uv is recommended for managing Python environments. ```bash # Linux / MacOS curl -LsSf https://astral.sh/uv/install.sh | sh ``` ```powershell # Windows (PowerShell) powershell -c "irm https://astral.sh/uv/install.ps1 | iex" ``` -------------------------------- ### Place Basic Options Order Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/ORDERS.md Example of placing a buy call option order with specified parameters. Ensure the contract and account are correctly initialized. ```python # Buy call option 買進買權 contract = api.Contracts.Options["TXO202401C18000"] order = api.Order( price=100, quantity=1, action=sj.constant.Action.Buy, price_type=sj.constant.FuturesPriceType.LMT, order_type=sj.constant.OrderType.ROD, octype=sj.constant.FuturesOCType.Auto, account=api.futopt_account, ) trade = api.place_order(contract, order) ``` -------------------------------- ### Place Options Limit Order Source: https://context7.com/sinotrade/shioaji/llms.txt This example shows how to place a limit order for options contracts. Similar to futures, use `FuturesPriceType.LMT` and specify the `octype`. ```python call_contract = api.Contracts.Options["TXO202401C18000"] call_order = api.Order( price=100, quantity=1, action=sj.constant.Action.Buy, price_type=sj.constant.FuturesPriceType.LMT, order_type=sj.constant.OrderType.ROD, octype=sj.constant.FuturesOCType.Auto, account=api.futopt_account, ) trade = api.place_order(call_contract, call_order) # Trade status values: # PendingSubmit, PreSubmitted, Submitted, Failed, Cancelled, Filled, PartFilled print(trade.status.status) print(trade.status.deal_quantity) print(trade.order.id) ``` -------------------------------- ### Stop Order Usage Example (Shioaji API) Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/ADVANCED.md Demonstrates how to initialize the StopOrderExecutor, define contracts and orders, add stop orders, and set up tick callbacks for real-time monitoring. Ensure you are logged in and have subscribed to relevant quotes. ```python import shioaji as sj api = sj.Shioaji() api.login(api_key="YOUR_KEY", secret_key="YOUR_SECRET") # Create stop order executor 建立觸價執行器 soe = StopOrderExecutor(api) # Define contract and order 定義合約和訂單 contract = api.Contracts.Futures["TXFC0"] order = api.Order( action=sj.constant.Action.Buy, price=18000, quantity=1, price_type=sj.constant.FuturesPriceType.LMT, order_type=sj.constant.OrderType.ROD, account=api.futopt_account, ) # Add stop order (trigger when price >= 18005) # 新增觸價委託(價格 >= 18005 時觸發) soe.add_stop_order(contract=contract, stop_price=18005, order=order) # Bind callback with context 綁定回調與 context api.set_context(soe) @api.on_tick_fop_v1(bind=True) def on_tick(self, exchange: Exchange, tick: TickFOPv1): self.on_tick(exchange, tick) # Subscribe to quotes 訂閱行情 api.quote.subscribe(contract, quote_type=sj.constant.QuoteType.Tick) ``` -------------------------------- ### Place Stock Order Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/SKILL.md Demonstrates how to get a contract, create an order object with specific parameters, and place the order using the Shioaji API. ```python contract = api.Contracts.Stocks["2330"] # TSMC 台積電 order = api.Order( price=580, quantity=1, action=sj.constant.Action.Buy, price_type=sj.constant.StockPriceType.LMT, order_type=sj.constant.OrderType.ROD, account=api.stock_account, ) trade = api.place_order(contract, order) ``` -------------------------------- ### Contract Snapshots Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/CONTRACTS.md Shows how to get real-time market data snapshots for specific contracts. ```APIDOC ## Contract Snapshots Get real-time snapshot for contracts: ```python # Single contract snapshot = api.snapshots([api.Contracts.Stocks["2330"]]) ``` ``` -------------------------------- ### Place Sell Options Order Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/ORDERS.md Example of placing a sell put option order. Similar to buying options, ensure correct contract and account details are provided. ```python # Sell put option 賣出賣權 contract = api.Contracts.Options["TXO202401P17000"] order = api.Order( price=50, quantity=1, action=sj.constant.Action.Sell, price_type=sj.constant.FuturesPriceType.LMT, order_type=sj.constant.OrderType.ROD, octype=sj.constant.FuturesOCType.Auto, account=api.futopt_account, ) trade = api.place_order(contract, order) ``` -------------------------------- ### Day Trading Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/ORDERS.md Provides examples for day trading orders, covering both the initial buy (first leg) and the subsequent sell to close the position. ```APIDOC ### Day Trading 現股當沖 ```python # Day trade buy (first leg) 當沖買進(第一筆) order = api.Order( price=580, quantity=1, action=sj.constant.Action.Buy, price_type=sj.constant.StockPriceType.LMT, order_type=sj.constant.OrderType.ROD, daytrade_short=True, # Enable day trade 啟用當沖 account=api.stock_account, ) # Day trade sell (close position) 當沖賣出(平倉) order = api.Order( price=590, quantity=1, action=sj.constant.Action.Sell, price_type=sj.constant.StockPriceType.LMT, order_type=sj.constant.OrderType.ROD, daytrade_short=True, account=api.stock_account, ) ``` ``` -------------------------------- ### Error Handling for Placing Orders Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/SKILL.md Provides an example of how to use a try-except block to catch and handle potential exceptions when placing an order with the Shioaji API. ```python try: trade = api.place_order(contract, order) except Exception as e: print(f"Order failed: {e}") ``` -------------------------------- ### Query Credit Enquiries and Short Sources Source: https://context7.com/sinotrade/shioaji/llms.txt Retrieves margin/short balance and available borrow shares for stocks. Also includes examples for querying disposition and attention stocks, and converting results to Polars DataFrames. Note the available attributes for each query type. ```python import polars as pl contracts = [api.Contracts.Stocks["2330"], api.Contracts.Stocks["2890"]] # --- Margin and short balance --- enquiries = api.credit_enquires(contracts) for e in enquiries: print(f"{e.stock_id}: margin={e.margin_unit} short={e.short_unit}") # e.update_time, e.system df_credit = pl.DataFrame([c.dict() for c in enquiries]) # --- Available short stock sources (borrow shares) --- sources = api.short_stock_sources(contracts) for s in sources: print(f"{s.code}: available={s.short_stock_source}") # s.ts (timestamp) df_short = pl.DataFrame([s.dict() for s in sources]).with_columns( pl.col("ts").cast(pl.Datetime("ns")) ) # --- Disposition stocks (處置股) --- punish = api.punish() df_punish = pl.DataFrame(punish.dict()) # Columns: code, start_date, end_date, interval, unit_limit, total_limit, description # --- Attention stocks (注意股) --- notice = api.notice() df_notice = pl.DataFrame(notice.dict()) # Columns: code, updated_at, close, reason, announced_date ``` -------------------------------- ### Initialize Project with uv Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/PREPARE.md Create a new packaged application project named 'sj-trading' using uv and navigate into the project directory. ```bash # Create packaged application 建立打包應用程式 uv init sj-trading --package cd sj-trading ``` -------------------------------- ### Configure and Run Tests with uv Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/PREPARE.md Add test commands to your `pyproject.toml` file and then use `uv run` to execute the stock and futures testing scripts. ```bash # Add test commands to pyproject.toml # 將測試命令加入 pyproject.toml [project.scripts] stock_testing = "sj_trading.testing_flow:testing_stock_ordering" futures_testing = "sj_trading.testing_flow:testing_futures_ordering" # Run tests 執行測試 uv run stock_testing uv run futures_testing ``` -------------------------------- ### Configure Project Scripts Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/PREPARE.md Add a 'hello' script to your 'pyproject.toml' file to make the 'hello' function executable from the command line. ```toml [project.scripts] hello = "sj_trading:hello" ``` -------------------------------- ### Get Stock Position Details Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/ACCOUNTING.md Retrieves detailed information for stock positions. You can fetch all position details for a given account or specify a `detail_id` to get information for a particular position. ```python from shioaji import StockPositionDetail # Get all position details 取得所有持倉明細 details = api.list_position_detail(api.stock_account) # Get specific position detail 取得特定持倉明細 detail = api.list_position_detail(api.stock_account, detail_id="position_id") ``` -------------------------------- ### Initialize Shioaji for Production Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/PREPARE.md To switch to the production environment, remove the `simulation=True` argument when initializing the Shioaji API. Ensure your API keys and CA details are correctly configured. ```python # Remove simulation=True for production # 正式環境移除 simulation=True api = sj.Shioaji() # Production mode 正式模式 api.login( api_key=os.environ["API_KEY"], secret_key=os.environ["SECRET_KEY"], ) ``` -------------------------------- ### Scanners Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/MARKET_DATA.md Get market rankings by various criteria. ```APIDOC ## Scanners 掃描器排行 Get market rankings by various criteria. 依各種條件取得市場排行。 ### Scanner Types 掃描器類型 ```python import shioaji as sj sj.constant.ScannerType.ChangePercentRank # 漲跌幅排行 sj.constant.ScannerType.ChangePriceRank # 漲跌價排行 sj.constant.ScannerType.DayRangeRank # 振幅排行 sj.constant.ScannerType.VolumeRank # 成交量排行 sj.constant.ScannerType.AmountRank # 成交金額排行 ``` ### Query Scanners 查詢排行 ```python # Top 10 gainers 漲幅前 10 名 scanners = api.scanners( scanner_type=sj.constant.ScannerType.ChangePercentRank, ascending=False, # False = descending 由大到小 count=10, ) # Top 10 losers 跌幅前 10 名 scanners = api.scanners( scanner_type=sj.constant.ScannerType.ChangePercentRank, ascending=True, # True = ascending 由小到大 count=10, ) # Top volume 成交量排行 scanners = api.scanners( scanner_type=sj.constant.ScannerType.VolumeRank, ascending=False, count=10, ) ``` ### Scanner Attributes 掃描器屬性 ```python scan.date # str: Trade date 交易日 scan.code # str: Stock code 股票代碼 scan.name # str: Stock name 股票名稱 scan.ts # int: Timestamp 時間戳 scan.open # float: Open price 開盤價 scan.high # float: High price 最高價 scan.low # float: Low price 最低價 scan.close # float: Close price 收盤價 scan.price_range # float: Day range 振幅 scan.change_price # float: Price change 漲跌價 scan.change_type # int: Change type 漲跌類型 scan.average_price # float: Average price 均價 scan.volume # int: Last volume 最後成交量 scan.total_volume # int: Total volume 總成交量 scan.amount # int: Last amount 最後成交金額 scan.total_amount # int: Total amount 總成交金額 scan.yesterday_volume # int: Yesterday volume 昨日成交量 scan.volume_ratio # float: Volume ratio 量比 scan.buy_price # float: Bid price 買價 scan.buy_volume # int: Bid volume 買量 scan.sell_price # float: Ask price 賣價 scan.sell_volume # int: Ask volume 賣量 scan.bid_orders # int: Bid side orders 內盤成交單數 scan.bid_volumes # int: Bid side volume 內盤成交量 scan.ask_orders # int: Ask side orders 外盤成交單數 scan.ask_volumes # int: Ask side volume 外盤成交量 scan.tick_type # int: 1=外盤, 2=內盤, 0=無法判定 ``` ### Convert to Polars 轉換為 Polars ```python import polars as pl scanners = api.scanners( scanner_type=sj.constant.ScannerType.ChangePercentRank, count=50, ) # Use BaseModel.dict() to convert 使用 BaseModel.dict() 轉換 df = pl.DataFrame([s.dict() for s in scanners]) # Filter high volume ratio 篩選量比高的 high_volume = df.filter(pl.col("volume_ratio") > 2) ``` ``` -------------------------------- ### Snapshot Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/MARKET_DATA.md Get current snapshot data for multiple contracts (up to 500 per request). ```APIDOC ## Snapshot 即時快照 Get current snapshot for multiple contracts (max 500 per request). 取得多個合約的當前快照(每次最多 500 個)。 ```python contracts = [ api.Contracts.Stocks["2330"], api.Contracts.Stocks["2317"], ] snapshots = api.snapshots(contracts) ``` ### Snapshot Attributes 快照屬性 ```python snap.ts # int: Timestamp 時間戳 snap.code # str: Stock code 股票代碼 snap.exchange # str: Exchange 交易所 snap.open # float: Open price 開盤價 snap.high # float: High price 最高價 snap.low # float: Low price 最低價 snap.close # float: Close price 收盤價 snap.tick_type # TickType: Buy/Sell 內外盤 snap.change_price # float: Price change 漲跌價 snap.change_rate # float: Change rate % 漲跌幅 snap.change_type # ChangeType: Up/Down/Unchanged/LimitUp/LimitDown snap.average_price # float: Average price 均價 snap.volume # int: Last volume 最後成交量 snap.total_volume # int: Total volume 總成交量 snap.amount # int: Last amount 最後成交金額 snap.total_amount # int: Total amount 總成交金額 snap.yesterday_volume # float: Yesterday volume 昨日成交量 snap.buy_price # float: Bid price 買價 snap.buy_volume # float: Bid volume 買量 snap.sell_price # float: Ask price 賣價 snap.sell_volume # int: Ask volume 賣量 snap.volume_ratio # float: Volume ratio 量比 ``` ### Convert to Polars 轉換為 Polars ```python import polars as pl # Use BaseModel.dict() to convert 使用 BaseModel.dict() 轉換 df = pl.DataFrame([s.dict() for s in snapshots]) ``` ``` -------------------------------- ### Initialize Shioaji API and Login Source: https://github.com/sinotrade/shioaji/blob/master/README.md Initialize the Shioaji API instance and log in using your token and secret key. Activate your CA certificate with its path and password. ```python import shioaji as sj api = sj.Shioaji() accounts = api.login("YOUR_TOKEN", "YOUR_SECRET_KEY") api.activate_ca( ca_path="/c/your/ca/path/Sinopac.pfx", ca_passwd="YOUR_CA_PASSWORD", ) ``` -------------------------------- ### Modify Order Price Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/ORDERS.md Example of changing the price of an existing order using the `update_order` function. ```python api.update_order(trade=trade, price=585) ``` -------------------------------- ### Initialize Shioaji API and Login Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/CONTRACTS.md Initializes the Shioaji API and logs in using provided API keys. Contracts are automatically downloaded after a successful login. ```python import shioaji as sj api = sj.Shioaji() api.login(api_key="YOUR_KEY", secret_key="YOUR_SECRET") ``` -------------------------------- ### Clone and Navigate Demo Project Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/PREPARE.md Clone the official Shioaji trading demo project from GitHub and navigate into the project directory. ```bash git clone https://github.com/Sinotrade/sj-trading-demo.git cd sj-trading-demo ``` -------------------------------- ### Get Snapshots Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/ADVANCED.md Retrieving current market data for multiple contracts simultaneously. Supports up to 500 contracts. ```APIDOC ## Snapshots 快照 Get current market data for multiple contracts: 取得多個合約的當前市場數據: ```python contracts = [ api.Contracts.Stocks["2330"], api.Contracts.Stocks["2317"], api.Contracts.Futures["TXFC0"], ] # Max 500 contracts 最多 500 個合約 snapshots = api.snapshots(contracts) for snap in snapshots: print(f"{snap.code}: {snap.close} ({snap.change_rate}%)") ``` ``` -------------------------------- ### Contract in Watchlist Attributes Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/WATCHLIST.md Access attributes of a contract within a watchlist to get its security type, exchange, and code. ```python contract.security_type # SecurityType: Stock/Future/Option/Index 商品類型 contract.exchange # Exchange: TSE/OTC/TAIFEX 交易所 contract.code # str: Contract code 合約代碼 ``` -------------------------------- ### Market Order Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/ORDERS.md Example of placing a market order where the price is ignored and the order is executed at the best available market price. ```APIDOC ### Market Order 市價單 ```python order = api.Order( price=0, # Price ignored for MKT 市價單忽略價格 quantity=1, action=sj.constant.Action.Buy, price_type=sj.constant.StockPriceType.MKT, order_type=sj.constant.OrderType.IOC, # MKT requires IOC/FOK 市價須 IOC/FOK account=api.stock_account, ) ``` ``` -------------------------------- ### Basic Stock Order Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/ORDERS.md Demonstrates how to place a basic stock order with specified parameters like price, quantity, action, and order types. ```APIDOC ## Basic Stock Order 基本股票下單 ```python contract = api.Contracts.Stocks["2330"] order = api.Order( price=580, 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, account=api.stock_account, ) trade = api.place_order(contract, order) ``` ### Order Parameters 訂單參數 | Parameter 參數 | Type 類型 | Description 說明 | |----------------|-----------|------------------| | `price` | float/int | Order price 委託價格 | | `quantity` | int | Order quantity 委託數量 | | `action` | Action | Buy/Sell 買/賣 | | `price_type` | PriceType | LMT/MKT/MKP 限價/市價/範圍市價 | | `order_type` | OrderType | ROD/IOC/FOK 委託條件 | | `order_lot` | OrderLot | Common/Odd/IntradayOdd/Fixing 交易單位 | | `order_cond` | OrderCond | Cash/MarginTrading/ShortSelling 信用條件 | | `account` | Account | Trading account 交易帳戶 | | `custom_field` | str | Memo (max 6 chars) 備註(最多6字元)| ``` -------------------------------- ### Query Scanners Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/ADVANCED.md Examples of querying scanners to retrieve ranked market data, such as top gainers, losers, or high-volume stocks. ```APIDOC ### Query Scanners 查詢掃描器 ```python # Top 10 gainers 漲幅前 10 名 scanners = api.scanners( scanner_type=sj.constant.ScannerType.ChangePercentRank, ascending=False, # Descending 由大到小 count=10 ) # Top 10 losers 跌幅前 10 名 scanners = api.scanners( scanner_type=sj.constant.ScannerType.ChangePercentRank, ascending=True, # Ascending 由小到大 count=10 ) # Top 10 by volume 成交量前 10 名 scanners = api.scanners( scanner_type=sj.constant.ScannerType.VolumeRank, ascending=False, count=10 ) ``` ``` -------------------------------- ### Initialize Shioaji API in Simulation Mode Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/PREPARE.md Instantiate the Shioaji API with the 'simulation=True' argument to enable trading in the simulation environment. ```python import shioaji as sj # Enable simulation mode 啟用模擬模式 api = sj.Shioaji(simulation=True) ``` -------------------------------- ### Get Single Watchlist Details Source: https://context7.com/sinotrade/shioaji/llms.txt Retrieves a specific watchlist by its ID and prints the code, security type, and exchange for each contract within it. ```python # --- Get single watchlist --- wl = api.get_watchlist("watchlist_id") for c in wl.contracts: print(c.code, c.security_type, c.exchange) ``` -------------------------------- ### Get Single Watchlist Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/WATCHLIST.md Retrieves a specific watchlist by its unique ID. Displays the watchlist's name and the list of contracts it contains. ```APIDOC ## Get Single Watchlist ### Description Retrieves a specific watchlist by its ID. Displays the watchlist's name and its contracts. ### Method `get_watchlist(group_id: str, timeout: int = 5000, cb: Callable = None)` ### Parameters #### Path Parameters - **group_id** (str) - Required - Watchlist ID #### Query Parameters - **timeout** (int) - Optional - Request timeout in ms (Default: 5000) - **cb** (Callable) - Optional - Callback for async mode ### Request Example ```python watchlist = api.get_watchlist("watchlist_id") print(f"Name: {watchlist.name}") for contract in watchlist.contracts: print(f" - {contract.code} ({contract.security_type})") ``` ### Response #### Success Response Returns a watchlist object with `name` and a list of `contracts`. ``` -------------------------------- ### Place Options Order Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/ORDERS.md Demonstrates how to place buy or sell orders for options contracts. ```APIDOC ## Place Options Order ### Description Place buy or sell orders for options contracts. ### Method `api.place_order(contract, order)` ### Parameters #### Contract - **contract**: The options contract object (e.g., `api.Contracts.Options["TXO202401C18000"]`). #### Order - **price** (float/int) - Order price. - **quantity** (int) - Number of contracts. - **action** (Action) - Buy or Sell. - **price_type** (FuturesPriceType) - Limit (LMT), Market (MKT), or Market-to-Limit (MKP). - **order_type** (OrderType) - Day order (ROD), Immediate or Cancel (IOC), or Fill or Kill (FOK). - **octype** (FuturesOCType) - Auto, NewPosition, Cover, or DayTrade. - **account** (Account) - The futures/options account object. ### Request Example ```python # Buy call option contract = api.Contracts.Options["TXO202401C18000"] order = api.Order( price=100, quantity=1, action=sj.constant.Action.Buy, price_type=sj.constant.FuturesPriceType.LMT, order_type=sj.constant.OrderType.ROD, octype=sj.constant.FuturesOCType.Auto, account=api.futopt_account, ) trade = api.place_order(contract, order) ``` ``` -------------------------------- ### Add Shioaji Dependency with uv Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/PREPARE.md Add the 'shioaji' library as a dependency to your project using the uv add command. ```bash uv add shioaji ``` -------------------------------- ### Create and Monitor Multiple Stocks Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/WATCHLIST.md Create a watchlist for specific stocks and then retrieve snapshots for all contracts within that watchlist that are of type 'STK'. Prints the code, close price, and change rate for each snapshot. ```python # Create a tech watchlist 建立科技股清單 tech_watchlist = api.create_watchlist( name="Tech Stocks", contracts=[ api.Contracts.Stocks["2330"], # TSMC api.Contracts.Stocks["2454"], # MediaTek api.Contracts.Stocks["2317"], # Hon Hai api.Contracts.Stocks["2308"], # Delta ] ) # Get snapshots for all contracts 取得所有合約快照 snapshots = api.snapshots([ api.Contracts.Stocks[c.code] for c in tech_watchlist.contracts if c.security_type == "STK" ]) for snap in snapshots: print(f"{snap.code}: {snap.close} ({snap.change_rate}%)") ``` -------------------------------- ### Place a Stock Order Source: https://github.com/sinotrade/shioaji/blob/master/README.md Create and place a limit order for a stock. Specify price, quantity, action (Buy/Sell), price type, order type, order lot, and the relevant account. ```python contract = api.Contracts.Stocks["2890"] order = api.Order( price=9.6, quantity=1, action="Buy", price_type="LMT", order_type="ROD", order_lot="Common", account=api.stock_account, ) ``` -------------------------------- ### Stock Reservation and Earmarking Source: https://context7.com/sinotrade/shioaji/llms.txt Demonstrates how to reserve shares, reserve all available shares, pre-pay for cash buys, and query reservation and earmarking details. ```APIDOC ## Reserve Shares ### Description Reserves a specified number of shares for a given stock contract. ### Method `api.reserve_stock(account, contract, quantity)` ### Parameters - `account`: The trading account. - `contract`: The stock contract object. - `quantity` (int): The number of shares to reserve. ### Request Example ```python contract = api.Contracts.Stocks["2890"] resp = api.reserve_stock(api.stock_account, contract, 1000) ``` ### Response Example ``` Reserved: status=SUCCESS shares=1000 info=None ``` ## Reserve All Available Shares ### Description Reserves all available shares for each stock in the summary. ### Method `api.reserve_stock(account, contract, available_share)` ### Parameters - `account`: The trading account. - `contract`: The stock contract object. - `available_share` (int): The number of available shares to reserve. ### Request Example ```python for stock in summary.response.stocks: if stock.available_share > 0: r = api.reserve_stock(api.stock_account, stock.contract, stock.available_share) print(f"{stock.contract.code}: {r.response.status}") ``` ## Pre-payment (Earmarking) for Cash Buy ### Description Earmarks a specified amount for a cash buy order. ### Method `api.reserve_earmarking(account, contract, quantity, price)` ### Parameters - `account`: The trading account. - `contract`: The stock contract object. - `quantity` (int): The number of shares. - `price` (float): The price per share. ### Request Example ```python resp2 = api.reserve_earmarking(api.stock_account, contract, 1000, 15.15) ``` ### Response Example ``` Earmarked: amount=15150.0 status=SUCCESS ``` ## Query Reserve Detail ### Description Retrieves the reservation details for stocks. ### Method `api.stock_reserve_detail(account)` ### Parameters - `account`: The trading account. ### Request Example ```python detail = api.stock_reserve_detail(api.stock_account) ``` ### Response Example ``` 2890: shares=1000 status=RESERVED info=None ``` ## Query Earmarking Detail ### Description Retrieves the earmarking details for stocks. ### Method `api.earmarking_detail(account)` ### Parameters - `account`: The trading account. ### Request Example ```python emark_detail = api.earmarking_detail(api.stock_account) ``` ### Response Example ``` 2890: shares=1000 price=15.15 amount=15150.0 ``` ``` -------------------------------- ### Get Specific Watchlist by ID Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/WATCHLIST.md Fetches a single watchlist using its unique identifier. Prints the name and details of each contract within the retrieved watchlist. ```python # Get watchlist by ID 依 ID 取得清單 watchlist = api.get_watchlist("watchlist_id") print(f"Name: {watchlist.name}") for contract in watchlist.contracts: print(f" - {contract.code} ({contract.security_type})") ``` -------------------------------- ### Subscribe to Market Data (Bid/Ask) Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/SKILL.md Demonstrates how to subscribe to real-time bid/ask (5-level) data for a specific stock contract using the Shioaji API. ```python # Subscribe bidask 訂閱五檔 api.quote.subscribe( api.Contracts.Stocks["2330"], quote_type=sj.constant.QuoteType.BidAsk ) ``` -------------------------------- ### Query Historical KBars Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/MARKET_DATA.md Retrieve historical 1-minute K-bar data for a stock within a specified date range. Ensure the contract, start, and end dates are correctly provided. ```python kbars = api.kbars( contract=api.Contracts.Stocks["2330"], start="2023-01-15", end="2023-01-16", ) ``` -------------------------------- ### Fetch Multiple Contracts and Snapshots Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/CONTRACTS.md Demonstrates how to request snapshots for multiple contracts (up to 500) and iterate through the results. Ensure contracts are defined using the `api.Contracts` object. ```python contracts = [ api.Contracts.Stocks["2330"], api.Contracts.Stocks["2317"], api.Contracts.Futures["TXFC0"], ] snapshots = api.snapshots(contracts) for snap in snapshots: print(f"{snap.code}: {snap.close} ({snap.change_price})") ``` -------------------------------- ### Get K-bars with Custom Indicators (Polars) Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/ADVANCED.md Retrieve k-bar data and enrich it with custom technical indicators like EMA and MACD using Polars for efficient data manipulation. ```python df = qm.get_kbars("5m").with_columns([ pl.col("close").ta.ema(5).over("code").alias("ema5"), pl.col("close").ta.ema(20).over("code").alias("ema20"), plta.macd(pl.col("close"), 12, 26, 9).over("code").struct.field("macd"), ]) ``` -------------------------------- ### Create a New Watchlist Source: https://context7.com/sinotrade/shioaji/llms.txt Creates a new watchlist with a specified name and a list of initial stock contracts. Prints the ID of the newly created watchlist. ```python # --- Create watchlist --- tech_wl = api.create_watchlist( name="Tech Stocks", contracts=[ api.Contracts.Stocks["2330"], # TSMC api.Contracts.Stocks["2454"], # MediaTek api.Contracts.Stocks["2317"], # Hon Hai ] ) print(f"Created watchlist: {tech_wl.id}") ``` -------------------------------- ### Subscribe to Watchlist Quotes Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/WATCHLIST.md Retrieve a watchlist by its ID and then subscribe to the quotes for each contract in the watchlist. It handles different security types (Stock, Future) to get the full contract object before subscribing. ```python watchlist = api.get_watchlist("watchlist_id") for contract in watchlist.contracts: # Get full contract object 取得完整合約物件 if contract.security_type.value == "STK": full_contract = api.Contracts.Stocks[contract.code] elif contract.security_type.value == "FUT": full_contract = api.Contracts.Futures[contract.code] api.quote.subscribe(full_contract) ``` -------------------------------- ### Get Trading Limits Source: https://context7.com/sinotrade/shioaji/llms.txt Fetches and displays trading limits, used amount, available amount, margin available, and short available for stock accounts. Includes a warning for low available trading limits. ```python limits = api.trading_limits(api.stock_account) print(f"Trading limit: {limits.trading_limit}") print(f"Used: {limits.trading_used}") print(f"Available: {limits.trading_available}") print(f"Margin available: {limits.margin_available}") print(f"Short available: {limits.short_available}") if limits.trading_available < 100_000: print("Warning: Low trading limit!") ``` -------------------------------- ### List All Options Contracts Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/CONTRACTS.md Retrieves a list of all available options contracts. ```python all_options = [c for c in api.Contracts.Options] ``` -------------------------------- ### Get Market Snapshots for Multiple Contracts Source: https://github.com/sinotrade/shioaji/blob/master/skills/shioaji/references/ADVANCED.md Retrieve current market data for a list of contracts. The API supports fetching snapshots for up to 500 contracts at once. Iterate through the results to access individual snapshot data. ```python contracts = [ api.Contracts.Stocks["2330"], api.Contracts.Stocks["2317"], api.Contracts.Futures["TXFC0"], ] # Max 500 contracts 最多 500 個合約 snapshots = api.snapshots(contracts) for snap in snapshots: print(f"{snap.code}: {snap.close} ({snap.change_rate}%)") ``` -------------------------------- ### Place Stock Order (`api.place_order`) Source: https://context7.com/sinotrade/shioaji/llms.txt Place various types of stock orders including limit, market, odd-lot, margin, and day-trade orders. ```APIDOC ## Place Stock Order (`api.place_order`) Place limit, market, odd-lot, margin, or day-trade stock orders by constructing an `Order` object and passing a contract. ```python import shioaji as sj contract = api.Contracts.Stocks["2330"] ``` -------------------------------- ### Get Futures Margin Information Source: https://context7.com/sinotrade/shioaji/llms.txt Retrieves and prints today's balance, available margin, maintenance margin, margin call status, risk indicator, and open P&L for futures and options accounts. ```python margin = api.margin(api.futopt_account) print(f"Today balance: {margin.today_balance}") print(f"Available margin: {margin.available_margin}") print(f"Maintenance margin: {margin.maintenance_margin}") print(f"Margin call: {margin.margin_call}") print(f"Risk indicator: {margin.risk_indicator}") print(f"Futures open P&L: {margin.future_open_position}") print(f"Options open P&L: {margin.option_open_position}") ```