Metadata-Version: 2.4
Name: kgiapp
Version: 3.0.1
Summary: Python client for send order to KGI Securities.
Home-page: https://github.com/phymach
Author: Leo Wu
Author-email: phymach@gmail.com
License: MIT
Keywords: stock,futures,option,TWSE,TPEX,TAIFEX
Classifier: Development Status :: 4 - Beta
Classifier: License :: OSI Approved :: MIT License
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Operating System :: OS Independent
Classifier: Topic :: Office/Business :: Financial
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.13
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: cryptography>=42
Requires-Dist: pandas
Requires-Dist: pyyaml
Requires-Dist: websockets>=14.0
Provides-Extra: mcp
Requires-Dist: fastmcp>=4.0.0; extra == "mcp"
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: license
Dynamic: license-file
Dynamic: provides-extra
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# kgiapp

![PyPI](https://img.shields.io/pypi/v/kgiapp)
![PyPI - Python Version](https://img.shields.io/pypi/pyversions/kgiapp)
![PyPI - Format](https://img.shields.io/pypi/format/kgiapp)
![PyPI - License](https://img.shields.io/pypi/l/kgiapp)
![PyPI - Downloads](https://img.shields.io/pypi/dm/kgiapp)

(非官方) 凱基證券程式下單API整合了報價與交易介面，讓使用者可以輕鬆的運用python執行快速下單。

>kgiapp is a securities, futures, option API, which send orders to Concord Securities Group.
This package is pure Python and is compatible with Python 3.13+.
It is distributed under the MIT license.

- [Installation](#installation)
    - [Preinstall](#preinstall)
    - [Install](#install)
    - [Certificate](#certificate)
- [Quick Starts](#quick-starts)
    - [Login](#login)
    - [Register Event](#register-event)
- [Place Order](#place-order)
    - [Stock](#stock)
    - [Cancel Order](#cancel-order)
    - [Futures](#futures)
    - [Foreign Futures](#foreign-futures)
- [Account Query](#account-query)
- [Quote](#quote)
- [Gateway](#gateway)
    - [WebSocket](#websocket)
    - [MCP](#mcp)
- [Upgrade from 2.x](#upgrade-from-2x)
- [Reference](#reference)


## Installation
### Preinstall
本套件為非官方實作。使用前需先向凱基證券申請 API 權限與下單憑證，並確認使用方式符合凱基的 API 條款。

### Install
需要 Python 3.13 以上。報價與下單都是純 Python，不需要 .NET 或官方 DLL。

```
pip install kgiapp
```

> **注意：下單功能尚未在凱基正式主機完成驗證。** 封包與簽章已和官方 DLL 逐 byte 比對，但實際使用前請先以盤中零股 1 股測試，並確認第二回覆的 `ErrorCode` 為 0。

### Certificate
下單需要憑證檔 (`.pfx`)。憑證已安裝在 Windows 時，可用 PowerShell 匯出：

```powershell
New-Item -ItemType Directory -Force C:\secure | Out-Null
$cert = Get-ChildItem Cert:\CurrentUser\My | Where-Object { $_.Issuer -match 'TaiCA' -and $_.NotAfter -gt (Get-Date) }
$cert.Count   # 應該是 1
$pfxPwd = Read-Host -AsSecureString "設定 PFX 密碼"
Export-PfxCertificate -Cert $cert -FilePath C:\secure\kgi.pfx -Password $pfxPwd -CryptoAlgorithmOption AES256_SHA256
```

`.pfx` 等同你的下單身分，請放在 repo 以外的位置，檔案與密碼都不要提交到 git。憑證過期時 `TradeAPI` 會拒絕登入與送單。

## Quick Starts
### Login
`TradeAPI` 預設連測試主機，要連正式主機必須傳 `debug=False`，此時送出的都是真實委託。

```python
from kgiapp import TradeAPI

agent = TradeAPI("C:/secure/kgi.pfx", "YOUR_PFX_PASSWORD", debug=False)
if not agent.login("YOUR_PERSON_ID", "YOUR_PASSWORD"):
    raise SystemExit("登入失敗")

print(agent.accounts)   # 登入回傳的帳號, key 為 分公司-帳號
```

用完請呼叫 `agent.close()`，或用 `with` 自動關閉。

### Register Event
回報與查詢結果都是非同步的，用 `add_listener` 接收。listener 在收包執行緒上呼叫，不可長時間阻塞。

```python
def on_event(event):
    if event['kind'] == 'status':
        print(event['name'], event['message'])
    elif event['name'] in ('SECU_ORDER_ACK', 'SECU_ORDER_ACK_N'):
        print('委託書號', event['data']['OrderNo'], 'ErrorCode', event['data']['ErrorCode'])
    else:
        print(event['name'], event['data'])

agent.add_listener(on_event)
```

| 欄位 | 說明 |
|---|---|
| `source` | `trade` 或 `quote` |
| `kind` | `message`（封包）或 `status`（連線狀態） |
| `name` | 封包或狀態名稱，對應 `kgiapp.Common.datatype.DataType` |
| `dt` / `topic` / `data` | `message` 才有；尚未解析的封包 `data` 為空 |
| `message` | `status` 才有 |

## Place Order
下單函式回傳 `request_id`，參數有誤時丟出 `OrderError`。`ACK_REQUESTID` 只代表主機收到封包，最終結果要看第二回覆的錯誤碼：

| 商品 | 第二回覆 | 錯誤碼欄位 | 委託回報 | 成交回報 |
|---|---|---|---|---|
| 股票 | `SECU_ORDER_ACK_N` | `ErrorCode` | `SECU_ORDER_RPT` | `SECU_DEAL_RPT` |
| 期貨 | `FUT_ORDER_ACK` | `ErrorCode` | `FUT_ORDER_RPT` | `FUT_DEAL_RPT` |
| 海外期貨 | `FFUT_ORDER_ACK` | `ErrCode` | `FFUT_ORDER_RPT` | `FFUT_DEAL_RPT` |

收盤後送出的委託可能只有 `ACK_REQUESTID`、沒有第二回覆，請以下單軟體查到的結果為準，不要重複送單。

### Stock
```python
from kgiapp.Trade.constant import SecurityAction, LotType, OrderType, Side, SecurityPriceFlag, TimeInForce

request_id = agent.stock_order(action=SecurityAction.NEW_ORDER, broker_no='YOUR_BROKER_NO', account_no='YOUR_ACCOUNT', lot_type=LotType.ODD_LOT_INTRA,
                               order_type=OrderType.ORDINARY, side=Side.BUY, symbol='2330', quantity=1, price=570, price_flag=SecurityPriceFlag.FIX,
                               time_in_force=TimeInForce.ROD)
```

`LotType` 有 `ROUND_LOT`（整股）、`ODD_LOT`（盤後零股）、`ODD_LOT_INTRA`（盤中零股）、`FIX_PRICE`（定價）、`BLOCK_LOT`（鉅額）。API 沒有預約單。

### Cancel Order
用第二回覆的 `OrderNo` 刪單，其他欄位和原委託相同。刪單流程尚未實測，失敗時請用下單軟體刪單。

```python
agent.stock_order(action=SecurityAction.CANCEL_ORDER, broker_no='YOUR_BROKER_NO', account_no='YOUR_ACCOUNT', lot_type=LotType.ODD_LOT_INTRA,
                  order_type=OrderType.ORDINARY, side=Side.BUY, symbol='2330', quantity=1, price=570, price_flag=SecurityPriceFlag.FIX,
                  time_in_force=TimeInForce.ROD, order_id='YOUR_ORDER_NO')
```

### Futures
```python
from kgiapp.Trade.constant import Action, Market, TimeInForce, WriteOff, PriceFlag, Side

agent.futures_order(action=Action.NEW_ORDER, branch_no='YOUR_FUTURES_BROKER_NO', account_no='YOUR_FUTURES_ACCOUNT', sub_account_no='', market_type=Market.FUTURES,
                    tb_20_code='MXFL6', time_in_force=TimeInForce.ROD, writeoff=WriteOff.OPEN, order_type=PriceFlag.LIMIT, side=Side.BUY, quantity=1, price=15100)
```

### Foreign Futures
```python
from kgiapp.Trade.constant import Action, ForeignPriceFlag, Market, Side, TimeInForce, WriteOff

agent.foreign_futures_order(action=Action.NEW_ORDER, market_type=Market.FUTURES, branch_no='YOUR_FUTURES_BROKER_NO', account_no='YOUR_FUTURES_ACCOUNT',
                            sub_account_no='', exchange='CME', symbol='ES', side1=Side.BUY, ComYM1='202612', strike_price1=0, cp1='F',
                            symbol2='', side2=Side.BUY, ComYM2='', strike_price2=0, cp2=' ', order_type=ForeignPriceFlag.LIMIT, daytrade='N',
                            writeoff=WriteOff.OPEN, time_in_force=TimeInForce.ROD, order_price=5000, stop_price=0, quantity=1)
```

## Account Query
查詢結果同樣由 listener 收到。

```python
agent.stock_inventory_summary('YOUR_BROKER_NO', 'YOUR_ACCOUNT')   # 回覆 FINANCIAL_WSINVENTORYSUM
agent.realized_profit('YOUR_BROKER_NO', 'YOUR_ACCOUNT', days=60)   # 回覆 FINANCIAL_WSREALIZEPL
```

| 函式 | 說明 | 回覆 |
|---|---|---|
| `stock_settlement_trial` | 當日交割金額試算 | `FINANCIAL_WSSETAMTTRIAL` |
| `stock_settlement_detail` | 當日交割金額沖銷明細 | `FINANCIAL_WSSETAMTDETAIL` |
| `stock_settlement` | 交割金額查詢 (3 日) | `FINANCIAL_WSSETTLEAMT` |
| `stock_inventory` | 庫存損益及維持率試算 | `FINANCIAL_WSINVENTORY` |
| `stock_inventory_summary` | 證券庫存彙總 | `FINANCIAL_WSINVENTORYSUM` |
| `balance_statement` | 證券對帳單 | `FINANCIAL_WSBALANCESTATEMENT` |
| `realized_profit` | 已實現損益 | `FINANCIAL_WSREALIZEPL` |
| `stock_credit` | 資券餘額 | `SECU_CREDITINFO` |

## Quote
目前支援股票與零股的成交、五檔、最新價，以及上市櫃商品檔和 ETF 成分股。其他行情封包的 `data` 為空，權證查詢尚未支援。報價不需要憑證，`QuoteAPI` 預設連正式主機。

```python
import time

from kgiapp import QuoteAPI

with QuoteAPI() as quote:
    quote.add_listener(print)
    if not quote.login("YOUR_PERSON_ID", "YOUR_PASSWORD"):
        raise SystemExit("登入失敗")

    time.sleep(1)
    print(quote.subscribe('2330'))   # 回傳註冊失敗訊息, 空 list 表示成功
    quote.get_last_price('2330')
    time.sleep(60)
```

成交與五檔事件為 `QUOTE_STOCK_MATCH1/2`、`QUOTE_STOCK_DEPTH1/2`，零股為 `QUOTE_ODD_MATCH1/2`、`QUOTE_ODD_DEPTH1/2`，最新價為 `QUOTE_LAST_PRICE_STOCK`。訂閱零股時傳 `is_odd=True`。

## Gateway
唯讀 gateway 持有唯一一條 KGI 連線，提供行情訂閱與帳務查詢。**gateway 與 MCP 都沒有下單、改單、刪單功能**，下單請直接使用 `TradeAPI`。

```
pip install kgiapp[mcp]
```

帳密只從環境變數讀取，不會由 client 傳入：

| 環境變數 | 說明 | 預設 |
|---|---|---|
| `KGIAPP_ID` / `KGIAPP_PASSWORD` | 登入帳密 | 必填 |
| `KGIAPP_PFX_PATH` / `KGIAPP_PFX_PASSWORD` | 憑證檔與密碼，啟用帳務查詢時必填 | 無 |
| `KGIAPP_BROKER_NO` / `KGIAPP_ACCOUNT_NO` | 帳務查詢預設帳號 | 無 |
| `KGIAPP_GATEWAY_HOST` / `KGIAPP_GATEWAY_PORT` | 監聽位址 | `127.0.0.1` / `8765` |
| `KGIAPP_GATEWAY_TOKEN` | 連線 token，監聽非本機位址時必填 | 無 |
| `KGIAPP_DEBUG` | 使用測試主機 | `0` |
| `KGIAPP_ENABLE_QUERY` | 啟用帳務查詢與回報（會登入交易主機） | `1` |

```
kgiapp-gateway
```

### WebSocket
連線 `ws://127.0.0.1:8765`，訊息皆為 JSON。有設定 token 時，第一則訊息必須是 `{"op": "auth", "token": "..."}`。瀏覽器連線預設會被拒絕。

| op | 參數 | 說明 |
|---|---|---|
| `subscribe` / `unsubscribe` | `channel`, `symbol` | channel: `match`, `depth`, `odd_match`, `odd_depth`, `report`（`report` 不需 symbol） |
| `snapshot` | `symbol`, `odd` | 最新價與五檔 |
| `queries` | | 列出可用查詢 |
| `query` | `name`, `params` | 帳務查詢，例如 `inventory_summary` |
| `status` / `ping` | | 連線狀態 |

```python
import asyncio
from kgiapp.gateway.client import GatewayClient


async def main():
    async with GatewayClient(on_event=print) as client:
        await client.subscribe('match', '2330')
        print(await client.snapshot('2330'))
        await asyncio.sleep(60)

asyncio.run(main())
```

回覆為 `{"id": 1, "ok": true, "result": {...}}`，推送為 `{"type": "event", "channel": "match", "symbol": "2330", "data": {...}}`，連線狀態為 `{"type": "status", ...}`。

### MCP
先啟動 `kgiapp-gateway`，再將 MCP client 指向 `kgiapp-mcp`（stdio）。MCP server 不另外登入，多個 client 共用同一條 KGI 連線。

```json
{
  "mcpServers": {
    "kgiapp": {"command": "kgiapp-mcp"}
  }
}
```

提供 `get_quote`, `watch_symbol`, `unwatch_symbol`, `get_recent_reports`, `list_account_queries`, `query_account`, `gateway_status`。

## Upgrade from 2.x
3.0 起 `TradeAPI` 改為純 Python，舊程式需要修改：

- `TradeAPI(debug=False)` 改為 `TradeAPI(pfx_path, pfx_password, debug=False)`，且 `debug` 預設為 `True`。
- 常數仍在 `kgiapp.Trade.constant`，但改為一般字串，`Security_OrdType` 等 .NET 型別不再提供。
- 下單函式回傳 `request_id`，參數有誤時丟出 `OrderError`，不再只寫 log。
- `agent.conn` 與 .NET 物件已移除，回報請改用 `add_listener`。
- 仍需官方 DLL 版本時請安裝 `pip install "kgiapp==2.1.0"`。

## Reference
- [docs/](docs/)：凱基提供的 QuoteCom、TradeCom 格式與範例文件。文件描述官方 DLL 的用法，封包欄位名稱與本套件相同。
