Metadata-Version: 2.5
Name: ptb-sdk
Version: 0.1.0
Summary: Official Python SDK for the PTB Public API: Indonesia Stock Exchange (IDX/BEI) data & analytics, REST + WebSocket
Project-URL: Homepage, https://developers.papertobillion.com
Project-URL: Source, https://github.com/ealfarozi/ptb-sdk-python
Project-URL: Issues, https://github.com/ealfarozi/ptb-sdk-python/issues
Author: PTB (Paper to Billion)
License-Expression: MIT
License-File: LICENSE
Keywords: bei,idx,indonesia,market-data,order-flow,ptb,stock
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: httpx<1,>=0.25
Requires-Dist: typing-extensions>=4.5; python_version < '3.11'
Requires-Dist: websockets<16,>=14
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Description-Content-Type: text/markdown

# 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](#bahasa-indonesia) · [English](#english) · Docs: https://developers.papertobillion.com

> Status: 0.1.0, belum dirilis ke PyPI. / Not yet published to PyPI.

---

## Bahasa Indonesia

### Instalasi

```bash
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.

```bash
export PTB_API_KEY=ptbk_live_...
```

```python
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.

```python
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

```python
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/`](examples).

---

## English

### Install

```bash
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.

```python
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/`](examples).

---

## Development

```bash
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
