Skip to main content

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 header header_charged/header_remaining.
  • r.rate_limit: limit, remaining, reset.
  • Kirim if_none_match=r.etag. Kalau data belum berubah, server membalas 304: r.not_modified bernilai True, r.data bernilai None, 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 mengirim Retry-After, SDK menunggu persis selama itu.
  • Setiap POST otomatis membawa Idempotency-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

  • AsyncPTB punya method yang sama dengan PTB, dipanggil dengan await (async for untuk *_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_URL dan PTB_STREAM_URL mengganti 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 /v1 endpoint as a typed method, grouped by path prefix (ptb.stocks.*, ptb.market.*, ptb.indices.*, ...). ptb_sdk.OPERATIONS maps all 71 operations. from is spelled from_.
  • Paging: *_iter methods follow meta.next_cursor (1,000 rows and 1 Kredit per page) with the same filters.
  • Credits: r.billing exposes the billing block and the X-PTB-Credits-Charged/Remaining headers. r.rate_limit exposes the RateLimit-* headers.
  • ETag: pass if_none_match=r.etag. A 304 sets r.not_modified=True, returns data=None, and costs 0 Kredit.
  • Retries: 429, 5xx, 202 data_preparing, and network errors are retried with exponential backoff and jitter. Retry-After is honoured exactly.
  • Idempotency: every POST gets an automatic Idempotency-Key, reused across retries.
  • Typed errors: InvalidParamsError, RangeTooLargeError, UnauthorizedError, InsufficientCreditsError, SymbolNotFoundError, RateLimitedError, DataPreparingError, ServerError, and ConnectionError, all subclasses of PTBError, with code, docs_url, and request_id.
  • WebSocket: Stream supports subscribe/unsubscribe/resume, reconnects automatically, resumes from the last seq per symbol, and pings when idle.
  • Async: AsyncPTB has the same API with await.

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)

Source distribution for ptb-sdk 0.1.0
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)

Table of built distributions (wheels) for ptb-sdk 0.1.0
File Interpreter ABI Platform Actions
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 log

Release 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 log

Security 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.

Select from 2 files

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 log

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.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page