pytossinvest
토스증권 Open API 의 비공식(unofficial) Python SDK. 돈은 절대 float 가 아니고, 레이트리밋·멱등성·토큰 생애주기를 손으로 제대로 다룬 동기(sync) 클라이언트.
⚠️ 비공식 클라이언트 — 토스증권과 무관하며 상표/엔도르스먼트와도 무관합니다. 토스 Open API 는 WTS
설정 > Open API에서 키 발급이 가능하지만, 이 SDK 는 라이브 API 가 아니라 응답 fixture(respxmock) 에 대해 개발·테스트됩니다. 한도·정책 변동 시 일부 동작이 바뀔 수 있습니다.
🤖 AI 에게 계좌를 안전하게 쥐여주는 MCP 서버를 찾는다면 →
pytossinvest-mcp(이 SDK 위에 안전모델을 얹은 패키지).
무엇을 해주나
자동생성 래퍼는 토스 API 의 함정을 안 막아줍니다. 그래서 손으로, 제대로:
| 💸 돈은 절대 float 가 아니다 | 금액·수량 전구간 문자열/Decimal. float 은 들어오는 순간 TypeError — 부동소수 반올림으로 1원도 안 틀어집니다. |
| 🚦 클라이언트단 레이트리미터 | 17개 그룹별 토큰버킷이 요청 속도를 조절. 09:00–09:10 KST 개장 동시호가 10분간 ORDER/ORDER_INFO 반토막(6→3) 반영. |
| 🔁 멱등성 | clientOrderId 로 중복주문 방지 — 네트워크 단절로 응답을 못 받아도 같은 키로 재시도하면 두 번 체결되지 않음(서버측 ~10분 유효). |
🧩 에러는 code 로 분기 |
message 가 비어도 OK. 서버가 모르는 code/enum 을 추가해도 안 깨짐(관용적 파싱). |
| 🔐 토큰 생애주기 | 만료 30초 전까지 메모리 캐싱·자동 갱신(expires_in 이 30초 이하라도 과거 시각으로 뭉개지지 않게 max(0, …) 클램프), 401 expired-token·token-revoked(같은 키로 다른 프로세스가 토큰을 받으면 이전 토큰 무효) 시 1회 재발급 후 재시도. |
| ✅ 라이브 키 없이 그린 | pytest → 155개 테스트 통과(respx mock, 네트워크 0). 기여 장벽 0. |
설치
# PyPI (배포 이름은 pytossinvest-sdk, import 이름은 pytossinvest)
pip install pytossinvest-sdk
pip install "pytossinvest-sdk[ws]" # 실시간 WebSocket 스트림까지
# 소스에서 (uv 워크스페이스 모노레포)
git clone <repo> && cd toss
uv sync --package pytossinvest-sdk --extra dev
요구사항: Python 3.12+. 의존성은 httpx(sync) + pydantic v2 뿐. 실시간 스트림(pytossinvest.stream)만 선택 의존성 websockets([ws] extra).
빠른 시작
from pytossinvest import TossInvestClient
with TossInvestClient(client_id="...", client_secret="...") as c:
# 1) 계좌 — 첫 호출 시 accountSeq 를 자동 캐싱 (ACCOUNT 그룹 1 req/s)
accounts = c.get_accounts()
# 2) 시세 — 계좌 컨텍스트 불필요
prices = c.get_prices(["005930"])
print(prices[0].last_price) # Decimal("70000") — 절대 float 아님
# 3) 주문 — 문자열-decimal + 멱등(clientOrderId 직접 부여)
resp = c.place_order(
symbol="005930", side="BUY", order_type="LIMIT",
price="70000", quantity="10", client_order_id="my-001",
)
print(resp.order_id)
with 블록을 벗어나면 내부 httpx.Client 가 닫힙니다(c.close() 수동 호출도 가능).
돈/수량은 무조건 문자열로 넣고
Decimal로 받습니다.price=70000.0처럼 float 을 넣으면TypeError. 의도된 안전장치입니다.
공개 API 표면
from pytossinvest import ... 로 노출되는 것 전부:
from pytossinvest import (
TossInvestClient,
# 에러 (10종, 전부 TossInvestError 상속)
TossInvestError, AuthError, ForbiddenError, NotFoundError,
ValidationError, ConflictError, BusinessRuleError,
RateLimitError, ServerError, OAuthError,
# 모델
Account, Price, BuyingPower, OrderResponse,
# money 헬퍼
to_decimal, decimal_to_str,
)
Money타입 별칭과HoldingsItem모델은__init__엔 미노출입니다. 필요하면from pytossinvest.models import Money, HoldingsItem.
TossInvestClient
TossInvestClient(
client_id, client_secret, *,
base_url="https://openapi.tossinvest.com",
timeout=10.0,
sleep=time.sleep, # 주입 가능 (레이트리밋 대기) — 테스트 결정성용
monotonic=time.monotonic, # 주입 가능 (토큰버킷·토큰만료)
now_kst=lambda: datetime.now(KST), # 주입 가능 (피크시간 판정)
max_retries=3, # 429 bounded 재시도 횟수 (0 이면 즉시 RateLimitError)
retry_max_wait=60.0, # 재시도 백오프 상한 (초)
rng=random.random, # jitter 주입 — 테스트 결정성용
account_seq=None, # 계좌 지정 (생략 시 get_accounts() 의 첫 계좌)
token_cache=None, # 프로세스 간 토큰 공유 (pytossinvest.auth.TokenCache 구현체)
)
sleep/monotonic/now_kst 주입은 테스트 결정성을 위한 것입니다(가짜 시계로 레이트리밋·피크시간을 제어). max_retries/retry_max_wait/rng 는 429 재시도 동작을 제어합니다. 일반 사용 시엔 신경 쓸 필요 없습니다.
계좌가 둘 이상이면 account_seq 로 주문·잔고 조회에 쓸 계좌를 고르세요(get_accounts() 의 Account.account_seq). 생략하면 첫 계좌를 씁니다.
클라이언트 하나를 여러 스레드가 공유해도 됩니다. 토큰 발급은 락으로 한 번에 묶여 있어, 동시 호출이 서로의 토큰을 revoke 하지 않습니다(토스는 client 당 유효 토큰이 1개). 유휴 연결은 60초까지 재사용합니다.
여러 프로세스가 같은 키를 쓰면 프로세스끼리는 여전히 서로의 토큰을 죽입니다. token_cache 에 pytossinvest.auth.TokenCache(lock·load·save·discard) 구현체를 주면 한 프로세스만 발급하고 나머지는 그 토큰을 씁니다. pytossinvest-mcp 는 redis 백엔드에서 이를 자동으로 씁니다.
메서드
모든 메서드는 내부 _request 오케스트레이션을 거칩니다(레이트게이트 → 인증 → 계좌헤더 → 언래핑 → 401 재시도).
시세 (계좌 컨텍스트 불필요)
| 메서드 | 반환 | 그룹 |
|---|---|---|
get_prices(symbols: list[str]) |
list[Price] |
MARKET_DATA |
get_orderbook(symbol) |
dict |
MARKET_DATA |
get_trades(symbol, count=50) |
list |
MARKET_DATA |
get_candles(symbol, interval, count=100, before=None) |
dict |
MARKET_DATA_CHART |
get_stocks(symbols: list[str]) |
list |
STOCK |
get_exchange_rate(base, quote) |
dict |
MARKET_INFO |
get_market_calendar(country, date=None) |
dict |
MARKET_INFO |
get_all_stocks(market, *, status=None, security_type=None, common_share=None) |
list · 시장 전체 |
STOCK_ALL |
get_investor_trading(symbol, count=10, until=None) · get_program_trades · get_short_selling · get_credit_trades · get_securities_lending |
dict · 국내 수급, 최신순, until=nextUntil 로 과거 |
STOCK_TRADING_TREND |
get_rankings(type, market_country, duration, *, exclude_investment_caution=False, count=100) |
dict |
RANKING |
get_indicator_prices(symbols) |
list · KOSPI·KOSDAQ·국채금리 |
MARKET_INDICATOR |
get_indicator_candles(symbol, interval, count=100, before=None) |
dict |
MARKET_INDICATOR_CHART |
get_index_investor_trading(symbol, interval, count=10, until=None) |
dict · KOSPI·KOSDAQ 투자자별 매매대금 |
MARKET_INDICATOR |
계좌 / 자산 / 주문 (계좌 헤더 X-Tossinvest-Account 자동 부착)
| 메서드 | 반환 | 그룹 |
|---|---|---|
get_accounts() |
list[Account] · 첫 호출 시 accountSeq 캐싱 |
ACCOUNT |
get_holdings(symbol=None) |
dict |
ASSET |
get_buying_power(currency) |
BuyingPower |
ORDER_INFO |
get_sellable_quantity(symbol) |
dict |
ORDER_INFO |
get_commissions() |
list |
ORDER_INFO |
list_orders(status="OPEN", symbol=None, cursor=None, limit=20) |
dict |
ORDER_HISTORY |
get_order(order_id) |
dict |
ORDER_HISTORY |
주문 write (계좌 헤더)
place_order(*, symbol, side, order_type,
quantity=None, price=None, order_amount=None,
time_in_force="DAY", client_order_id=None,
confirm_high_value_order=False) -> OrderResponse
modify_order(order_id, *, order_type,
price=None, quantity=None,
confirm_high_value_order=False) -> dict
cancel_order(order_id) -> dict
조건주문 (계좌 헤더) — 감시가 도달 시 주문이 자동 생성됩니다. first/second 는 API 형태 그대로 {"orderSide", "triggerPrice", "orderPrice"?}(가격은 문자열).
create_conditional_order(*, symbol, type, quantity, order_type, expire_date,
first, second=None, client_order_id=None,
confirm_high_value_order=False) -> dict # type: SINGLE | OCO | OTO
modify_conditional_order(conditional_order_id, *, type, quantity, order_type,
expire_date, first, second=None,
confirm_high_value_order=False) -> dict # 전체 재설정, 새 id 반환
cancel_conditional_order(conditional_order_id) -> None # 204
list_conditional_orders(status="OPEN", symbol=None, cursor=None, limit=20) -> dict
get_conditional_order(conditional_order_id) -> dict
조건주문 목록에는 앱 등 다른 채널에서 만든 조건주문도 섞여 나옵니다.
실시간 스트림 (pip install "pytossinvest-sdk[ws]") — 구독은 선언형이라 subscribe() 한 번이 구독 전체를 바꿉니다([] = 전체 해제). 60초마다 PING keepalive 를 알아서 보냅니다.
import asyncio
from pytossinvest import TossInvestClient
from pytossinvest.stream import TossInvestStream
async def main():
client = TossInvestClient(CLIENT_ID, CLIENT_SECRET)
async with TossInvestStream(client) as stream:
await stream.subscribe([{"type": "trade:kr", "codes": ["005930"]}])
async for frame in stream: # subscriptions / message / error (pong 은 걸러짐)
print(frame)
asyncio.run(main())
personal:order채널의 codes 는str(account.account_seq). 이 채널은 한 연결 안에서만 유실이 없으니 재연결 뒤엔list_orders로 다시 맞추세요.
타입화 설계: 코어 엔드포인트(accounts/prices/buying-power/orders)는 검증된 pydantic 모델을 반환하고, 얇은 엔드포인트(holdings/candles/stocks/orderbook/trades/…)는 언래핑된
result(dict/list)를 그대로 반환합니다. TODO 가 아니라 의도된 절충입니다 — 변동이 잦은 응답은 강타입을 강요하지 않습니다.
핵심 동작
_request 오케스트레이션
- 레이트 게이트 — 해당 그룹 토큰버킷에서 토큰을 얻을 때까지
sleep. 피크시간(09:00–09:10 KST)엔 ORDER/ORDER_INFO 버킷을 반토막(단, 해당 그룹이 응답 헤더를 한 번이라도 받은 뒤엔 피크반토막 미적용). - 인증 —
Authorization: Bearer {token}(TokenManager 가 캐싱·갱신). - 계좌 헤더 —
account=True엔드포인트는X-Tossinvest-Account: {accountSeq}부착.accountSeq가 아직 없으면 첫 호출이 알아서get_accounts()로 첫 계좌를 캐싱합니다(계좌가 없을 때만RuntimeError). 생성자에account_seq를 줬으면 그 값을 쓰고 조회하지 않습니다. - 버킷 동기화 + 언래핑 — 응답을 받으면 (상태코드 무관) 헤더로 버킷 동기화. 이어
200이면resp.json()["result"]를 반환(토큰 엔드포인트 제외),204(조건주문 취소)는None. 바디가 비-JSON·과도하게 중첩된 JSON(RecursionError)이거나, JSON 객체가 아니거나result키가 없으면TossInvestError(invalid-response/missing-result)로 거부 —None을 조용히 순회하다TypeError로 깨지지 않게. - 401 재시도 —
code가expired-token또는token-revoked면 토큰을 무효화하고 재발급 후 재시도, 최대 2회(429 카운터 보존). 토스는 client 당 유효 토큰이 1개라, 같은 키를 쓰는 다른 프로세스가 토큰을 받으면 이쪽 토큰이token-revoked가 됩니다. - 429 bounded 재시도 — 잔여 시도 횟수가 있으면
backoff_wait(Retry-After헤더가 있으면 그 값, 없으면 지수백오프+jitter) 만큼 sleep 후 같은 요청을 재시도.max_retries소진 시RateLimitError던짐. 5xx·타임아웃은 재시도 안 함. - 그 외 비2xx →
code기반 예외로 변환해 raise. 게이트웨이가 준 비표준 본문(JSON 문자열·배열,error가 문자열)이어도 status 에 맞는 예외에code="unknown"으로 올라옵니다.
주문 id·심볼처럼 URL 경로에 들어가는 인자는 경로 구조를 바꿀 수 있으면 요청 전에 ValueError 로 거부합니다: ""·.·.., 그리고 / \ % ? # ;·공백·제어문자가 든 값. 인자를 LLM 이 채우는 환경에서 값 하나가 다른 엔드포인트를 가리키지 못하게 하기 위한 것입니다. 그 밖의 예약 문자는 퍼센트 인코딩합니다.
돈 / Decimal 규약 (money.py)
to_decimal("70000") # Decimal("70000")
to_decimal(70000) # Decimal("70000") — int 허용
to_decimal(70000.0) # TypeError! — float 금지
to_decimal(True) # TypeError! — bool 금지
to_decimal("NaN") # InvalidOperation! — NaN·Infinity 는 파싱 불가 문자열과 같은 취급
decimal_to_str(Decimal("70000.50")) # "70000.50" — 지수표기 방지(format(v,"f"))
Money = Annotated[Decimal, BeforeValidator(to_decimal)] 로 pydantic 모델도 문자열→Decimal 을 강제하고 float 을 거부합니다. 모든 돈/수량은 이 한 경로를 통과합니다.
레이트리밋 (ratelimit.py)
그룹별 기본 TPS(토큰버킷 capacity = refill/sec):
| 그룹 | TPS | 그룹 | TPS |
|---|---|---|---|
MARKET_INDICATOR_CHART |
5 | MARKET_DATA |
10 |
ACCOUNT |
1 | MARKET_DATA_CHART |
5 |
ASSET |
5 | ORDER |
6 |
STOCK |
5 | ORDER_HISTORY |
5 |
MARKET_INFO |
3 | ORDER_INFO |
6 |
CONDITIONAL_ORDER |
5 | CONDITIONAL_ORDER_HISTORY |
10 |
STOCK_ALL |
1 | STOCK_TRADING_TREND |
10 |
RANKING |
5 | MARKET_INDICATOR |
10 |
피크 반토막: PEAK_GROUPS = {ORDER, ORDER_INFO} 는 09:00–09:10 KST 개장 동시호가 동안 TPS 가 절반(6→3)으로 떨어집니다. 단, 서버 응답 헤더(X-RateLimit-*)를 한 번이라도 받은 그룹은 이후 피크반토막 미적용 — 헤더가 진실. 토큰 발급(AUTH)은 버킷을 거치지 않습니다. 말이 안 되는 헤더 값(비유한, Limit<1, 음수)은 무시하고, 버킷 대기는 retry_max_wait 를 넘지 않습니다. 버킷이 요청 속도를 조절(pacing)하며, 서버가 429 를 주면 자동으로 재시도합니다(max_retries=3, 백오프+jitter). 재시도 소진 시 RateLimitError 로 표면화됩니다.
에러 처리 (errors.py)
HTTP status → 예외 클래스 매핑:
| status | 예외 | status | 예외 |
|---|---|---|---|
| 400 | ValidationError |
422 | BusinessRuleError |
| 401 | AuthError |
429 | RateLimitError |
| 403 | ForbiddenError |
≥500 | ServerError |
| 404 | NotFoundError |
그 외 | TossInvestError(base) |
| 409 | ConflictError |
(토큰 EP) | OAuthError |
모든 예외는 .code(항상 문자열, 기본 "unknown"), .message, .http_status, .request_id, .data, .retry_after 를 가집니다. code 로 분기하면 서버가 모르는 코드를 추가해도 안 깨집니다. retry_after 는 429 의 Retry-After 헤더에서만 파싱됩니다.
from pytossinvest import RateLimitError, BusinessRuleError
try:
c.place_order(...)
except RateLimitError as e:
# SDK 가 max_retries 횟수만큼 자동 재시도 후 소진 시 raise — 필요 시 추가 처리
...
except BusinessRuleError as e:
if e.code == "insufficient-buying-power":
...
멱등성
place_order(client_order_id="my-001") — 같은 clientOrderId 로 재시도하면 서버가 중복을 막아 두 번 체결되지 않습니다(서버측 ~10분 유효). clientOrderId 는 자동 생성하지 않으니 호출자가 직접 부여해야 합니다.
재시도할 때는 send_within=<초> 로 전송 시한을 같이 주세요. 그 시간이 지나면 요청을 보내지 않고 SendDeadlineError 를 던집니다. 레이트리밋 대기 때문에 재시도가 10분 뒤에 전송되면 서버는 새 주문으로 받기 때문입니다.
c.place_order(..., client_order_id="my-001", send_within=540) # 지금부터 9분 안에만 보낸다
레이트리밋 / 재시도 동작 (v0.0.2)
X-RateLimit-*헤더 동적 동기화 — 서버 응답마다 해당 그룹 버킷을Limit(capacity)·Reset(1/refill_per_sec)·Remaining(잔여 토큰 상한)으로 업데이트합니다. 헤더가 없으면 no-op. 헤더를 한 번 받은 그룹은 이후 피크반토막 미적용(헤더가 진실).- 429 bounded 자동 retry —
Retry-After헤더가 있으면 그 값만큼, 없으면 지수백오프+full jitter(retry_max_wait상한) 만큼 대기 후 자동 재시도. 기본max_retries=3.max_retries=0이면 즉시RateLimitError. - 5xx·타임아웃은 재시도 안 함 — 재시도 오케스트레이션은 호출자(또는
pytossinvest-mcp레이어) 책임. clientOrderId자동 생성 안 함 — 멱등성을 원하면 직접 부여하세요. 429 재시도 시clientOrderId는 변경되지 않아 멱등성이 유지됩니다.
테스트
uv run --package pytossinvest-sdk --extra dev pytest pytossinvest/tests # 155 passing
respx 로 httpx 를 mock 합니다 — 라이브 키 불필요, 네트워크 0. git clone && uv sync && pytest 면 그린.
라이선스
MIT — 패키지 디렉터리의 LICENSE 참고. (상위 MCP 서버 pytossinvest-mcp 는 Apache-2.0.)
Metadata
Release files for pytossinvest-sdk 0.0.4
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pytossinvest_sdk-0.0.4.tar.gz | 34.1 kB | Without provenance | Details for pytossinvest_sdk-0.0.4.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pytossinvest_sdk-0.0.4-py3-none-any.whl | Python 3 | none | any | Details for pytossinvest_sdk-0.0.4-py3-none-any.whl |
Total release size: 58.2 kB
Release files / pytossinvest_sdk-0.0.4.tar.gz
| Download URL | pytossinvest_sdk-0.0.4.tar.gz |
|---|---|
| Size | 34.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
8e102fedc5e678b17287d25c9cc7a3fd1be3611626a528f87497b5fe00bbedb8
|
|
BLAKE2b-256 checksum How to use checksums |
f6119ae1b54e7a1acf7332d33c6d7d0dd6c2d85b700382852b15cb88ba20d4bf
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / pytossinvest_sdk-0.0.4-py3-none-any.whl
| Download URL | pytossinvest_sdk-0.0.4-py3-none-any.whl |
|---|---|
| Size | 24.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
c352a0e3a29c07e60466d1d263b8fc2462684209146e6ef43be828d3ea64b952
|
|
BLAKE2b-256 checksum How to use checksums |
2fd43c215c9b5fb7a6925b70c948d928e68d523bed2e6d8476aa5a1e7a5cfad5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for pytossinvest-sdk 0.0.4
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.