内容
<p align="center">
<a href="https://tossinvest-cli.vercel.app/"><img src="docs/assets/hero-banner-v5.png" alt="tossinvest-cli — connect your AI agents to Toss Securities" width="100%" /></a>
</p>
<p align="right"><strong>한국어</strong> · <a href="README.en.md">English</a></p>
<div align="center">
<h1>tossinvest-cli</h1>
<p><strong>토스증권에 연결하는 가장 유연한 방법. CLI 로, MCP 서버로, 어떤 AI 에이전트로든 — 공식 API는 물론 웹앱에만 있던 기능까지 하나로.</strong></p>
<p>Claude Code · Codex · Gemini · Cursor · GitHub Copilot — 어떤 AI 에이전트로든 <code>tossctl</code> 하나로 토스증권 계좌·시세·거래를 다룹니다. <strong>MCP 서버(<code>tossctl mcp</code>)로 붙이거나 터미널에서 직접</strong>, <strong>공식 키 없이 바로 또는 연결 시 자동 라우팅.</strong></p>
<p><sub>수급 · 시장지수 · AI 시그널 · 조건검색 · 관심종목 관리 · 거래내역 ledger · 실시간 푸시 · 원화 소수점 주문 · dry-run preview 등 WTS 전용 기능 21가지 — <strong>공식 Open API 지원 범위도 물론 100% 포함합니다.</strong> <a href="#지원-범위">전체 비교표 ↓</a></sub></p>
<p><sub><em>The most flexible way to connect Toss Securities — via CLI, via MCP, from any AI agent. 100% of the official Open API, plus 21 features only the web app had.</em></sub></p>
</div>
<p align="center">
<a href="LICENSE"><img src="docs/assets/badges/license.svg" height="44" alt="License: MIT" /></a>
<a href="https://go.dev/"><img src="docs/assets/badges/go.svg" height="44" alt="Built with Go 1.25+" /></a>
<img src="docs/assets/badges/agents.svg" height="44" alt="Works with Claude · Codex · Cursor" />
</p>
<p align="center">
<img src="docs/assets/badges/output.svg" height="44" alt="Output: JSON · CSV · SSE" />
<a href="https://tossinvest-cli.vercel.app/docs/guide/hybrid-openapi"><img src="docs/assets/badges/hybrid.svg" height="44" alt="Routing: Official API + WTS" /></a>
</p>
<p align="center">
<a href="#빠른-시작"><strong>빠른 시작</strong></a> ·
<a href="#지원-범위"><strong>지원 범위</strong></a> ·
<a href="#명령-목록"><strong>명령 목록</strong></a> ·
<a href="#faq"><strong>FAQ</strong></a> ·
<a href="#문서"><strong>문서</strong></a> ·
<a href="#후원"><strong>후원</strong></a>
</p>
<p align="center">
<a href="https://github.com/JungHoonGhae/tossinvest-cli/stargazers"><img src="https://img.shields.io/github/stars/JungHoonGhae/tossinvest-cli" alt="GitHub stars" /></a>
<a href="https://github.com/JungHoonGhae/tossinvest-cli"><img src="https://img.shields.io/badge/status-beta-orange.svg" alt="Status Beta" /></a>
<a href="https://github.com/JungHoonGhae/tossinvest-cli/actions/workflows/ci.yml"><img src="https://github.com/JungHoonGhae/tossinvest-cli/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
</p>
> [!WARNING]
> 이 프로젝트는 토스증권 공식 제품이 아닙니다. 공식 Open API 키를 연결하면 해당 기능은 토스가 공식 지원하는 경로로 동작하지만, 그 외 기능은 토스 웹 내부 API를 비공식적으로 사용하며 이는 토스증권 이용약관(TOS) 위반에 해당할 수 있습니다. API는 예고 없이 변경될 수 있고, 사용으로 인한 계좌 제한·손실·기타 불이익에 대해 개발자는 어떠한 책임도 지지 않습니다. 본인의 판단과 책임 하에 사용하세요.
> [!IMPORTANT]
> 거래 기능은 설치 직후 모두 꺼져 있습니다. `config.json`에서 기능별로 직접 허용해야만 실행됩니다.
<div align="center">
<sub><strong>WORKS WITH</strong></sub>
<br /><br />
<img src="docs/assets/logos/claude.svg" height="30" alt="Claude Code" title="Claude Code" />
<picture><source media="(prefers-color-scheme: dark)" srcset="docs/assets/logos/codex.svg" /><img src="docs/assets/logos/codex-light.svg" height="30" alt="Codex" title="Codex" /></picture>
<img src="docs/assets/logos/googlegemini.svg" height="30" alt="Gemini CLI" title="Gemini CLI" />
<picture><source media="(prefers-color-scheme: dark)" srcset="docs/assets/logos/cursor.svg" /><img src="docs/assets/logos/cursor-light.svg" height="30" alt="Cursor" title="Cursor" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="docs/assets/logos/githubcopilot.svg" /><img src="docs/assets/logos/githubcopilot-light.svg" height="30" alt="GitHub Copilot" title="GitHub Copilot" /></picture>
<img src="docs/assets/logos/opencode.svg" height="30" alt="OpenCode" title="OpenCode" />
<img src="docs/assets/logos/qwen.svg" height="30" alt="Qwen Code" title="Qwen Code" />
<img src="docs/assets/logos/deepseek.svg" height="30" alt="DeepSeek" title="DeepSeek" />
<img src="docs/assets/logos/mistralai.svg" height="30" alt="Mistral" title="Mistral" />
<picture><source media="(prefers-color-scheme: dark)" srcset="docs/assets/logos/moonshotai.svg" /><img src="docs/assets/logos/moonshotai-light.svg" height="30" alt="Kimi CLI" title="Kimi CLI" /></picture>
<img src="docs/assets/logos/openclaw.svg" height="30" alt="OpenClaw" title="OpenClaw" />
</div>
---
<p align="center">
<a href="https://www.star-history.com/#JungHoonGhae/tossinvest-cli&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/star-history/star-history-dark.svg" />
<source media="(prefers-color-scheme: light)" srcset="docs/assets/star-history/star-history-light.svg" />
<img alt="Star History Chart" src="docs/assets/star-history/star-history-light.svg" width="600" />
</picture>
</a>
</p>
<p align="center">
<a href="https://www.star-history.com/?repos=JungHoonGhae/tossinvest-cli">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=JungHoonGhae/tossinvest-cli&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/badge?repo=JungHoonGhae/tossinvest-cli" />
<img alt="Star History Rank" src="https://api.star-history.com/badge?repo=JungHoonGhae/tossinvest-cli" />
</picture>
</a>
</p>
## 후원
<p align="center">
<a href="https://github.com/sponsors/JungHoonGhae"><img src="docs/assets/badges/sponsor.svg" height="46" alt="Become a sponsor" /></a>
</p>
<!-- sponsors:start -->
<p align="center">
<a href="https://github.com/sponsors/JungHoonGhae" title="비공개 후원자 / private sponsor"><img src="docs/assets/sponsors/anonymous.svg" width="56" height="56" alt="private sponsor" /></a>
</p>
<p align="center"><sub>현재 <strong>1</strong>분이 제 오픈소스 작업을 후원하고 있습니다 (일회성 포함). 후원은 tossinvest-cli 를 포함한 제 작업 전반에 쓰입니다.</sub></p>
<!-- sponsors:end -->
## 빠른 시작
**어떻게 쓸지에 따라 고르세요.**
- **AI 에이전트(Claude·Codex·Cursor…)로 쓴다** → **MCP 가 가장 간단합니다.** 한 번 등록하면
(`claude mcp add tossctl tossctl mcp`) 에이전트가 자연어로 알아서 다룹니다. → [MCP 빠른 시작](#mcp-빠른-시작--3단계)
- **터미널·스크립트·자동화, 또는 전 기능(관심종목 등 WTS 쓰기·실시간 포함)** → **CLI.** 아래에서
바로 시작하세요. ↓
둘 다 로그인 한 번이면 되고, 같은 `tossctl` 을 씁니다. 자세한 차이는 [CLI 와 MCP — 언제 무엇을](#cli-와-mcp--언제-무엇을-상호-보완).
### 에이전트용
```text
Install tossinvest-cli:
curl -fsSL https://raw.githubusercontent.com/JungHoonGhae/tossinvest-cli/main/install.sh | sh
(macOS/Linux) or GitHub Releases (Windows).
Run `tossctl doctor` to verify setup, then complete browser login with
`tossctl auth login`. Use read-only commands first (account, portfolio, quote).
Trading actions stay disabled until config.json explicitly allows them.
Always run `tossctl order preview` before any trading mutation.
```
### 사람용
macOS / Linux:
```bash
curl -fsSL https://raw.githubusercontent.com/JungHoonGhae/tossinvest-cli/main/install.sh | sh
```
Windows (PowerShell):
```powershell
irm https://raw.githubusercontent.com/JungHoonGhae/tossinvest-cli/main/install.ps1 | iex
```
설치 확인:
```bash
tossctl version
tossctl doctor
tossctl auth login
tossctl account summary --output json
```
설치 후 새 버전이 나오면 `tossctl update` 로 갱신할 수 있습니다 (Homebrew로 설치했다면 `brew upgrade tossctl-cli` 로 자동 위임됩니다).
> `auth login`에는 Google Chrome과 Python이 필요하며, 설치 스크립트가 자동으로 설정합니다.
> Windows, Homebrew, 소스 빌드 등 다른 설치 방법은 [설치](#설치) 섹션을 참고하세요.
>
> QR 스캔 후 폰에 뜨는 **"이 기기 로그인 유지"** 확인 프롬프트까지 꼭 눌러주세요.
> 이 2차 확인을 건너뛰면 세션이 약 1시간 idle 후 만료되어 재로그인이 필요해집니다.
> 정상 캡처 여부는 `tossctl auth status` 의 `Persistence: persistent cookie (expires ...)` 로 확인할 수 있습니다.
> **GUI 없는 환경 (SSH 서버·CI):** `tossctl auth login --headless [--qr-output /tmp/toss-qr.png]`.
> QR URL 과 확인 문자(answerLetter)가 stderr 로 출력되며, URL 을 폰으로 전달해 탭하면 카메라 없이 Toss 앱에서 인증할 수 있습니다. `--qr-output` 파일은 `0600` 권한으로 저장됩니다.
### 세션 연장
토스 서버는 SESSION 쿠키(1년 `Max-Age`)와 별개로 약 7일짜리 활성 만료 시계를 운영합니다. 만료 24시간 전부터 모든 명령에 다음과 같은 stderr 경고가 표시됩니다.
```
⚠ session expires in ~18h; run `tossctl auth extend` to renew
```
`tossctl auth extend` 는 폰의 토스 앱에 푸시를 보내고 승인을 기다립니다.
```
$ tossctl auth extend
Waiting for approval in the Toss app on your phone...
✓ Extension complete. New expiry: 2026-05-13 07:03 KST (took 4s)
```
기본 timeout 은 120초이며 `--timeout 60s` 처럼 단축할 수 있습니다.
## 지원 범위
> **tossctl 은 토스 공식 Open API 의 조회·거래 범위를 100% 커버하고, 그 너머까지 다룹니다.**
> 공식 [Open API 문서](https://developers.tossinvest.com/docs)의 모든 엔드포인트(계좌·잔고·시세·호가·체결·캔들·상하한가·매도가능수량·수수료·주문 등)에 대응하며, 추가로 수급·시장지수·AI 시그널·조건검색·관심종목 관리·거래내역 ledger·실시간 푸시·원화 소수점 주문·dry-run preview 등 **21개가 공식 Open API에 없는 tossctl 고유 범위**입니다.
<p align="center">
<img src="docs/assets/api-comparison.svg" alt="tossctl vs 공식 Open API(예정) 커버리지 비교 — tossctl 이 상위집합" width="840" />
</p>
토스증권 공식 Open API 는 현재 **사전 신청자 대상으로 단계적 롤아웃** 중이며, REST only 의
좁은 범위입니다 (공식 문서: <https://developers.tossinvest.com/docs>). 아래 표의
`공식 API (예정)` 칼럼은 그 문서 기준 공식이 커버하는 범위이고, `tossctl` 칼럼은 우리가
제공하는 범위입니다. **공식 Open API 범위를 100% 커버합니다.**
- ✅ 지원 · ❌ 미지원 · 🔸 부분 지원 · 🆕 최근 한 달 내 새로 추가된 기능
- **`공식 API (예정)` 칼럼 = 공개 문서 기준 예상 커버리지** (사전 신청자 단계적 롤아웃 — 변동 가능).
- **`공식 API (예정)` 가 ❌ 인 행 = tossctl 고유 범위.**
- **검증 기준 버전**: 아래 표·다이어그램의 `공식 API` 칼럼은 **상단 배지에 표시된 공식 Open API 버전** 기준으로 검증된 결과입니다 (그 버전·마지막 점검일은 [`.openapi-snapshot.json`](docs/migration/.openapi-snapshot.json) 에 기록). 전체 spec 사본을 매일 [`docs/migration/openapi.latest.json`](docs/migration/openapi.latest.json) 에 미러링하며, 토스가 spec 을 올리면 자동 감지·알림되어 갱신됩니다.
### 조회 (읽기 전용) · US·KR 공통
| 기능 | 커맨드 | 공식 API (예정) | tossctl |
|------|--------|:--:|:--:|
| 계좌 목록 / 요약 | `account list`, `account summary` | ✅ | ✅ |
| 포트폴리오 | `portfolio positions`, `portfolio allocation` (US: USD 병기) | ✅ | ✅ |
| 체결 내역 (틱) | `quote trades <symbol> --count N` | ✅ | ✅ |
| 호가 (bid/ask 10단계) | `quote orderbook <symbol>` (매도·매수 잔량) | ✅ | ✅ |
| 상/하한가 | `quote limits <symbol>` (KR) | ✅ | ✅ |
| 매수 유의사항 | `quote warnings <symbol>` (정리매매·투자경고·VI 등) | ✅ | ✅ |
| 장 운영 시간 | `market hours` (오늘 + 휴장 시 다음 영업일) | ✅ | ✅ |
| 환율 | `market fx` (달러 환율·달러 인덱스) | ✅ | ✅ |
| 매도가능수량 | `quote sellable <symbol>` (보유 종목 매도가능 주수) | ✅ | ✅ |
| 수수료 / 거래세율 | `quote commission <symbol>` (수수료율·거래세율) | ✅ | ✅ |
| 미체결 / 체결 / 단건 주문 | `orders list`, `orders completed`, `order show <id>` | ✅ | ✅ |
| 시세 | `quote get <symbol>` (OHLC·52주 고저·시총·거래대금·체결강도) | 🔸 *(체결강도·52주 등 제외)* | ✅ |
| 캔들 차트 | `quote chart --interval 1m\|3m\|5m\|10m\|15m\|30m\|60m` | 🔸 *(1분·일봉만)* | ✅ |
| **멀티 시세 / 실시간 갱신** | `quote batch <sym>[,sym,...]` (`--chart`·`--live`) | ❌ | ✅ |
| **수급 (투자자별 순매수)** | `quote flows <symbol>` (개인·외국인·기관, KR) | ❌ | ✅ |
| **시장 지수** | `market index` (코스피·코스닥·나스닥·S&P500·VIX), `market index <코드\|이름>` 상세(OHLC·52주) | ❌ | ✅ |
| **실시간 인기 순위** | `market ranking --size N` | ❌ | ✅ |
| **공식 랭킹(거래대금/등락률)** | `market rankings --type ... --market KR --duration 1d` | ✅ | ✅ |
| **시장 지표 현재가** | `market indicator KOSPI,KOSDAQ` | ✅ | ✅ |
| **시장 지표 캔들** | `market indicator-candles KOSPI --interval 1d` | ✅ | ✅ |
| **시장 투자자별 매매동향** | `market investor-trading KOSPI --interval 1d` | ✅ | ✅ |
| **조건주문 조회** | `order conditional list`, `order conditional get <id>` | ✅ | ✅ |
| **조건주문 거래** | `order conditional place\|cancel\|modify` (안전 게이트: config 허용 + --execute + --confirm) | ✅ | ✅ |
| **🆕 투자자별 순매수 상위** | `market investors` (외국인·기관·개인 순매수 상위) | ❌ | ✅ |
| **🆕 실적(어닝콜) 일정** | `market earnings` (`--major` 주요 기업 큐레이션) | ❌ | ✅ |
| **🆕 배당 내역** | `portfolio dividends` (연간 총액·지역·월별, `--by-payment-date` 세금) | ❌ | ✅ |
| **Prime 구독 상태·혜택** | `account prime` (수수료·이자 3단 비교: 일반/Prime/내 적용) | ❌ | ✅ |
| **🆕 커뮤니티 랭킹** | `community rankings --type influencer\|profit\|followers` | ❌ | ✅ |
| **🆕 업종별 등락** | `market sectors [id]` (대분류·하위 업종, 1일·1개월·1년) | ❌ | ✅ |
| **🆕 테마 등락 랭킹** | `market themes` (오늘 가장 많이 오른 테마, 상승종목 수) | ❌ | ✅ |
| **🆕 개인화 뉴스 브리핑** | `market briefing` (테마별 뉴스 묶음) | ❌ | ✅ |
| **토스 AI 시그널** | `market signals` (종목별 AI 시그널·키워드·등락) | ❌ | ✅ |
| **조건 검색 (스크리너)** | `market screener [id]` (프리셋) · `--filter '<json>'` (커스텀 조건) `--nation kr\|us` | ❌ | ✅ |
| **관심 종목 조회·관리** | `watchlist list`·`groups`, `watchlist group create\|rename\|delete`, `watchlist add\|remove --group <id>` (폴더 CRUD + 종목 추가/제거) | ❌ | ✅ |
| **거래내역 ledger** | `transactions list --market us\|kr` (매매·입출금·배당·입출고) | ❌ | ✅ |
| **현금 overview** | `transactions overview --market us\|kr` (주문가능·출금가능·예정입금) | ❌ | ✅ |
| **CSV 내보내기** | `export positions\|orders --market`, `transactions list --output csv` | ❌ | ✅ |
| **실시간 푸시** | `push listen` (SSE 스트림 — 주문/가격 변경 알림) | ❌ *(공식 API REST only)* | ✅ |
### 거래
공식 API 도 주문 생성·정정·취소·소수점 주문(`orderAmount` 금액 기반 매수, 1.1.5부터 US 시장가 소수점 매도)을 제공합니다. 다만 **원화(KRW) 결제 모드의 소수점 주문·dry-run preview·config 기반 안전 게이트** 등 tossctl 의 거래 UX/안전장치는 우리 고유입니다.
| 기능 | 커맨드 | 필요 config | 공식 API (예정) | tossctl |
|------|--------|-------------|:--:|:--:|
| 지정가 매수 (US/KR) | `order place --side buy --price <value>` | `place` | ✅ | ✅ |
| 지정가 매도 (US/KR) | `order place --side sell --price <value>` | `place` + `sell` | ✅ | ✅ |
| 국내주식 거래 | `order place --market kr` (6자리 코드는 자동 인식) | `place` | ✅ | ✅ |
| 주문 취소 | `order cancel --order-id <id>` | `cancel` | ✅ | ✅ |
| 주문 정정 | `order amend --order-id <id>` | `amend` | ✅ | ✅ |
| 소수점 매수 (US, 금액 기반) | `order place --fractional --amount <value>` (`--currency-mode USD`) | `place` + `fractional` | ✅ | ✅ |
| **소수점 매수 — 원화(KRW) 결제** | `order place --fractional --amount <value>` (기본 KRW) | `place` + `fractional` | ❌ | ✅ |
| **주문 dry-run / preview** | `order preview` (실제 전송 없이 검증) | — | ❌ | ✅ |
모든 거래는 `allow_live_order_actions=true`도 필요합니다. 소수점 주문은 시장가(market order)로 자동 전환되며, 금액 기반입니다 (`--currency-mode KRW` 기본 또는 `USD`).
US 지정가는 `--currency-mode`로 가격 해석을 선택합니다: `KRW` (기본, 서버 환율로 USD 변환) 또는 `USD` (입력을 USD 가격 그대로 전송). 예: `order place --symbol MRVL --side buy --qty 1 --price 158.01 --currency-mode USD`.
### 왜 tossctl 인가 — 공식 API 는 토스 기능의 일부일 뿐
공식 Open API 는 **REST 조회·주문의 기본만** 제공합니다 (약 20개 엔드포인트). 반면
토스 웹앱(WTS)이 실제로 쓰는 **의미있는 조회·거래 기능은 ~440개** — 온보딩·KYC·약관·
프로모션·텔레메트리 같은 무의미한 엔드포인트는 뺀 숫자입니다.
> **공식 Open API 는 그중 약 4%만 커버합니다.** tossctl 은 나머지 범위 위에서 동작하며,
> 공식 Open API에 없는 기능(수급·시장지수·AI 시그널·스크리너·투자자별 순매수·어닝콜·배당 내역·
> 커뮤니티 랭킹·업종별 등락·뉴스 브리핑·실시간 푸시·원화 소수점 주문·dry-run preview 등)을 이미 제공하고,
> **남은 의미있는 범위를 계속 구현해 나갑니다.**
#### 실전 시나리오 — 공식으로 막히는 것, tossctl 로 되는 것
추상적인 "범위가 넓다"가 실제로 무슨 차이인지. **공식만으로는 ❌ → tossctl(WTS 포함)이면 ✅**:
| 하고 싶은 것 | 공식 Open API | tossctl |
|---|:---:|---|
| **특정 종목으로 지금까지 실제 얼마 벌고 잃었나(실현손익)** | ❌ 체결단가 없음 | ✅ `completed_orders` 로 전 기간 매수·매도 체결가 집계 |
| **연도별 배당·원천세 내역 → 금융소득종합과세 대상 판단** | ❌ | ✅ `dividends` (세전/세후·월별) |
| **해외주식 양도세·양도차손 통산 신고자료** | ❌ | ✅ `transactions` + `completed_orders` 로 원장 구성 |
| **월별 배당 현금흐름(받은 것 + 예정)** | ❌ | ✅ `dividends` monthly |
| **종목별 투자자(개인/외국인/기관) 순매수 흐름** | ❌ 체결량까지만 | ✅ `trading_flows` |
| **코스피·코스닥·VIX 등 지수** | ❌ 개별 종목만 | ✅ `market_indices` / `index_detail` |
| **오늘 외국인·기관이 담은 종목 top** | ❌ | ✅ `investor_rankings` |
| **섹터·테마 등락 스캔(무엇이 움직이나)** | ❌ | ✅ `sectors` / `theme_rankings` |
| **조건검색(고배당·저PBR·성장)** | ❌ | ✅ `screener_presets` |
| **실적발표(어닝콜) 일정** | ❌ | ✅ `earning_calls` / `earnings_major` |
| **총자산·평가손익을 한 화면에** | △ `holdings`+`buying_power` 조합 | ✅ `account_summary` 한 번에 |
| **공식 키 없이 보유·대기주문 조회** | ❌ 키 필요 | ✅ `positions` / `pending_orders` (웹 세션만으로) |
| **커버드콜 ETF 진짜 총수익(배당 − NAV손실)** | ❌ | ✅ `completed_orders` + `dividends` 결합 |
| **매수 후 그 종목에 수급이 어땠나 사후분석** | ❌ | ✅ `completed_orders` + `trading_flows` 결합 |
> 요컨대 공식은 *"아는 종목을 정밀 조회하고 주문을 넣는다"* 까지. tossctl 은 여기에 **내 계좌의 실현손익·배당·세금 복기 + 시장 수급·지수 맥락 + 발굴·스크리닝**을 더해, 단순 조회/거래 도구를 **세무·수급·리서치가 붙은 종합 분석 도구**로 확장합니다. 전체 매핑은 [자동 라우팅 가이드 ↗](https://tossinvest-cli.vercel.app/docs/guide/hybrid-openapi) 참고.
장기적으로 tossctl 이 더 나은 이유:
- **유연성 — 토스증권에 연결하는 방법이 가장 열려 있습니다.** 터미널 CLI 로, [MCP 서버](#mcp-서버-tossctl-mcp)로 어떤 AI 에이전트(Claude Code·Codex·Gemini·Cursor·Copilot)에든, 스크립트로 — 전부 **하나의 `tossctl`** 이 처리합니다. **공식 키 없이 바로 시작**하고, 연결하면 공식 경로로 **자동 라우팅**. 특정 앱·SDK·언어·에이전트에 묶이지 않습니다.
- **범위** — 공식 Open API는 좁은 영역을 단계적으로 천천히 엽니다. tossctl 은 웹 전체(아래 카탈로그)를 추적해 골라 구현하므로 항상 더 넓습니다.
- **속도** — 새 기능은 어느 플랫폼이든 자사 앱에서 가장 빠르게 통합되므로 늘 웹앱(WTS)에 먼저 실리고, 외부 공개용 API 는 안정적인 범위만 뒤따라 엽니다(누구의 잘못이 아니라 구조적으로 자연스러운 일). tossctl 은 주간 모니터로 신규 엔드포인트를 잡아 **공식 Open API 출시를 기다리지 않고 먼저 구현**합니다. [왜 공식 API가 늦는지 ↗](https://tossinvest-cli.vercel.app/docs/guide/hybrid-openapi)
- **상위호환** — 공식 Open API가 커버하는 범위는 [이미 100% 지원](#지원-범위)합니다 (공식 Open API가 따라와도 우리가 앞섭니다).
- **안정성(복원력)** — 공식 Open API 는 엔드포인트 그룹별 초당 1~10회로 제한됩니다(계좌 조회가 **초당 1회**로 가장 빡빡). 빠르게 반복하면 10번 중 8번이 막혀요(실측 3개 시점). tossctl 은 막히면 **곧바로 웹 세션으로 우회**해 데이터를 가져오므로 사용자는 막힌 줄도 모르고 항상 성공합니다 — 자동매매·대시보드처럼 계속 불러야 할 때 차이가 큽니다. (한도 숫자는 토스 정책에 따라 바뀔 수 있어도 '막히면 우회'하는 구조는 그대로.) [공식 한도 표 + 실측 ↗](docs/migration/open-api.md#rate-limit-실측)
#### WTS 网页 API 目录(持续追踪)
网页包中提取所有 `/api/*` 端点,并分类为 **已实现 / 下一步候选 / 故意排除**,新增、变更、删除的端点每周由监控器检测。(徽章数字以 **非无意义端点** 为基准,自动从目录中更新)
<p align="center">
<a href="docs/reverse-engineering/wts-endpoints.json"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fraw.githubusercontent.com%2FJungHoonGhae%2Ftossinvest-cli%2Fmain%2Fdocs%2Freverse-engineering%2Fwts-endpoints.json&query=%24.counts.meaningful&label=WTS%20meaningful%20API&suffix=%20endpoints&color=3182F6" alt="WTS meaningful API" /></a>
<a href="docs/reverse-engineering/wts-endpoints.json"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fraw.githubusercontent.com%2FJungHoonGhae%2Ftossinvest-cli%2Fmain%2Fdocs%2Freverse-engineering%2Fwts-endpoints.json&query=%24.counts.implemented&label=implemented&color=success" alt="implemented" /></a>
<a href="docs/reverse-engineering/wts-endpoints.json"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fraw.githubusercontent.com%2FJungHoonGhae%2Ftossinvest-cli%2Fmain%2Fdocs%2Freverse-engineering%2Fwts-endpoints.json&query=%24.counts.candidate_next&label=next%20candidates&color=orange" alt="next candidates" /></a>
<img src="https://img.shields.io/badge/official%20Open%20API-~4%25%20of%20WTS-lightgrey" alt="official API coverage of WTS" />
</p>
- **分类** (完整目录:[`docs/reverse-engineering/wts-endpoints.json`](docs/reverse-engineering/wts-endpoints.json)):
- `implemented` — tossctl 已经提供(对应每个 tossctl 命令)
- `candidate` / `priority: next` — 尚未实现,其中 **下一步添加的高价值候选** 单独标记(例如:虚拟资产行情、实时图表、行业内股票排名、AI 信号详情)
- `excluded` — 故意排除(账户开设·KYC·条款·促销·遥测等范围外,原因记录)
- **持续追踪**:每周重新提取网页包,检测新增/删除/变更的端点(`first_seen` 记录生命周期),变动时提醒 + 自动更新目录。新候选从这里选择并实现。
### 安全模型
交易功能默认全部关闭。一个 live 订单到达 **经纪人** 前,必须通过 **持久化配置门控** 和 **运行时标志门控**。
```mermaid
flowchart TD
A["order place / cancel / amend"] --> P{"action 开关<br/>place·cancel·amend"}
P -->|off| X1["❌ DisabledActionError"]
P -->|on| S{"范围声明<br/>sell·fractional<br/>(对应时)"}
S -->|违规| X2["❌ DisabledActionError"]
S -->|ok| E{"--execute"}
E -->|无| PV["📋 preview 输出<br/>(confirm token 发放)"]
E -->|有| M{"allow_live_order_actions"}
M -->|false| X3["❌ ErrLiveActionsDisabled"]
M -->|true| C{"--confirm token<br/>== preview token?"}
C -->|不匹配| X4["❌ ErrConfirmMismatch"]
C -->|匹配| GO["✅ broker live mutation"]
subgraph CFG["持久化门控 · config.json"]
P
S
M
end
subgraph RT["运行时门控 · CLI 标志"]
E
C
end
```
- **持久化门控(config.json):** `place`/`cancel`/`amend` 路径开关 + `sell`/`fractional` 声明 + `allow_live_order_actions` 主开关。(市场 US/KR 不是门控 — KR 订单比 US 更安全,因此相同处理)
- **运行时门控(每次执行):** `--execute`(非 preview 实际执行) + `--confirm <token>`(preview 收到订单 token)。
- 真正的安全装置是订单 `--confirm <token>` — 只有 preview 才能获得,因此防止意外订单 token 不匹配而被拦截。
> **v0.5.x 简化历史记录:** 曾有的 TTL grant 层 (`internal/permissions`) 被移除(`allow_live_order_actions` 提供相同的保护),虚假名称 `--dangerously-skip-permissions`(现在没有指向的 permissions + 含义反向)被退休。现有标志作为弃用 noop 别名接受一个发布期间,以保持脚本/代理兼容。
## 官方 Open API 自动路由 <!--since:2026-06-27**
`tossctl` 仅需 WTS 网页会话即可运行。选择性连接官方 Open API 密钥后,支持官方 API 的功能将通过官方 API OAuth 路径处理,其余功能仍通过 WTS 网页会话处理,实现 **自动路由**。
> 官方 Open API 与 WTS 网页会话的区别(认证 · 更新 · 覆盖范围 · 稳定性)、IP 自动注册和路由逻辑图可参考 [自动路由指南](https://tossinvest-cli.vercel.app/docs/guide/hybrid-openapi)。
```bash
# 官方密钥申请:https://corp.tossinvest.com/ko/open-api
tossctl init # 引导程序(首次设置时)
tossctl openapi login # 官方密钥注册(支持环境变量)
tossctl openapi status # 密钥 · token · 允许 IP · 路由诊断
tossctl openapi test # 连接验证
tossctl account summary --backend openapi # 强制官方 API 路径(可选)
```
连接后,CI · 服务器 · 代理可无人工干预自动更新 token。
> 官方限额较严格 — 官方文档标准账户查询 **1 次/秒**,快速重复查询可能导致 10 次中 8 次被拒绝 ([官方限额表 + 实测](docs/migration/open-api.md#rate-limit-实测),可能根据政策调整)。`tossctl` 遇到阻塞会自动切换到网页会话(WTS),因此在重复查询 · 监控中不会中断。
### MCP 服务器 (`tossctl mcp`) <!--since:2026-07-08-->
不仅官方 Open API,连 WTS **专属功能** 也通过 **MCP(Model Context Protocol)服务器** 暴露。Claude Code · Claude Desktop · Codex 等 MCP 主机注册后,代理可使用自然语言处理账户 · 余额 · 行情 · 买卖 · 成交 · 蜡烛图(官方)及 **热门排行 · 资金流 · AI 信号 · 筛选器 · 行业 · 盈利 · 财经资讯 · 分红** 等 WTS 专属查询,并支持 **买卖(买入/卖出 · 取消 · 修改)**。
#### MCP 快速开始 — 3 步
MCP 是 `tossctl` 命令的一个模式(`tossctl mcp`),因此 **需先安装 CLI**,然后连接认证(官方密钥 · 网页会话之一),并在主机上注册即可。
```bash
# 1) 安装 tossctl(macOS/Linux — Windows · Homebrew · 源码编译见下方“安装”)
curl -fsSL https://raw.githubusercontent.com/JungHoonGhae/tossinvest-cli/main/install.sh | sh
# 2) 认证 — 有一种即可(没有认证的操作不会激活)
tossctl openapi login # 官方 Open API:官方查询 + 买卖(申请:https://corp.tossinvest.com/ko/open-api)
tossctl auth login # WTS 网页会话:WTS 专属查询(热门排行 · 资金流 · AI 信号等)
# 3) MCP 主机注册 + 连接确认(Claude Code 示例)
claude mcp add tossctl tossctl mcp
claude mcp list # → "tossctl: tossctl mcp - ✔ Connected"
```
Claude Desktop · Codex 等 **JSON 配置方式** 主机,请在配置文件中添加以下设置(`tossctl` 需在 PATH 中):
```json
{
"mcpServers": {
"tossinvest": { "command": "tossctl", "args": ["mcp"] }
}
}
```
#### 为什么 catalog 方式?— 固定 3 个上下文
MCP 的高成本在于 **工具模式必须常驻在模型上下文中**。如果每个 API 都注册一个工具,其名称、描述和参数模式将始终占据对话。`tossctl` API 表面有 **40+ 操作**(官方 16 + 买卖 3 + WTS 专属 20+ + 系统 1,不断增加)— 如果每个操作都暴露为工具,则 **相应的模式将始终存在**,消耗 token,还增加工具选择噪音(类似工具间误判)。
`tossctl` 参考 KIS_MCP_Server 的 catalog 模式,前端仅暴露 **固定的 3 个工具**,其余操作全部 **按需加载模式**:
- `list_operations` — 可用操作列表(id · 简介 · 是否可写)查询,可用 `query` 过滤
- `describe_operation` — 特定操作的 **参数模式仅在当时加载**
- `call_operation` — 通过 id + 参数实际调用
结果:固定上下文 = **仅 3 个工具模式**。操作即使有 40 个或 100 个,其常驻成本固定为 3。代理找到需要的操作后,通过 `list_operations` 查找 → `describe_operation` 读取当时模式 → `call_operation` 调用,因此不会让未使用的操作模式占据上下文。
#### MCP 暴露范围 — 查询官方 + WTS,写官方
MCP 暴露 **查询官方 Open API + WTS 专属功能**,但 **写操作仅官方 API 路径**。
- **查询(read)** — 官方 API(账户 · 行情 · 买卖 · 成交 · 蜡烛图等)和 **WTS 专属功能(热门排行 · 资金流 · AI 信号 · 筛选器 · 行业 · 盈利 · 财经资讯 · 分红等)** 全部暴露。WTS 查询需要网页会话,没有会话会返回 `tossctl auth login` 引导。
- **写操作(write)** — 生成 · 取消 · 修改始终 **仅官方 API 路径**。代理执行买卖时,提交路径必须是 **官方 API** 以确保安全和正直。
#### MCP 主机 JSON 配置
Claude Code 通过一行 `claude mcp add` 完成,而 Claude Desktop · Codex 等 JSON 配置方式主机,请参考以下设置文件(`tossctl` 需在 PATH 中):
```json
{
"mcpServers": {
"tossinvest": { "command": "tossctl", "args": ["mcp"] }
}
}
```
#### CLI 与 MCP — 何时使用
基于同一 `tossctl` 二进制文件,提供两种入口。**两者都适用于 AI 代理。**
| | **CLI** (`tossctl ...`) | **MCP** (`tossctl mcp`) |
|---|---|---|
| 执行方式 | shell 命令 (`tossctl …`) | 结构化 MCP 工具(JSON-RPC,无需 shell) |
| 适用场景 | shell 环境无处不在 — 终端 · 脚本 · cron,以及支持 shell 的 AI 代理(Claude Code · Codex · Cursor…) | **MCP 原生主机** — 代理以工具形式调用操作(catalog 仅 3 个工具,最小化上下文) |
| 代理认知方式 | 需要在提示中提及或通过技能 · `AGENTS.md`/`CLAUDE.md` 注册 | **注册即自动暴露为工具** → 无需额外通知即可调用 |
| 认证 | **仅需网页会话即可** 全部功能(连接官方密钥时自动路由) | 官方查询 · 买卖需官方密钥(`openapi login`),WTS 查询需网页会话(`auth login`)— **至少一种即可** |
| 功能范围 | **全部功能** — 官方 + WTS(查询 · 买卖 · 实时流媒体 · 持仓等) | 查询官方 + WTS,买卖仅官方。实时流媒体 · WTS 写操作不支持 |
| 自然语言支持 | 代理需将自然语言转换为 `tossctl` 命令执行 | 代理直接调用 MCP 工具 |
- **AI 代理两者皆用 — 区别在于认知方式**。MCP 注册后自动暴露为工具,无需额外通知即可调用(查询官方 + 买卖)。CLI 需要在提示中提及或通过技能 · `AGENTS.md`/`CLAUDE.md` 注册 — 但可执行 **全部功能(实时流媒体 + WTS 写操作)**,且基于 **确定性 · 可管道化**。
- **脚本 · cron · 管道 · 可复制自动化** 更适合 CLI(同一命令 = 相同结果)。
- 查询数据 · 买卖安全门控相同:配置 opt-in + dry-run preview + `execute`/`confirm` token。
> **建议自主代理仅使用查询功能。** 配置中关闭 `trading.*` 时,MCP 仅支持查询,买卖操作调用会被门控拦截。交易功能需人为显式开启配置,且每次提交需 `execute:true` + 有效 `confirm` token。
## 配置
```bash
tossctl config init
tossctl config show
```
```json
{
"$schema": "https://raw.githubusercontent.com/JungHoonGhae/tossinvest-cli/main/schemas/config.schema.json",
"schema_version": 3,
"trading": {
"place": false,
"sell": false,
"fractional": false,
"cancel": false,
"amend": false,
"allow_live_order_actions": false,
"dangerous_automation": {
"accept_fx_consent": false
}
},
"update_check": {
"enabled": true
}
}
```
| 字段 | 描述 |
|------|------|
| `place` | 允许 `order place` 路径 |
| `cancel` | 允许 `order cancel` 路径 |
| `amend` | 允许 `order amend` 路径 |
| `conditional` | 允许 `order conditional place/cancel/modify` 路径(官方 Open API,同时需 `allow_live_order_actions`) |
| `sell` | 允许卖出订单(需 `place`)— **范围声明**:用户可自行限制范围 |
| `fractional` | 允许小数点订单(需 `place`,仅 US 市场价)— **范围声明** |
| `allow_live_order_actions` | 主开关 — 上述 `place/cancel/amend` 任一需实际到达经纪人,需此值也为 `true` |
| `accept_fx_consent` | 自动进行 post-prepare FX 确认 |
| `update_check.enabled` | 新版本通知(24 小时缓存,GitHub Releases API,失败时静默)。默认为 `true`。JSON/CSV 输出 · 非 tty · 开发构建时自动跳过 |
> **两种类型的开关:**
> - **路径门控** (`place`, `cancel`, `amend`) — 经纪人 API 分支实际不同操作
> - **范围声明** (`sell`, `fractional`) — 用户自行声明“我不进行该类订单”以防止错误/代理误操作
`v0.4.3` 版本中,`trading.grant`、`dangerous_automation.complete_trade_auth` 和 `dangerous_automation.accept_product_ack` 被移除;`v0.5.2` 版本中,`trading.kr`(非对称市场门控 — KR 订单不比 US 更危险,因此移除)被移除。剩余旧配置将自动忽略,通用命令执行时会在 stderr 中以警告(24 小时退避)提示,`config status`/`doctor` 也会显示。
## 订单示例
### 指定价买入(US)
```bash
tossctl config init
# config.json: place, allow_live_order_actions → true
tossctl order preview \
--symbol TSLL --side buy --qty 1 --price 18000 --output json
tossctl order place \
--symbol TSLL --side buy --qty 1 --price 18000 \
--execute --confirm <token> \
--output json
```
### 小数点买入(US,金额为基准)
```bash
# config.json: place, fractional, allow_live_order_actions → true
tossctl order preview \
--symbol TSLL --side buy --fractional --amount 1000 --qty 0 --output json
tossctl order place \
--symbol TSLL --side buy --fractional --amount 1000 --qty 0 \
--execute --confirm <token> \
--output json
```
### 国内股票买入
```bash
# config.json: place, kr, allow_live_order_actions → true
tossctl order place \
--symbol 005930 --market kr --side buy --qty 1 --price 200000 \
--execute --confirm <token>
```
### 卖出
```bash
# config.json: sell → true(需添加)
tossctl order place \
--symbol TSLL --side sell --qty 1 --price 18000 \
--execute --confirm <token>
```
### 多品种行情
```bash
tossctl quote batch TSLL 005930 GOOG VOO --output table
```
## 本项目不做的事
| 不做的事 | 描述 |
|---|---|
| 官方 API SDK | 不是官方 API 或官方支持 SDK 的项目。官方 Open API ([申请页面](https://corp.tossinvest.com/ko/open-api)) 发布后的迁移计划见 [`docs/migration/open-api.md`](docs/migration/open-api.md)。 |
| 通用交易客户端 | 不支持所有订单类型和市场。 |
| 无限制自动交易 | 不旨在成为无安全措施的自动交易工具。 |
## 安装
<details>
<summary>Homebrew, Windows, 源码编译等其他安装方式</summary>
### Homebrew (macOS)
```bash
brew tap JungHoonGhae/tossinvest-cli
brew install tossctl
```
### Windows (PowerShell)
```powershell
irm https://raw.githubusercontent.com/JungHoonGhae/tossinvest-cli/main/install.ps1 | iex
```
脚本会安装到 `%LOCALAPPDATA%\tossctl`,并自动添加到用户 PATH 中。打开新终端后即可使用 `tossctl` 命令。
如果需要手动安装,可从 [Releases](https://github.com/JungHoonGhae/tossinvest-cli/releases/latest) 下载 `tossctl-windows-amd64.zip`。
### 源码编译
```bash
git clone https://github.com/JungHoonGhae/tossinvest-cli.git
cd tossinvest-cli
make build
cd auth-helper
python3 -m pip install -e .
```
</details>
## 命令列表
### 查询
```bash
tossctl account list
tossctl account summary
tossctl portfolio positions
tossctl portfolio allocation
tossctl portfolio dividends [--year YYYY] [--by-payment-date]
tossctl market investors|earnings|briefing|sectors|themes|index|ranking|signals
tossctl community rankings --type influencer|profit|followers
tossctl orders list
tossctl orders completed --market us|kr|all
tossctl order show <id>
tossctl quote get <symbol>
tossctl quote batch <symbol> [symbol...]
tossctl quote orderbook|sellable|commission <symbol>
tossctl watchlist list
tossctl export positions --market us|kr|all
tossctl export orders --market us|kr|all
```
### 交易
```bash
tossctl order preview --symbol <sym> --side <buy|sell> --qty <n> --price <krw>
tossctl order preview --symbol <sym> --side buy --fractional --amount <krw> --qty 0
tossctl order place ...flags... --execute --confirm <token>
tossctl order cancel --order-id <id> --symbol <sym> ...
tossctl order amend --order-id <id> ...
```
`order cancel` · `order amend` · `order show` 如果不带 `--order-id` 参数,会从待处理/最近订单列表中选择进行操作。`watchlist group delete` · `rename` 也是如此。支持管道 · 非 tty 环境,适用于脚本 · 代理的安全错误返回。投资组合 · 行情等核心输出使用韩式盈亏颜色(上涨/盈利 = 红色,下跌/损失 = 蓝色),在管道 · 非 tty · `NO_COLOR` · `--output json|csv` 环境下纯文本显示。
### 实时推送
```bash
tossctl push listen # SSE 订阅,JSONL 输出(Ctrl+C 退出)
tossctl push listen --retry=false # 禁止重连
```
从 Toss 网页的 SSE 通道订阅 `pending-order-refresh` · `purchase-price-refresh` · `share-holdings` · `web-push` 事件,以 JSONL 格式输出。事件分类和后续重查映射见 [`docs/reverse-engineering/push-events.md`](docs/reverse-engineering/push-events.md)。
### 系统
```bash
tossctl version
tossctl doctor
tossctl doctor --report # JSON 诊断包(用于 issue 附件,路径自动脱敏)
tossctl config init
tossctl config show
tossctl auth login
tossctl auth status # 显示会话 + 服务器过期时间(KST)
tossctl auth extend # 通过手机推送确认延长服务器端 ~7 日过期时间
tossctl auth doctor
tossctl auth logout
```
### 官方 Open API
```bash
tossctl init # 引导程序(首次设置时)
tossctl openapi login # 官方密钥注册(环境变量:TOSSCTL_OPENAPI_KEY / TOSSCTL_OPENAPI_SECRET)
tossctl openapi status # 密钥 · token · 允许 IP 诊断
tossctl openapi test # 连接验证
tossctl openapi logout # 退出登录
```
### API 回归监控
```bash
tossctl monitor api # 25 个端点 schema 探测(并行);exit 0 通过,1 失败
tossctl monitor api --quiet # cron 使用
```
在本地机器上使用本地会话检测 16 个只读端点响应 schema 以快速发现 Toss 服务器端变更。[#29](https://github.com/JungHoonGhae/tossinvest-cli/issues/29) 官方示例。退出码仅返回,因此用户在 `|| <command>` 后自行添加通知渠道(Discord / Slack / ntfy / macOS / 邮箱)。合成示例:[`AGENTS.md`](AGENTS.md)。设置指南:[`docs/operations.md`](docs/operations.md)。
## 订单 Ref 更新
`amend` 或 `cancel` 后,经纪人订单 Ref 可能会变化。
- `tossctl order show <old-id>` 通过本地 lineage cache 追踪新 Ref。
- lineage cache: `<config dir>/trading-lineage.json`
- 如果条件相同但已取消的行有多个,可能需要手动确认。
## 开发
```bash
make build
make test
make fmt
make tidy
```
## FAQ
**可以直接下单吗?**
US/KR 指定价买入/卖出,US 小数点买入,当日未成交取消已在生产环境验证通过。`amend` 需要额外验证。所有交易均需在 `config.json` 中相应操作权限后才能执行。
**这是官方 API 吗?**
不是。 这是一个非官方项目,复用 Toss 内部 API。
**为什么需要 Playwright?**
需要浏览器流程来确保登录会话。查询/交易逻辑在 Go CLI 中实现。
**似乎有问题。如何排查?**
运行 `tossctl doctor --report` 并将 JSON 输出粘贴到 GitHub issue 中。包含版本、操作系统、Chrome 版本、会话状态、3 个端点实时响应(200/401/403)、文件权限和临时文件等信息,帮助快速定位问题。主目录路径会自动用 `~` 替换以保护用户信息。
## 文档
- [`docs/architecture.md`](docs/architecture.md)
- [`docs/configuration.md`](docs/configuration.md)
- [`docs/reverse-engineering/`](docs/reverse-engineering/)
- [`docs/trading/`](docs/trading/)
- [`auth-helper/README.md`](auth-helper/README.md)
## 本地存储路径
| 路径 | 描述 |
|------|------|
| `<config dir>/config.json` | 交易设置 |
| `<config dir>/session.json` | 浏览器会话 |
| `<config dir>/trading-lineage.json` | 订单 Ref 跟踪 |
| `<cache dir>/update-check.json` | 版本 · 会话过期 · 配置警告 backoff 缓存 |
支持 `--config-dir`、`--session-file` 标志修改路径。
## 贡献
欢迎反馈。建议 · 问题报告:
- 在 GitHub 上开 [issue](https://github.com/JungHoonGhae/tossinvest-cli/issues) 或 PR
- LinkedIn [@junghoonghae](https://www.linkedin.com/in/junghoonghae)
- 邮箱 [lucas.ghae@remodule.dev](mailto:lucas.ghae@remodule.dev)
## License
MIT
MCP 配置
以下是此 MCP Server 的配置信息,可直接复制到 Cursor 或其他 MCP 客户端中使用。
mcp.json
连接信息
猜你喜欢
暂无推荐服务器