Paper trading (simulated) for CN/HK/US equities — place/cancel orders, query balance and positions, order/fill history, market session status. Quotes via Sto...
---
name: stocki-trading-assistant
version: 0.1.0
description: "Paper trading (simulated) for CN/HK/US equities — place/cancel orders, query balance and positions, order/fill history, market session status. Quotes via Stocki gateway."
metadata:
openclaw:
emoji: "💹"
requires:
bins: [python3]
env: [STOCKI_GATEWAY_URL, STOCKI_API_KEY]
os: [linux, darwin, win32]
primaryEnv: STOCKI_API_KEY
envVars: [STOCKI_GATEWAY_URL, STOCKI_API_KEY]
---
# stocki-trading-assistant
Paper trading for CN / HK / US equities. The skill wraps a locally-spawned
`paper-trading` service; the service is auto-started on first use. Orders,
positions, and fills are **simulated** — not a live brokerage account.
This file instructs the **Agent**. Do not quote implementation details
(tokens, ports, file paths, script names) to the user unless they are
explicitly troubleshooting via `INSTALL.md`.
## Core principle
**Use this skill** when the user wants simulated trading — place or cancel
orders, check balance/positions/P&L, order or fill history, market session
status.
**Do NOT use** for real-money brokerage execution or personalized buy/sell
recommendations.
**Never fabricate** balances, positions, fills, or order states. If a value
is missing or the service is down, say so.
**Paper only.** Remind the user when relevant that fills are simulated and
not investment advice.
## Local API convention
All API calls go through `scripts/_http.py` `Client()` — do not hand-build
curl with a fixed port or read auth material for the user.
- **Base URL & port**: `Client()` reads `state/port` (lifecycle may pick
8000–8010). Do not hardcode `:8000` in user-visible text.
- **Auth**: `Client()` reads `state/token` and sends Bearer automatically.
Never ask the user for this token or mention `PAPER_TRADING_TOKEN`.
- **Stocki quotes** — same v3 API; quote upstream `auth` in `config/main.yaml` selects credentials:
- `bearer`: `STOCKI_GATEWAY_URL` + `STOCKI_API_KEY` (export / SkillHub)
- `none`: `STOCKI_GATEWAY_URL` only (private gateway, auth: none)
Precedence: process env → optional skill-root `.env`. Never paste API keys in chat.
- **Content-Type**: `application/json` for POST bodies.
- **Error envelope**: `{"error": {"code", "message", "recovery_hint", ...}}`.
`_http.py` maps `recovery_hint` — see [Error handling](#error-handling).
## Routing rules
Decide which reference to consult by user intent. Each rule names the
reference file containing the contract, error mapping, and worked examples.
- **R1 — place order.** Triggers: "买", "卖", "buy", "sell", "下单",
"place order", "market buy", "limit sell". → `references/place-order.md`.
Calls `POST /v1/orders` via `scripts/_http.py`.
下单后根据订单类型执行[下单通知流程](#下单通知流程)。
- **R2 — cancel order.** Triggers: "撤单", "取消", "cancel", "撤掉".
→ `references/cancel-order.md`. Calls `DELETE /v1/orders/{order_id}`.
- **R3 — account state.** Triggers: "余额", "持仓", "盈亏", "balance",
"positions", "P&L". → `references/account-state.md`. Calls
`GET /v1/accounts/{id}` and `GET /v1/accounts/{id}/positions`.
- **R4 — order history.** Triggers: "历史订单", "查订单 ord_xxx",
"order history", "list orders". → `references/order-history.md`.
`GET /v1/accounts/{id}/orders`, `GET /v1/orders/{id}`.
- **R5 — fills.** Triggers: "成交", "fills", "成交记录".
→ `references/fill-history.md`. `GET /v1/accounts/{id}/fills`.
- **R6 — market status.** Triggers: "市场", "开盘", "收盘", "market status",
"open?". → `references/market-status.md`. `GET /v1/capabilities` and
`GET /v1/markets/{m}/status`.
- **R7 — service troubleshooting.** Triggers: "起不来", "没响应",
"restart trading", "service status". → `references/troubleshooting.md`.
Calls `python3 scripts/lifecycle.py {start|stop|status|logs}`.
- **R8 — events / reconnect.** Triggers: "重连", "事件", "replay", "events".
→ `references/events.md`. `GET /v1/events?since=<id>`.
- **R9 — symbol metadata / lot-size discipline.** Triggers: "一手", "最小买",
"tick", "T+1 吗", "lot size", "minimum order"; OR any time the user-provided
qty isn't obviously lot-aligned for the market (CN MAIN 100, STAR/CHINEXT
200+, HK varies, US 1); OR after a prior order rejected with
`INVALID_LOT_SIZE` / `INVALID_TICK_SIZE` / `SYMBOL_METADATA_UNAVAILABLE`.
→ `references/symbols.md`. `GET /v1/symbols/{symbol}`. **Round qty
locally** and resubmit; do not surface `INVALID_LOT_SIZE` to the user when
you could round and proceed. Report `original → rounded` if you change it.
### Routing decision rules
Apply when intent is ambiguous. Later rules override earlier ones.
- **Cancel without order_id** → R4 (`status=WORKING`) first, then R2.
- **Sell / sellable qty** → R3 before R1 (`sellable = qty - qty_pending_t1 - qty_locked_sell`).
- **Invalid-looking qty or price** → R9 before R1; round locally when possible.
- **Poll order state** ("filled yet?") → R4, not R1.
- **MARKET rejected** (`NO_ASK_LIQUIDITY` / `NO_BID_LIQUIDITY`) → explain limit lock; suggest LIMIT (R1).
- **Service / connection errors** → R7; run doctor before asking the user to restart.
- **`recovery_hint=reconcile`** → R8, then retry the original action.
## Order notification flow
After placing an order (R1), the agent **must** follow the notification flow
based on order type. This is mandatory for every R1 invocation.
### MARKET order — single-stage notification
1. Call `POST /v1/orders`
2. Check the response `state`:
- **`FILLED`** — immediately notify the user with fill details:
fill price, quantity, fees, order ID
- **`REJECTED`** — immediately notify with the rejection reason and
suggested next step
- Other errors — notify the user about the error
### LIMIT order — two-stage notification
**Stage 1: Order-placed notification (immediate — in conversation)**
This is a direct agent response, **not** a cron notification.
1. Call `POST /v1/orders`
2. Check the response `state`:
- **`WORKING`** → immediately reply to the user in Chinese:
> ✅ 挂单成功
> 订单号:ord_xxx
> 股票:600601.SH(方正科技)
> 方向:买入 | 数量:100 股 | 限价:13.77 元
> 正在等待成交,成交/失败后将自动通知你
- **`FILLED`** (rare, limit crossed immediately) → follow MARKET flow;
fill price is the market ask/bid that crossed, **not** the limit price
- **`REJECTED`** → notify the rejection reason
**Stage 2: State-change monitoring (single global cron job)**
**One cron job manages all orders.** Not one per order.
On the first LIMIT placement that results in `WORKING`, check if a cron job
named `stocki-trading-assistant-order-monitor` already exists (via `cronjob(action='list')`).
If none exists, create a single cron job:
```
cronjob(
action='create',
name='stocki-trading-assistant-order-monitor',
schedule='every 1m',
skills=['stocki-trading-assistant'],
deliver='origin'
)
```
This cron job polls **all** `WORKING` orders. It stores a snapshot of
previous states (e.g. `state/order_snapshot.json`) to detect changes.
Cron job behaviour each tick:
1. Fetch all orders via `GET /v1/accounts/acc_default/orders`
2. Filter to `state=WORKING`
3. Compare against previous snapshot:
- If a previous `WORKING` order is now **gone from the list** (filled,
rejected, or cancelled → check each with `GET /v1/orders/{id}`)
- If a previous `WORKING` order is still `WORKING` → skip (no change)
4. Collect **all state changes** into a list
5. At the end of the tick:
- **Changes found** → send **one** notification in Chinese listing all
changes (e.g. "以下订单状态已更新:\n- ord_xxx:已成交 100 股 @ 13.77\n- ord_yyy:已撤单")
- **No changes** → send nothing (silent)
6. If **zero** `WORKING` orders remain → `cronjob(action='remove')` — stop
the monitor automatically
Key rules:
- **No repeat limit** — runs until all orders resolve
- **No duplicate notification** — `WORKING→WORKING` is silent
- **Multiple changes batched** — one message per tick, not one per order
- **Cron never re-announces "挂单成功"** — that's done in Stage 1
The cron job prompt **must** include:
- stocki-trading-assistant skill path: `/home/agentuser/.hermes/skills/stocki-trading-assistant/`
- Snapshot file path: `state/order_snapshot.json` under the skill root
- Clear instructions: detect state changes, batch notifications, self-remove
when no orders remain
- Produce an **empty response** when no changes detected (silent tick)
## Confirmation discipline
Mutating calls (R1 place-order, R2 cancel-order) require user confirmation
**by default**. Before sending the POST/DELETE, echo a one-line summary
that includes side, quantity, symbol, type, price (if LIMIT), and account:
"即将下单:BUY 100 600519.SH MARKET (account: acc_default),确认?"
Read-only calls (R3–R6, R8, R9) never require confirmation.
### Skipping confirmation
If the user's trade request itself contains any of these phrases, skip
the confirmation for that single call:
"不要确认" "直接下单" "立即买入" "立即卖出"
"skip confirm" "no confirm" "just do it"
Skip is **per-call**, not session-wide. The next trade request without
the phrase requires confirmation again.
## Output discipline
When relaying API results to the user, translate implementation detail into
plain language. Follow the same hygiene as `stocki-financial-reader`.
| Category | Do not show | Show instead |
|----------|-------------|--------------|
| Secrets | `state/token`, Bearer headers, API key values, `.env` contents | nothing, or "local auth is configured" |
| Network | `127.0.0.1`, port numbers, `/v1/health` URLs | "local simulator" / "service unavailable" |
| Storage | SQLite paths, `data/`, `state/`, `logs/` | "records stored on this machine" |
| Config | yaml URL fields, `risk.max_working_orders` | env vars; limits in plain words |
| Errors | `recovery_hint`, raw JSON, HTTP status alone | translated `message` + next step |
| Field names | `qty_pending_t1`, `qty_locked_sell`, `floating_pnl` | sellable qty, T+1 lock, unrealized P&L |
Required: label **simulated** on first balance/trade touch in a session;
distinguish open (`WORKING`) vs filled vs cancelled/rejected/expired;
do not invent P&L when quote is missing; no buy/sell/hold advice.
## Default account
Unless the user specifies an account, all R1–R5 calls target `acc_default`.
Power users may add accounts in `config/accounts.yaml`; in that case ask
the user which account they mean if it is not obvious from context.
## Symbol naming
This skill expects exchange-coded symbols: `600519.SH`, `00700.HK`,
`AAPL.US`. If the user gives a natural-language name ("茅台"), ask for the
exchange code. If another name-resolver skill is installed in the environment,
you may use it once, then continue with the returned code — this skill does
not require any specific reader skill.
## Service lifecycle
The local paper-trading process is auto-started on first `_http.py` call.
The user need not invoke `start` manually. For diagnostics:
python3 {baseDir}/scripts/doctor.py
python3 {baseDir}/scripts/diagnose.py
R7 covers explicit `lifecycle.py start | stop | status | logs`. In normal
chat, report outcomes only — do not ask the user to run lifecycle commands.
### First-run account setup
Before auto-starting for the very first time, check whether accounts have
been configured:
python3 -c "from scripts.init import is_first_run; print(is_first_run())"
If `True`, this is the first run and initial cash has not been set yet.
**Before proceeding**, show the user the defaults and ask for confirmation:
> 即将初始化模拟账户,默认初始资金:
> - CNY(人民币):10,000,000 元
> - HKD(港币):10,000,000 元
> - USD(美元):50,000,000 元
>
> 是否调整?(直接回复"确认"或给出修改后的金额)
Once the user confirms (or provides custom amounts), write accounts.yaml
and then proceed with the normal autostart:
python3 -c "
from pathlib import Path; from scripts.init import write_accounts_yaml
write_accounts_yaml(Path('.'), cny=<CNY>, hkd=<HKD>, usd=<USD>)
"
**Important constraint**: initial cash is a one-time setting. After the
service starts for the first time, accounts are seeded from accounts.yaml
into the local database. Subsequent edits to accounts.yaml have no effect —
changing initial cash after first start requires resetting the simulation,
which permanently deletes all trade history. Warn the user clearly if they ask
to change initial cash after the service has already run. Do not mention
`accounts.yaml` or SQLite in the user dialog — use the prompt above only.
## Error handling
`_http.py` maps trading-assistant error `recovery_hint` (agent-internal —
do not expose hint names to the user):
- **fix_input** — surface translated `message`; ask the user to correct
- **retry** — one retry already attempted; propagate if still failing
- **reconcile** — R8: refresh account + events, then retry
`DUPLICATE_CLIENT_ORDER_ID` returns the existing order — treat as success.
`SERVICE_UNREACHABLE` means autostart already tried; run R7 (doctor /
lifecycle) silently, then tell the user the simulator is temporarily
unreachable and you are fixing it.
## Doctor / diagnose
Run before reporting setup issues:
python3 {baseDir}/scripts/doctor.py
python3 {baseDir}/scripts/diagnose.py
Report exit code 0/1 and the one-line status if failed — do not paste token
or path details from the output.
## Cross-ref
See `INSTALL.md` for install and `.env` setup. See `references/*.md` for
per-endpoint contracts.
don't have the plugin yet? install it then click "run inline in claude" again.