PTB SDK for Python
SDK resmi PTB Public API: data & analitik saham Bursa Efek Indonesia (REST + WebSocket). Official Python SDK for the PTB Public API: Indonesia Stock Exchange data & analytics (REST + WebSocket).
Bahasa Indonesia · English · Docs: https://developers.papertobillion.com
Status: 0.1.0, belum dirilis ke PyPI. / Not yet published to PyPI.
Bahasa Indonesia
Instalasi
pip install ptb-sdk
Python 3.9+. Dependensi: httpx, websockets.
Mulai cepat
Buat API key di developers.papertobillion.com → API Keys, lalu simpan di environment. Jangan menulis key di kode.
export PTB_API_KEY=ptbk_live_...
from ptb_sdk import PTB
ptb = PTB() # membaca PTB_API_KEY
q = ptb.stocks.quote("BBCA")
print(q.data["last"])
print(q.billing.credits_charged, q.billing.balance_after) # blok billing
print(q.billing.header_charged, q.billing.header_remaining) # header X-PTB-Credits-*
Key juga bisa diberikan langsung: PTB(api_key=os.environ["KEY_LAIN"]).
Semua endpoint
Setiap endpoint /v1 punya method bertipe, dikelompokkan per awalan path:
| Path | Method |
|---|---|
GET /stocks/{symbol}/trades |
ptb.stocks.trades("BBCA", date=...) |
GET /stocks/{symbol}/brokers/summary |
ptb.stocks.brokers_summary("BBCA", ...) |
GET /market/net-flow |
ptb.market.net_flow(...) |
GET /indices/{code} |
ptb.indices.get("IHSG", interval="1d") |
GET /compare |
ptb.compare(symbols="BBCA,BBRI") |
POST /batch |
ptb.batch({...}) |
Daftar lengkap (71 operasi) ada di ptb_sdk.OPERATIONS. Parameter from ditulis from_. Bentuk data tiap respons punya TypedDict sendiri, jadi editor bisa melengkapi nama kolom.
Paging
Endpoint daftar mengembalikan maksimal 1.000 baris per halaman. Method *_iter mengikuti meta.next_cursor sampai habis dengan filter yang sama. Biayanya 1 Kredit per halaman.
for t in ptb.stocks.trades_iter("BBCA", date="2026-11-26", fields="time,price,lots,side"):
...
Untuk paging manual, kirim cursor=r.next_cursor.
Kredit, ETag, dan 304
r.billing:credits_charged,balance_after,free,rule, serta headerheader_charged/header_remaining.r.rate_limit:limit,remaining,reset.- Kirim
if_none_match=r.etag. Kalau data belum berubah, server membalas 304:r.not_modifiedbernilaiTrue,r.databernilaiNone, dan tidak ada Kredit yang dipotong.
Retry dan idempotency
- Status 429, 5xx, 202 (
data_preparing), dan error jaringan diulang otomatis (max_retries=3) dengan backoff eksponensial + jitter. Kalau server mengirimRetry-After, SDK menunggu persis selama itu. - Setiap
POSTotomatis membawaIdempotency-Key, dan kunci yang sama dipakai ulang di setiap retry sehingga tidak ditagih dobel. Bisa diisi sendiri:ptb.batch(body, idempotency_key="...").
Error
Semua error turunan ptb_sdk.PTBError. Error dari API (APIError) punya status, code, message, docs_url, request_id, dan retry_after.
| Kode | HTTP | Kelas |
|---|---|---|
invalid_params |
400 | InvalidParamsError |
range_too_large |
400 | RangeTooLargeError (turunan InvalidParamsError) |
unauthorized |
401 | UnauthorizedError |
insufficient_credits |
402 | InsufficientCreditsError |
symbol_not_found |
404 | SymbolNotFoundError (turunan NotFoundError) |
rate_limited |
429 | RateLimitedError |
data_preparing |
202 | DataPreparingError |
| 5xx | 5xx | ServerError |
| jaringan | – | ConnectionError |
WebSocket
import asyncio
from ptb_sdk import Stream
async def main():
async with Stream() as s:
await s.subscribe("trades", ["BBCA", "BBRI"])
await s.subscribe("orderflow", ["BBCA"], tf="1m")
async for msg in s:
if msg["type"] == "event":
print(msg["symbol"], msg["seq"], msg["data"])
asyncio.run(main())
Kalau koneksi putus, SDK menyambung ulang dengan backoff, mengirim resume dari seq terakhir per saham, lalu subscribe lagi. ping dikirim saat koneksi diam. Pesan {"type":"error"} (misalnya insufficient_credits) diteruskan ke loop. Pakai raise_errors=True kalau ingin error itu dilempar sebagai StreamError. Channel yang tersedia: trades, orderflow, orderbook, heatmap, bigtrades, bookevents, quote, index, market, picks.
Async dan lain-lain
AsyncPTBpunya method yang sama denganPTB, dipanggil denganawait(async foruntuk*_iter).ptb.raw("GET", "/market/eod", {"format": "csv"})mengembalikan respons mentah, misalnya untuk CSV.ptb.request("GET", "/path-baru")memanggil endpoint yang belum ada di SDK.PTB_BASE_URLdanPTB_STREAM_URLmengganti URL default (berguna untuk mock).
Contoh lengkap ada di examples/.
English
Install
pip install ptb-sdk
Python 3.9+. Depends on httpx and websockets.
Quickstart
Create a key at developers.papertobillion.com → API Keys and keep it in the environment. Never hard-code it.
from ptb_sdk import PTB
ptb = PTB() # reads PTB_API_KEY
q = ptb.stocks.quote("BBCA")
print(q.data["last"], q.billing.credits_charged, q.billing.balance_after)
Features
- Every
/v1endpoint as a typed method, grouped by path prefix (ptb.stocks.*,ptb.market.*,ptb.indices.*, ...).ptb_sdk.OPERATIONSmaps all 71 operations.fromis spelledfrom_. - Paging:
*_itermethods followmeta.next_cursor(1,000 rows and 1 Kredit per page) with the same filters. - Credits:
r.billingexposes thebillingblock and theX-PTB-Credits-Charged/Remainingheaders.r.rate_limitexposes theRateLimit-*headers. - ETag: pass
if_none_match=r.etag. A 304 setsr.not_modified=True, returnsdata=None, and costs 0 Kredit. - Retries: 429, 5xx, 202
data_preparing, and network errors are retried with exponential backoff and jitter.Retry-Afteris honoured exactly. - Idempotency: every
POSTgets an automaticIdempotency-Key, reused across retries. - Typed errors:
InvalidParamsError,RangeTooLargeError,UnauthorizedError,InsufficientCreditsError,SymbolNotFoundError,RateLimitedError,DataPreparingError,ServerError, andConnectionError, all subclasses ofPTBError, withcode,docs_url, andrequest_id. - WebSocket:
Streamsupports subscribe/unsubscribe/resume, reconnects automatically, resumes from the lastseqper symbol, and pings when idle. - Async:
AsyncPTBhas the same API withawait.
See examples/.
Development
python -m venv .venv && .venv/bin/pip install -e '.[dev]'
npx @stoplight/prism-cli@5.14.2 mock -p 4010 spec/openapi.json & # mock server from the contract
PTB_MOCK_URL=http://127.0.0.1:4010 .venv/bin/pytest
.venv/bin/ruff check . && .venv/bin/mypy src
python3 scripts/generate.py --lang python --out src/ptb_sdk/_endpoints.py # after spec/ changes
src/ptb_sdk/_endpoints.py is generated from spec/openapi.json. CI fails if it is out of date.
This SDK is a thin client only. It contains no PTB analytics logic. Market data is information, not investment advice.
License
MIT
Metadata
Release files for ptb-sdk 0.1.0
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 |
|---|---|---|---|---|
| ptb_sdk-0.1.0.tar.gz | 61.9 kB | With provenance | Details for ptb_sdk-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| ptb_sdk-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for ptb_sdk-0.1.0-py3-none-any.whl |
Total release size: 94.9 kB
Release files / ptb_sdk-0.1.0.tar.gz
| Download URL | ptb_sdk-0.1.0.tar.gz |
|---|---|
| Size | 61.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
e71f867784073f6110fd555817a7ef7a16f46101060cfc977bbdc3ae0c98d9d3
|
|
BLAKE2b-256 checksum How to use checksums |
40bc2bb825660bc8db756d8fc30ab73ad2636f426fc27d28f5fb800c3fa19278
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.
Transparency logRelease files / ptb_sdk-0.1.0-py3-none-any.whl
| Download URL | ptb_sdk-0.1.0-py3-none-any.whl |
|---|---|
| Size | 33.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
4014109be57941a61cf3f9a2d48010648b3f842668a8bb4721d04d4c09c7cb1c
|
|
BLAKE2b-256 checksum How to use checksums |
db3dd9c7846644d8ed608184cd2f2bbe68ce0ef896817ca4abf225f21ac5edbe
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.
Transparency logSecurity for ptb-sdk 0.1.0
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.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for ptb_sdk-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.
Transparency logA 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.