Shioaji api 永豐金

Shiaoji SinoPac 永豐金證券 Python API

By Jason Chuang 2023-05-03

Git Source Code

Requirements

Install required packages

pip install  -r requirements.txt

Modify .env file

cp .env.template .env

欲開通正式環境API下單權限,客戶須於模擬環境完成登入及下單測試.

api = sj.Shioaji(simulation=True) # 模擬模式登入
accounts = api.login(
    api_key=os.getenv('API_KEY'),
    secret_key=os.getenv('SECRET_KEY')  
)
accounts

等正式開通後,會出現signed=True

Response Code: 0 | Event Code: 0 | Info: host '203.66.91.161:80', hostname '203.66.91.161:80' 
IP 203.66.91.161:80 (host 1 of 1) (host connection attempt 1 of 1) (total connection attempt 1 of 1) | 
Event: Session up[FutureAccount(person_id='F123456789', broker_id='F002000', account_id='1234567', signed=True, username='莊OO'), 
StockAccount(person_id='F123456789', broker_id='9A95', account_id='1234568', signed=True, username='莊OO')]

要正式下單時記得CA憑證路徑要用斜線(/)

CA_PATH="C:/ekey/123/F12345678/S/Sinopac.pfx"

登入及查詢帳號餘額


api = sj.Shioaji(simulation=False) 
accounts = api.login(
    api_key=os.getenv('API_KEY'),
    secret_key=os.getenv('SECRET_KEY')  
)
tmp=api.account_balance()
print(tmp)

查詢0050報價


api = sj.Shioaji(simulation=False) 
accounts = api.login(
    api_key=os.getenv('API_KEY'),
    secret_key=os.getenv('SECRET_KEY')  
)
tmp = api.quote.subscribe(
    api.Contracts.Stocks["0050"], 
    quote_type = sj.constant.QuoteType.Tick,
    version = sj.constant.QuoteVersion.v1
)
print(tmp)

下單限價單買00878


api = sj.Shioaji(simulation=False) # 正式模式
accounts = api.login(
    api_key=os.getenv('API_KEY'),
    secret_key=os.getenv('SECRET_KEY')  
)
accounts
## Activate CA
result = api.activate_ca(
    ca_path=os.getenv('CA_PATH'),
    ca_passwd=os.getenv('CA_PASSWD'),
    person_id=os.getenv('PERSON_ID')
)
print(result)
# 商品檔 - 請修改此處
contract = api.Contracts.Stocks.TSE["00878"]
# 證券委託單 - 請修改此處
order = api.Order(
    price=17.67,                                    # 價格
    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)
trade

Reference

https://github.com/Sinotrade/Shioaji

Tutorial for Shioaji

永豐金證券API