ptb-sdk 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ptb_sdk-0.1.0/.gitignore +11 -0
- ptb_sdk-0.1.0/CHANGELOG.md +8 -0
- ptb_sdk-0.1.0/LICENSE +21 -0
- ptb_sdk-0.1.0/PKG-INFO +211 -0
- ptb_sdk-0.1.0/README.md +181 -0
- ptb_sdk-0.1.0/examples/async_quickstart.py +15 -0
- ptb_sdk-0.1.0/examples/batch.py +15 -0
- ptb_sdk-0.1.0/examples/etag.py +16 -0
- ptb_sdk-0.1.0/examples/paging.py +9 -0
- ptb_sdk-0.1.0/examples/quickstart.py +14 -0
- ptb_sdk-0.1.0/examples/stream.py +18 -0
- ptb_sdk-0.1.0/pyproject.toml +63 -0
- ptb_sdk-0.1.0/scripts/generate.py +628 -0
- ptb_sdk-0.1.0/spec/README.md +2 -0
- ptb_sdk-0.1.0/spec/asyncapi.json +550 -0
- ptb_sdk-0.1.0/spec/openapi.json +12685 -0
- ptb_sdk-0.1.0/src/ptb_sdk/__init__.py +48 -0
- ptb_sdk-0.1.0/src/ptb_sdk/_client.py +337 -0
- ptb_sdk-0.1.0/src/ptb_sdk/_endpoints.py +2252 -0
- ptb_sdk-0.1.0/src/ptb_sdk/_errors.py +121 -0
- ptb_sdk-0.1.0/src/ptb_sdk/_response.py +57 -0
- ptb_sdk-0.1.0/src/ptb_sdk/_stream.py +198 -0
- ptb_sdk-0.1.0/src/ptb_sdk/_version.py +1 -0
- ptb_sdk-0.1.0/src/ptb_sdk/py.typed +0 -0
- ptb_sdk-0.1.0/tests/test_client.py +203 -0
- ptb_sdk-0.1.0/tests/test_contract_mock.py +67 -0
- ptb_sdk-0.1.0/tests/test_stream.py +98 -0
ptb_sdk-0.1.0/.gitignore
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 (unreleased)
|
|
4
|
+
|
|
5
|
+
- First version, generated from the PTB Public API contract (OpenAPI 1.0.0, AsyncAPI 1.0.0).
|
|
6
|
+
- Typed client for all 71 `/v1` operations, cursor paging iterators, retries with backoff honouring `Retry-After`,
|
|
7
|
+
automatic `Idempotency-Key` for POST, billing block and credit headers, typed errors for the error catalog.
|
|
8
|
+
- WebSocket client for `/v1/stream` with subscribe/unsubscribe/resume and automatic reconnect.
|
ptb_sdk-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 PTB (Paper to Billion)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
ptb_sdk-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: ptb-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python SDK for the PTB Public API: Indonesia Stock Exchange (IDX/BEI) data & analytics, REST + WebSocket
|
|
5
|
+
Project-URL: Homepage, https://developers.papertobillion.com
|
|
6
|
+
Project-URL: Source, https://github.com/ealfarozi/ptb-sdk-python
|
|
7
|
+
Project-URL: Issues, https://github.com/ealfarozi/ptb-sdk-python/issues
|
|
8
|
+
Author: PTB (Paper to Billion)
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: bei,idx,indonesia,market-data,order-flow,ptb,stock
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.9
|
|
20
|
+
Requires-Dist: httpx<1,>=0.25
|
|
21
|
+
Requires-Dist: typing-extensions>=4.5; python_version < '3.11'
|
|
22
|
+
Requires-Dist: websockets<16,>=14
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
25
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
26
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
27
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
28
|
+
Requires-Dist: ruff>=0.6; extra == 'dev'
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# PTB SDK for Python
|
|
32
|
+
|
|
33
|
+
SDK resmi **PTB Public API**: data & analitik saham Bursa Efek Indonesia (REST + WebSocket).
|
|
34
|
+
Official Python SDK for the **PTB Public API**: Indonesia Stock Exchange data & analytics (REST + WebSocket).
|
|
35
|
+
|
|
36
|
+
[Bahasa Indonesia](#bahasa-indonesia) · [English](#english) · Docs: https://developers.papertobillion.com
|
|
37
|
+
|
|
38
|
+
> Status: 0.1.0, belum dirilis ke PyPI. / Not yet published to PyPI.
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## Bahasa Indonesia
|
|
43
|
+
|
|
44
|
+
### Instalasi
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install ptb-sdk
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Python 3.9+. Dependensi: `httpx`, `websockets`.
|
|
51
|
+
|
|
52
|
+
### Mulai cepat
|
|
53
|
+
|
|
54
|
+
Buat API key di **developers.papertobillion.com → API Keys**, lalu simpan di environment. Jangan menulis key di kode.
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
export PTB_API_KEY=ptbk_live_...
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
from ptb_sdk import PTB
|
|
62
|
+
|
|
63
|
+
ptb = PTB() # membaca PTB_API_KEY
|
|
64
|
+
q = ptb.stocks.quote("BBCA")
|
|
65
|
+
print(q.data["last"])
|
|
66
|
+
print(q.billing.credits_charged, q.billing.balance_after) # blok billing
|
|
67
|
+
print(q.billing.header_charged, q.billing.header_remaining) # header X-PTB-Credits-*
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Key juga bisa diberikan langsung: `PTB(api_key=os.environ["KEY_LAIN"])`.
|
|
71
|
+
|
|
72
|
+
### Semua endpoint
|
|
73
|
+
|
|
74
|
+
Setiap endpoint `/v1` punya method bertipe, dikelompokkan per awalan path:
|
|
75
|
+
|
|
76
|
+
| Path | Method |
|
|
77
|
+
|---|---|
|
|
78
|
+
| `GET /stocks/{symbol}/trades` | `ptb.stocks.trades("BBCA", date=...)` |
|
|
79
|
+
| `GET /stocks/{symbol}/brokers/summary` | `ptb.stocks.brokers_summary("BBCA", ...)` |
|
|
80
|
+
| `GET /market/net-flow` | `ptb.market.net_flow(...)` |
|
|
81
|
+
| `GET /indices/{code}` | `ptb.indices.get("IHSG", interval="1d")` |
|
|
82
|
+
| `GET /compare` | `ptb.compare(symbols="BBCA,BBRI")` |
|
|
83
|
+
| `POST /batch` | `ptb.batch({...})` |
|
|
84
|
+
|
|
85
|
+
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.
|
|
86
|
+
|
|
87
|
+
### Paging
|
|
88
|
+
|
|
89
|
+
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.
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
for t in ptb.stocks.trades_iter("BBCA", date="2026-11-26", fields="time,price,lots,side"):
|
|
93
|
+
...
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Untuk paging manual, kirim `cursor=r.next_cursor`.
|
|
97
|
+
|
|
98
|
+
### Kredit, ETag, dan 304
|
|
99
|
+
|
|
100
|
+
- `r.billing`: `credits_charged`, `balance_after`, `free`, `rule`, serta header `header_charged`/`header_remaining`.
|
|
101
|
+
- `r.rate_limit`: `limit`, `remaining`, `reset`.
|
|
102
|
+
- 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.
|
|
103
|
+
|
|
104
|
+
### Retry dan idempotency
|
|
105
|
+
|
|
106
|
+
- 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.
|
|
107
|
+
- 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="...")`.
|
|
108
|
+
|
|
109
|
+
### Error
|
|
110
|
+
|
|
111
|
+
Semua error turunan `ptb_sdk.PTBError`. Error dari API (`APIError`) punya `status`, `code`, `message`, `docs_url`, `request_id`, dan `retry_after`.
|
|
112
|
+
|
|
113
|
+
| Kode | HTTP | Kelas |
|
|
114
|
+
|---|---|---|
|
|
115
|
+
| `invalid_params` | 400 | `InvalidParamsError` |
|
|
116
|
+
| `range_too_large` | 400 | `RangeTooLargeError` (turunan `InvalidParamsError`) |
|
|
117
|
+
| `unauthorized` | 401 | `UnauthorizedError` |
|
|
118
|
+
| `insufficient_credits` | 402 | `InsufficientCreditsError` |
|
|
119
|
+
| `symbol_not_found` | 404 | `SymbolNotFoundError` (turunan `NotFoundError`) |
|
|
120
|
+
| `rate_limited` | 429 | `RateLimitedError` |
|
|
121
|
+
| `data_preparing` | 202 | `DataPreparingError` |
|
|
122
|
+
| 5xx | 5xx | `ServerError` |
|
|
123
|
+
| jaringan | – | `ConnectionError` |
|
|
124
|
+
|
|
125
|
+
### WebSocket
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
import asyncio
|
|
129
|
+
from ptb_sdk import Stream
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
async def main():
|
|
133
|
+
async with Stream() as s:
|
|
134
|
+
await s.subscribe("trades", ["BBCA", "BBRI"])
|
|
135
|
+
await s.subscribe("orderflow", ["BBCA"], tf="1m")
|
|
136
|
+
async for msg in s:
|
|
137
|
+
if msg["type"] == "event":
|
|
138
|
+
print(msg["symbol"], msg["seq"], msg["data"])
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
asyncio.run(main())
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
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`.
|
|
145
|
+
|
|
146
|
+
### Async dan lain-lain
|
|
147
|
+
|
|
148
|
+
- `AsyncPTB` punya method yang sama dengan `PTB`, dipanggil dengan `await` (`async for` untuk `*_iter`).
|
|
149
|
+
- `ptb.raw("GET", "/market/eod", {"format": "csv"})` mengembalikan respons mentah, misalnya untuk CSV.
|
|
150
|
+
- `ptb.request("GET", "/path-baru")` memanggil endpoint yang belum ada di SDK.
|
|
151
|
+
- `PTB_BASE_URL` dan `PTB_STREAM_URL` mengganti URL default (berguna untuk mock).
|
|
152
|
+
|
|
153
|
+
Contoh lengkap ada di [`examples/`](examples).
|
|
154
|
+
|
|
155
|
+
---
|
|
156
|
+
|
|
157
|
+
## English
|
|
158
|
+
|
|
159
|
+
### Install
|
|
160
|
+
|
|
161
|
+
```bash
|
|
162
|
+
pip install ptb-sdk
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
Python 3.9+. Depends on `httpx` and `websockets`.
|
|
166
|
+
|
|
167
|
+
### Quickstart
|
|
168
|
+
|
|
169
|
+
Create a key at **developers.papertobillion.com → API Keys** and keep it in the environment. Never hard-code it.
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
from ptb_sdk import PTB
|
|
173
|
+
|
|
174
|
+
ptb = PTB() # reads PTB_API_KEY
|
|
175
|
+
q = ptb.stocks.quote("BBCA")
|
|
176
|
+
print(q.data["last"], q.billing.credits_charged, q.billing.balance_after)
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
### Features
|
|
180
|
+
|
|
181
|
+
- **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_`.
|
|
182
|
+
- **Paging:** `*_iter` methods follow `meta.next_cursor` (1,000 rows and 1 Kredit per page) with the same filters.
|
|
183
|
+
- **Credits:** `r.billing` exposes the `billing` block and the `X-PTB-Credits-Charged/Remaining` headers. `r.rate_limit` exposes the `RateLimit-*` headers.
|
|
184
|
+
- **ETag:** pass `if_none_match=r.etag`. A 304 sets `r.not_modified=True`, returns `data=None`, and costs 0 Kredit.
|
|
185
|
+
- **Retries:** 429, 5xx, 202 `data_preparing`, and network errors are retried with exponential backoff and jitter. `Retry-After` is honoured exactly.
|
|
186
|
+
- **Idempotency:** every `POST` gets an automatic `Idempotency-Key`, reused across retries.
|
|
187
|
+
- **Typed errors:** `InvalidParamsError`, `RangeTooLargeError`, `UnauthorizedError`, `InsufficientCreditsError`, `SymbolNotFoundError`, `RateLimitedError`, `DataPreparingError`, `ServerError`, and `ConnectionError`, all subclasses of `PTBError`, with `code`, `docs_url`, and `request_id`.
|
|
188
|
+
- **WebSocket:** `Stream` supports subscribe/unsubscribe/resume, reconnects automatically, resumes from the last `seq` per symbol, and pings when idle.
|
|
189
|
+
- **Async:** `AsyncPTB` has the same API with `await`.
|
|
190
|
+
|
|
191
|
+
See [`examples/`](examples).
|
|
192
|
+
|
|
193
|
+
---
|
|
194
|
+
|
|
195
|
+
## Development
|
|
196
|
+
|
|
197
|
+
```bash
|
|
198
|
+
python -m venv .venv && .venv/bin/pip install -e '.[dev]'
|
|
199
|
+
npx @stoplight/prism-cli@5.14.2 mock -p 4010 spec/openapi.json & # mock server from the contract
|
|
200
|
+
PTB_MOCK_URL=http://127.0.0.1:4010 .venv/bin/pytest
|
|
201
|
+
.venv/bin/ruff check . && .venv/bin/mypy src
|
|
202
|
+
python3 scripts/generate.py --lang python --out src/ptb_sdk/_endpoints.py # after spec/ changes
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
`src/ptb_sdk/_endpoints.py` is generated from `spec/openapi.json`. CI fails if it is out of date.
|
|
206
|
+
|
|
207
|
+
This SDK is a thin client only. It contains no PTB analytics logic. Market data is information, not investment advice.
|
|
208
|
+
|
|
209
|
+
## License
|
|
210
|
+
|
|
211
|
+
MIT
|
ptb_sdk-0.1.0/README.md
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
# PTB SDK for Python
|
|
2
|
+
|
|
3
|
+
SDK resmi **PTB Public API**: data & analitik saham Bursa Efek Indonesia (REST + WebSocket).
|
|
4
|
+
Official Python SDK for the **PTB Public API**: Indonesia Stock Exchange data & analytics (REST + WebSocket).
|
|
5
|
+
|
|
6
|
+
[Bahasa Indonesia](#bahasa-indonesia) · [English](#english) · Docs: https://developers.papertobillion.com
|
|
7
|
+
|
|
8
|
+
> Status: 0.1.0, belum dirilis ke PyPI. / Not yet published to PyPI.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## Bahasa Indonesia
|
|
13
|
+
|
|
14
|
+
### Instalasi
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install ptb-sdk
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Python 3.9+. Dependensi: `httpx`, `websockets`.
|
|
21
|
+
|
|
22
|
+
### Mulai cepat
|
|
23
|
+
|
|
24
|
+
Buat API key di **developers.papertobillion.com → API Keys**, lalu simpan di environment. Jangan menulis key di kode.
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
export PTB_API_KEY=ptbk_live_...
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from ptb_sdk import PTB
|
|
32
|
+
|
|
33
|
+
ptb = PTB() # membaca PTB_API_KEY
|
|
34
|
+
q = ptb.stocks.quote("BBCA")
|
|
35
|
+
print(q.data["last"])
|
|
36
|
+
print(q.billing.credits_charged, q.billing.balance_after) # blok billing
|
|
37
|
+
print(q.billing.header_charged, q.billing.header_remaining) # header X-PTB-Credits-*
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Key juga bisa diberikan langsung: `PTB(api_key=os.environ["KEY_LAIN"])`.
|
|
41
|
+
|
|
42
|
+
### Semua endpoint
|
|
43
|
+
|
|
44
|
+
Setiap endpoint `/v1` punya method bertipe, dikelompokkan per awalan path:
|
|
45
|
+
|
|
46
|
+
| Path | Method |
|
|
47
|
+
|---|---|
|
|
48
|
+
| `GET /stocks/{symbol}/trades` | `ptb.stocks.trades("BBCA", date=...)` |
|
|
49
|
+
| `GET /stocks/{symbol}/brokers/summary` | `ptb.stocks.brokers_summary("BBCA", ...)` |
|
|
50
|
+
| `GET /market/net-flow` | `ptb.market.net_flow(...)` |
|
|
51
|
+
| `GET /indices/{code}` | `ptb.indices.get("IHSG", interval="1d")` |
|
|
52
|
+
| `GET /compare` | `ptb.compare(symbols="BBCA,BBRI")` |
|
|
53
|
+
| `POST /batch` | `ptb.batch({...})` |
|
|
54
|
+
|
|
55
|
+
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.
|
|
56
|
+
|
|
57
|
+
### Paging
|
|
58
|
+
|
|
59
|
+
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.
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
for t in ptb.stocks.trades_iter("BBCA", date="2026-11-26", fields="time,price,lots,side"):
|
|
63
|
+
...
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Untuk paging manual, kirim `cursor=r.next_cursor`.
|
|
67
|
+
|
|
68
|
+
### Kredit, ETag, dan 304
|
|
69
|
+
|
|
70
|
+
- `r.billing`: `credits_charged`, `balance_after`, `free`, `rule`, serta header `header_charged`/`header_remaining`.
|
|
71
|
+
- `r.rate_limit`: `limit`, `remaining`, `reset`.
|
|
72
|
+
- 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.
|
|
73
|
+
|
|
74
|
+
### Retry dan idempotency
|
|
75
|
+
|
|
76
|
+
- 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.
|
|
77
|
+
- 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="...")`.
|
|
78
|
+
|
|
79
|
+
### Error
|
|
80
|
+
|
|
81
|
+
Semua error turunan `ptb_sdk.PTBError`. Error dari API (`APIError`) punya `status`, `code`, `message`, `docs_url`, `request_id`, dan `retry_after`.
|
|
82
|
+
|
|
83
|
+
| Kode | HTTP | Kelas |
|
|
84
|
+
|---|---|---|
|
|
85
|
+
| `invalid_params` | 400 | `InvalidParamsError` |
|
|
86
|
+
| `range_too_large` | 400 | `RangeTooLargeError` (turunan `InvalidParamsError`) |
|
|
87
|
+
| `unauthorized` | 401 | `UnauthorizedError` |
|
|
88
|
+
| `insufficient_credits` | 402 | `InsufficientCreditsError` |
|
|
89
|
+
| `symbol_not_found` | 404 | `SymbolNotFoundError` (turunan `NotFoundError`) |
|
|
90
|
+
| `rate_limited` | 429 | `RateLimitedError` |
|
|
91
|
+
| `data_preparing` | 202 | `DataPreparingError` |
|
|
92
|
+
| 5xx | 5xx | `ServerError` |
|
|
93
|
+
| jaringan | – | `ConnectionError` |
|
|
94
|
+
|
|
95
|
+
### WebSocket
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
import asyncio
|
|
99
|
+
from ptb_sdk import Stream
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
async def main():
|
|
103
|
+
async with Stream() as s:
|
|
104
|
+
await s.subscribe("trades", ["BBCA", "BBRI"])
|
|
105
|
+
await s.subscribe("orderflow", ["BBCA"], tf="1m")
|
|
106
|
+
async for msg in s:
|
|
107
|
+
if msg["type"] == "event":
|
|
108
|
+
print(msg["symbol"], msg["seq"], msg["data"])
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
asyncio.run(main())
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
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`.
|
|
115
|
+
|
|
116
|
+
### Async dan lain-lain
|
|
117
|
+
|
|
118
|
+
- `AsyncPTB` punya method yang sama dengan `PTB`, dipanggil dengan `await` (`async for` untuk `*_iter`).
|
|
119
|
+
- `ptb.raw("GET", "/market/eod", {"format": "csv"})` mengembalikan respons mentah, misalnya untuk CSV.
|
|
120
|
+
- `ptb.request("GET", "/path-baru")` memanggil endpoint yang belum ada di SDK.
|
|
121
|
+
- `PTB_BASE_URL` dan `PTB_STREAM_URL` mengganti URL default (berguna untuk mock).
|
|
122
|
+
|
|
123
|
+
Contoh lengkap ada di [`examples/`](examples).
|
|
124
|
+
|
|
125
|
+
---
|
|
126
|
+
|
|
127
|
+
## English
|
|
128
|
+
|
|
129
|
+
### Install
|
|
130
|
+
|
|
131
|
+
```bash
|
|
132
|
+
pip install ptb-sdk
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Python 3.9+. Depends on `httpx` and `websockets`.
|
|
136
|
+
|
|
137
|
+
### Quickstart
|
|
138
|
+
|
|
139
|
+
Create a key at **developers.papertobillion.com → API Keys** and keep it in the environment. Never hard-code it.
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
from ptb_sdk import PTB
|
|
143
|
+
|
|
144
|
+
ptb = PTB() # reads PTB_API_KEY
|
|
145
|
+
q = ptb.stocks.quote("BBCA")
|
|
146
|
+
print(q.data["last"], q.billing.credits_charged, q.billing.balance_after)
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
### Features
|
|
150
|
+
|
|
151
|
+
- **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_`.
|
|
152
|
+
- **Paging:** `*_iter` methods follow `meta.next_cursor` (1,000 rows and 1 Kredit per page) with the same filters.
|
|
153
|
+
- **Credits:** `r.billing` exposes the `billing` block and the `X-PTB-Credits-Charged/Remaining` headers. `r.rate_limit` exposes the `RateLimit-*` headers.
|
|
154
|
+
- **ETag:** pass `if_none_match=r.etag`. A 304 sets `r.not_modified=True`, returns `data=None`, and costs 0 Kredit.
|
|
155
|
+
- **Retries:** 429, 5xx, 202 `data_preparing`, and network errors are retried with exponential backoff and jitter. `Retry-After` is honoured exactly.
|
|
156
|
+
- **Idempotency:** every `POST` gets an automatic `Idempotency-Key`, reused across retries.
|
|
157
|
+
- **Typed errors:** `InvalidParamsError`, `RangeTooLargeError`, `UnauthorizedError`, `InsufficientCreditsError`, `SymbolNotFoundError`, `RateLimitedError`, `DataPreparingError`, `ServerError`, and `ConnectionError`, all subclasses of `PTBError`, with `code`, `docs_url`, and `request_id`.
|
|
158
|
+
- **WebSocket:** `Stream` supports subscribe/unsubscribe/resume, reconnects automatically, resumes from the last `seq` per symbol, and pings when idle.
|
|
159
|
+
- **Async:** `AsyncPTB` has the same API with `await`.
|
|
160
|
+
|
|
161
|
+
See [`examples/`](examples).
|
|
162
|
+
|
|
163
|
+
---
|
|
164
|
+
|
|
165
|
+
## Development
|
|
166
|
+
|
|
167
|
+
```bash
|
|
168
|
+
python -m venv .venv && .venv/bin/pip install -e '.[dev]'
|
|
169
|
+
npx @stoplight/prism-cli@5.14.2 mock -p 4010 spec/openapi.json & # mock server from the contract
|
|
170
|
+
PTB_MOCK_URL=http://127.0.0.1:4010 .venv/bin/pytest
|
|
171
|
+
.venv/bin/ruff check . && .venv/bin/mypy src
|
|
172
|
+
python3 scripts/generate.py --lang python --out src/ptb_sdk/_endpoints.py # after spec/ changes
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
`src/ptb_sdk/_endpoints.py` is generated from `spec/openapi.json`. CI fails if it is out of date.
|
|
176
|
+
|
|
177
|
+
This SDK is a thin client only. It contains no PTB analytics logic. Market data is information, not investment advice.
|
|
178
|
+
|
|
179
|
+
## License
|
|
180
|
+
|
|
181
|
+
MIT
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Asyncio client."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
|
|
5
|
+
from ptb_sdk import AsyncPTB
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
async def main() -> None:
|
|
9
|
+
async with AsyncPTB() as ptb:
|
|
10
|
+
quotes = await asyncio.gather(*(ptb.stocks.quote(s) for s in ["BBCA", "BBRI", "TLKM"]))
|
|
11
|
+
for sym, q in zip(["BBCA", "BBRI", "TLKM"], quotes):
|
|
12
|
+
print(sym, q.data and q.data.get("last"))
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
asyncio.run(main())
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Several requests in one call. Idempotency-Key is added automatically (safe to retry)."""
|
|
2
|
+
|
|
3
|
+
from ptb_sdk import PTB
|
|
4
|
+
|
|
5
|
+
ptb = PTB()
|
|
6
|
+
r = ptb.batch(
|
|
7
|
+
{
|
|
8
|
+
"items": [
|
|
9
|
+
{"id": "a", "path": "/stocks/BBCA/brokers/summary", "params": {"date": "2026-11-26"}},
|
|
10
|
+
{"id": "b", "path": "/stocks/BBRI/ohlcv", "params": {"from": "2026-11-01", "to": "2026-11-26"}},
|
|
11
|
+
],
|
|
12
|
+
"max_credits": 50,
|
|
13
|
+
}
|
|
14
|
+
)
|
|
15
|
+
print(r.data["status"] if r.data else None, r.billing.charged)
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Poll market net flow with ETag: unchanged data answers 304 and costs 0 Kredit."""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
|
|
5
|
+
from ptb_sdk import PTB
|
|
6
|
+
|
|
7
|
+
ptb = PTB()
|
|
8
|
+
etag = None
|
|
9
|
+
for _ in range(5):
|
|
10
|
+
r = ptb.market.net_flow(if_none_match=etag)
|
|
11
|
+
if r.not_modified:
|
|
12
|
+
print("unchanged (free)")
|
|
13
|
+
else:
|
|
14
|
+
etag = r.etag
|
|
15
|
+
print("rows:", len(r.data or []), "charged:", r.billing.charged)
|
|
16
|
+
time.sleep(15)
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Iterate every done trade of a finished session (1 Kredit per 1,000-row page)."""
|
|
2
|
+
|
|
3
|
+
from ptb_sdk import PTB
|
|
4
|
+
|
|
5
|
+
ptb = PTB()
|
|
6
|
+
total = 0
|
|
7
|
+
for trade in ptb.stocks.trades_iter("BBCA", date="2026-11-26", fields="time,price,lots,side"):
|
|
8
|
+
total += trade.get("lots") or 0
|
|
9
|
+
print("total lots:", total)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Quickstart: quote, balance and credit usage. Run: PTB_API_KEY=... python examples/quickstart.py"""
|
|
2
|
+
|
|
3
|
+
from ptb_sdk import PTB, InsufficientCreditsError
|
|
4
|
+
|
|
5
|
+
with PTB() as ptb: # reads PTB_API_KEY
|
|
6
|
+
q = ptb.stocks.quote("BBCA")
|
|
7
|
+
print("BBCA last:", q.data["last"] if q.data else None)
|
|
8
|
+
print("charged:", q.billing.charged, "remaining:", q.billing.remaining)
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
eod = ptb.market.eod(date="2026-11-27", fields="code,close,value,foreign_buy,foreign_sell")
|
|
12
|
+
print("rows:", len(eod.data or []))
|
|
13
|
+
except InsufficientCreditsError as e:
|
|
14
|
+
print("top up first:", e.docs_url)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Live trades for several symbols; reconnects and resumes from the last seq automatically."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
|
|
5
|
+
from ptb_sdk import Stream
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
async def main() -> None:
|
|
9
|
+
async with Stream() as s: # reads PTB_API_KEY
|
|
10
|
+
await s.subscribe("trades", ["BBCA", "BBRI"])
|
|
11
|
+
async for msg in s:
|
|
12
|
+
if msg["type"] == "event":
|
|
13
|
+
print(msg["symbol"], msg["seq"], msg["data"])
|
|
14
|
+
elif msg["type"] == "error":
|
|
15
|
+
print("error:", msg)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
asyncio.run(main())
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.24"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ptb-sdk" # PROPOSED NAME - not published until approved
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Official Python SDK for the PTB Public API: Indonesia Stock Exchange (IDX/BEI) data & analytics, REST + WebSocket"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.9"
|
|
13
|
+
authors = [{ name = "PTB (Paper to Billion)" }]
|
|
14
|
+
keywords = ["idx", "bei", "indonesia", "stock", "market-data", "order-flow", "ptb"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Intended Audience :: Financial and Insurance Industry",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Topic :: Office/Business :: Financial :: Investment",
|
|
22
|
+
"Typing :: Typed",
|
|
23
|
+
]
|
|
24
|
+
dependencies = [
|
|
25
|
+
"httpx>=0.25,<1",
|
|
26
|
+
"websockets>=14,<16",
|
|
27
|
+
"typing_extensions>=4.5; python_version<'3.11'",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[project.optional-dependencies]
|
|
31
|
+
dev = ["pytest>=8", "pytest-asyncio>=0.23", "ruff>=0.6", "mypy>=1.10", "build>=1.2"]
|
|
32
|
+
|
|
33
|
+
[project.urls]
|
|
34
|
+
Homepage = "https://developers.papertobillion.com"
|
|
35
|
+
Source = "https://github.com/ealfarozi/ptb-sdk-python"
|
|
36
|
+
Issues = "https://github.com/ealfarozi/ptb-sdk-python/issues"
|
|
37
|
+
|
|
38
|
+
[tool.hatch.version]
|
|
39
|
+
path = "src/ptb_sdk/_version.py"
|
|
40
|
+
|
|
41
|
+
[tool.hatch.build.targets.wheel]
|
|
42
|
+
packages = ["src/ptb_sdk"]
|
|
43
|
+
|
|
44
|
+
[tool.hatch.build.targets.sdist]
|
|
45
|
+
include = ["src", "spec", "scripts", "tests", "examples", "README.md", "LICENSE", "CHANGELOG.md"]
|
|
46
|
+
|
|
47
|
+
[tool.pytest.ini_options]
|
|
48
|
+
asyncio_mode = "auto"
|
|
49
|
+
testpaths = ["tests"]
|
|
50
|
+
|
|
51
|
+
[tool.ruff]
|
|
52
|
+
line-length = 140
|
|
53
|
+
target-version = "py39"
|
|
54
|
+
extend-exclude = ["src/ptb_sdk/_endpoints.py"]
|
|
55
|
+
|
|
56
|
+
[tool.ruff.lint]
|
|
57
|
+
select = ["E", "F", "W", "I", "B", "UP"]
|
|
58
|
+
ignore = ["UP006", "UP007", "UP035", "UP045", "B904", "E501", "E741"]
|
|
59
|
+
|
|
60
|
+
[tool.mypy]
|
|
61
|
+
python_version = "3.9"
|
|
62
|
+
strict = false
|
|
63
|
+
ignore_missing_imports = true
|