Metadata-Version: 2.4
Name: kgiapp
Version: 3.0.0rc2
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 :: 2 - Pre-Alpha
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)
![contact](https://img.shields.io/badge/凱基證券)

凱基證券程式下單 API 的純 Python 實作，讓使用者可以輕鬆的運用 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)
    - [Binaries](#binaries)
- [Quick Starts](#quick-starts)
    - [Login](#login)
- [Place Order](#place-order)
    - [Stock](#stock)
    - [Futures](#futures)
    - [Foreign Futures](#foreign-futures)
- [Register Event](#register-event)
- [Quote](#quote)
- [Gateway](#gateway)
    - [WebSocket](#websocket)
    - [MCP](#mcp)
- [Reference](#reference)


## Installation
### Preinstall
>API usage needs application in advance. In order to use this package, please contact us.

### Binaries

simply use pip to install
```
pip install kgiapp
```

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

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

下單需要憑證檔 (`.pfx`)，請放在 repo 以外的位置並妥善保管，它等同你的下單身分。

## Quick Starts
### Login
```python
from kgiapp import TradeAPI

agent = TradeAPI("C:/secure/kgi.pfx", "YOUR_PFX_PASSWORD", debug=False)   # debug 預設為 True (測試主機)
agent.login("YOUR_PERSON_ID", "YOUR_PASSWORD")
```

## Place Order
下單函式回傳 `request_id`。序號回覆只代表主機收到封包，最終結果要看 `SECU_ORDER_ACK_N` 等回覆的 `ErrorCode`。

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

agent.stock_order(action=SecurityAction.NEW_ORDER, broker_no='YOUR_BROKER_NO', account_no='YOUR_ACCOUNT', lot_type=LotType.ROUND_LOT, order_type=OrderType.ORDINARY,
                  side=Side.BUY, symbol='2330', quantity=1, price=570, price_flag=SecurityPriceFlag.FIX, time_in_force=TimeInForce.ROD, sub_account_no='', agent_id='', order_id='')
```
### Futures
```python
from kgiapp.Trade.constant import Action, Market, TimeInForce, WriteOff, PriceFlag, Side

agent.futures_order(action=Action.NEW_ORDER, branch_no='YOUR_BROKER_NO', account_no='YOUR_ACCOUNT', sub_account_no='', market_type=Market.FUTURES, tb_20_code='MXFB1',
                    time_in_force=TimeInForce.ROD, writeoff=WriteOff.OPEN, order_type=PriceFlag.LIMIT, side=Side.BUY, quantity=1, price=15100, web_id='', orig_net_no='', order_id='')
```

## 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 不載入 DLL，也不另外登入，多個 client 共用同一條 KGI 連線。

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

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

## Reference
