ptb-sdk 0.1.0__py3-none-any.whl

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/__init__.py ADDED
@@ -0,0 +1,48 @@
1
+ """Official Python SDK for the PTB Public API (Bursa Efek Indonesia data & analytics)."""
2
+
3
+ from ._client import DEFAULT_BASE_URL, PTB, AsyncPTB
4
+ from ._endpoints import OPERATIONS
5
+ from ._errors import (
6
+ APIError,
7
+ ConnectionError,
8
+ DataPreparingError,
9
+ InsufficientCreditsError,
10
+ InvalidParamsError,
11
+ NotFoundError,
12
+ PTBError,
13
+ RangeTooLargeError,
14
+ RateLimitedError,
15
+ ServerError,
16
+ SymbolNotFoundError,
17
+ UnauthorizedError,
18
+ )
19
+ from ._response import Billing, RateLimit, Response
20
+ from ._stream import CHANNELS, DEFAULT_STREAM_URL, Stream, StreamError
21
+ from ._version import __version__
22
+
23
+ __all__ = [
24
+ "PTB",
25
+ "AsyncPTB",
26
+ "Stream",
27
+ "StreamError",
28
+ "Response",
29
+ "Billing",
30
+ "RateLimit",
31
+ "OPERATIONS",
32
+ "CHANNELS",
33
+ "DEFAULT_BASE_URL",
34
+ "DEFAULT_STREAM_URL",
35
+ "PTBError",
36
+ "APIError",
37
+ "ConnectionError",
38
+ "InvalidParamsError",
39
+ "RangeTooLargeError",
40
+ "UnauthorizedError",
41
+ "InsufficientCreditsError",
42
+ "NotFoundError",
43
+ "SymbolNotFoundError",
44
+ "RateLimitedError",
45
+ "DataPreparingError",
46
+ "ServerError",
47
+ "__version__",
48
+ ]
ptb_sdk/_client.py ADDED
@@ -0,0 +1,337 @@
1
+ """HTTP transport: auth, retries with backoff, idempotency, billing headers, paging."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import os
7
+ import random
8
+ import time
9
+ import uuid
10
+ from email.utils import parsedate_to_datetime
11
+ from typing import Any, AsyncIterator, Dict, Iterator, Mapping, Optional, Tuple
12
+
13
+ import httpx
14
+
15
+ from . import _errors
16
+ from ._endpoints import _AsyncEndpoints, _Endpoints
17
+ from ._response import Billing, RateLimit, Response
18
+ from ._version import __version__
19
+
20
+ DEFAULT_BASE_URL = "https://api.papertobillion.com/v1"
21
+ RETRY_STATUSES = {202, 429, 500, 502, 503, 504}
22
+
23
+
24
+ def _int(v: Optional[str]) -> Optional[int]:
25
+ try:
26
+ return int(v) if v is not None and v != "" else None
27
+ except ValueError:
28
+ return None
29
+
30
+
31
+ def _retry_after(headers: Mapping[str, str]) -> Optional[float]:
32
+ v = headers.get("retry-after")
33
+ if not v:
34
+ return None
35
+ try:
36
+ return max(0.0, float(v))
37
+ except ValueError:
38
+ try:
39
+ return max(0.0, parsedate_to_datetime(v).timestamp() - time.time())
40
+ except (TypeError, ValueError):
41
+ return None
42
+
43
+
44
+ def _clean(params: Mapping[str, Any]) -> Dict[str, Any]:
45
+ out: Dict[str, Any] = {}
46
+ for k, v in params.items():
47
+ if v is None:
48
+ continue
49
+ if isinstance(v, bool):
50
+ v = "true" if v else "false"
51
+ elif isinstance(v, (list, tuple)):
52
+ v = ",".join(str(x) for x in v)
53
+ out[k] = v
54
+ return out
55
+
56
+
57
+ class _Base:
58
+ def __init__(
59
+ self,
60
+ api_key: Optional[str],
61
+ base_url: Optional[str],
62
+ timeout: float,
63
+ max_retries: int,
64
+ backoff_base: float,
65
+ backoff_max: float,
66
+ user_agent: Optional[str],
67
+ ) -> None:
68
+ key = api_key or os.environ.get("PTB_API_KEY")
69
+ if not key:
70
+ raise _errors.PTBError("API key missing: pass api_key=... or set the PTB_API_KEY environment variable")
71
+ self.api_key = key
72
+ self.base_url = (base_url or os.environ.get("PTB_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
73
+ self.timeout = timeout
74
+ self.max_retries = max_retries
75
+ self.backoff_base = backoff_base
76
+ self.backoff_max = backoff_max
77
+ self.user_agent = user_agent or f"ptb-sdk-python/{__version__}"
78
+
79
+ def _headers(self, method: str, idempotency_key: Optional[str], if_none_match: Optional[str]) -> Dict[str, str]:
80
+ h = {
81
+ "Authorization": f"Bearer {self.api_key}",
82
+ "Accept": "application/json",
83
+ "User-Agent": self.user_agent,
84
+ }
85
+ if method == "POST":
86
+ h["Idempotency-Key"] = idempotency_key or str(uuid.uuid4())
87
+ if if_none_match:
88
+ h["If-None-Match"] = if_none_match
89
+ return h
90
+
91
+ def _delay(self, attempt: int, retry_after: Optional[float]) -> float:
92
+ if retry_after is not None:
93
+ return retry_after # the server knows best; honour Retry-After exactly
94
+ d = min(self.backoff_max, self.backoff_base * (2**attempt))
95
+ return d * (0.5 + random.random() / 2)
96
+
97
+ def _should_retry(self, status: int, attempt: int) -> bool:
98
+ return status in RETRY_STATUSES and attempt < self.max_retries
99
+
100
+ def _parse(self, r: httpx.Response) -> Response[Any]:
101
+ hdr = {k.lower(): v for k, v in r.headers.items()}
102
+ rl = RateLimit(_int(hdr.get("ratelimit-limit")), _int(hdr.get("ratelimit-remaining")), _int(hdr.get("ratelimit-reset")))
103
+ bh = Billing(header_charged=_int(hdr.get("x-ptb-credits-charged")), header_remaining=_int(hdr.get("x-ptb-credits-remaining")))
104
+ rid = hdr.get("x-request-id")
105
+ if r.status_code == 304:
106
+ return Response(
107
+ data=None, billing=bh, rate_limit=rl, request_id=rid, etag=hdr.get("etag"), status=304, not_modified=True, headers=hdr
108
+ )
109
+ ctype = hdr.get("content-type", "")
110
+ body: Any
111
+ if "json" in ctype:
112
+ try:
113
+ body = r.json()
114
+ except ValueError:
115
+ body = r.text
116
+ else:
117
+ body = r.text
118
+ if r.status_code >= 400 or (r.status_code == 202 and isinstance(body, dict) and "error" in body):
119
+ raise _errors.error_from_response(r.status_code, body, rid, _retry_after(hdr))
120
+ if not isinstance(body, dict):
121
+ return Response(data=body, billing=bh, rate_limit=rl, request_id=rid, etag=hdr.get("etag"), status=r.status_code, headers=hdr)
122
+ b = body.get("billing") or {}
123
+ bh.credits_charged = b.get("credits_charged")
124
+ bh.balance_after = b.get("balance_after")
125
+ bh.free = b.get("free")
126
+ bh.rule = b.get("rule")
127
+ return Response(
128
+ data=body.get("data"),
129
+ meta=body.get("meta") or {},
130
+ billing=bh,
131
+ rate_limit=rl,
132
+ request_id=body.get("request_id") or rid,
133
+ etag=hdr.get("etag"),
134
+ status=r.status_code,
135
+ headers=hdr,
136
+ )
137
+
138
+ def _prep(
139
+ self, method: str, path: str, params: Optional[Mapping[str, Any]], idempotency_key: Optional[str], if_none_match: Optional[str]
140
+ ) -> Tuple[str, Dict[str, Any], Dict[str, str]]:
141
+ return self.base_url + path, _clean(params or {}), self._headers(method, idempotency_key, if_none_match)
142
+
143
+
144
+ class SyncTransport(_Base):
145
+ def __init__(self, http: Optional[httpx.Client] = None, **kw: Any) -> None:
146
+ super().__init__(**kw)
147
+ self._http = http or httpx.Client(timeout=self.timeout)
148
+
149
+ def request(
150
+ self,
151
+ method: str,
152
+ path: str,
153
+ params: Optional[Mapping[str, Any]] = None,
154
+ *,
155
+ body: Any = None,
156
+ idempotency_key: Optional[str] = None,
157
+ if_none_match: Optional[str] = None,
158
+ ) -> Response[Any]:
159
+ url, q, h = self._prep(method, path, params, idempotency_key, if_none_match)
160
+ attempt = 0
161
+ while True:
162
+ try:
163
+ r = self._http.request(method, url, params=q, headers=h, json=body)
164
+ except httpx.TransportError as e:
165
+ if attempt < self.max_retries:
166
+ time.sleep(self._delay(attempt, None))
167
+ attempt += 1
168
+ continue
169
+ raise _errors.ConnectionError(str(e)) from e
170
+ if self._should_retry(r.status_code, attempt):
171
+ time.sleep(self._delay(attempt, _retry_after(r.headers)))
172
+ attempt += 1
173
+ continue
174
+ return self._parse(r)
175
+
176
+ def raw(self, method: str, path: str, params: Optional[Mapping[str, Any]] = None) -> httpx.Response:
177
+ url, q, h = self._prep(method, path, params, None, None)
178
+ return self._http.request(method, url, params=q, headers=h)
179
+
180
+ def paginate(self, path: str, params: Mapping[str, Any]) -> Iterator[Any]:
181
+ p = dict(params)
182
+ while True:
183
+ res = self.request("GET", path, p)
184
+ yield from res.data or []
185
+ cur = res.next_cursor
186
+ if not cur:
187
+ return
188
+ p["cursor"] = cur
189
+
190
+ def close(self) -> None:
191
+ self._http.close()
192
+
193
+
194
+ class AsyncTransport(_Base):
195
+ def __init__(self, http: Optional[httpx.AsyncClient] = None, **kw: Any) -> None:
196
+ super().__init__(**kw)
197
+ self._http = http or httpx.AsyncClient(timeout=self.timeout)
198
+
199
+ async def request(
200
+ self,
201
+ method: str,
202
+ path: str,
203
+ params: Optional[Mapping[str, Any]] = None,
204
+ *,
205
+ body: Any = None,
206
+ idempotency_key: Optional[str] = None,
207
+ if_none_match: Optional[str] = None,
208
+ ) -> Response[Any]:
209
+ url, q, h = self._prep(method, path, params, idempotency_key, if_none_match)
210
+ attempt = 0
211
+ while True:
212
+ try:
213
+ r = await self._http.request(method, url, params=q, headers=h, json=body)
214
+ except httpx.TransportError as e:
215
+ if attempt < self.max_retries:
216
+ await asyncio.sleep(self._delay(attempt, None))
217
+ attempt += 1
218
+ continue
219
+ raise _errors.ConnectionError(str(e)) from e
220
+ if self._should_retry(r.status_code, attempt):
221
+ await asyncio.sleep(self._delay(attempt, _retry_after(r.headers)))
222
+ attempt += 1
223
+ continue
224
+ return self._parse(r)
225
+
226
+ async def raw(self, method: str, path: str, params: Optional[Mapping[str, Any]] = None) -> httpx.Response:
227
+ url, q, h = self._prep(method, path, params, None, None)
228
+ return await self._http.request(method, url, params=q, headers=h)
229
+
230
+ async def paginate(self, path: str, params: Mapping[str, Any]) -> AsyncIterator[Any]:
231
+ p = dict(params)
232
+ while True:
233
+ res = await self.request("GET", path, p)
234
+ for row in res.data or []:
235
+ yield row
236
+ cur = res.next_cursor
237
+ if not cur:
238
+ return
239
+ p["cursor"] = cur
240
+
241
+ async def aclose(self) -> None:
242
+ await self._http.aclose()
243
+
244
+
245
+ class PTB(_Endpoints):
246
+ """Synchronous client for the PTB Public API.
247
+
248
+ >>> from ptb_sdk import PTB
249
+ >>> ptb = PTB() # reads PTB_API_KEY
250
+ >>> ptb.stocks.quote("BBCA").data
251
+ """
252
+
253
+ def __init__(
254
+ self,
255
+ api_key: Optional[str] = None,
256
+ *,
257
+ base_url: Optional[str] = None,
258
+ timeout: float = 30.0,
259
+ max_retries: int = 3,
260
+ backoff_base: float = 0.5,
261
+ backoff_max: float = 30.0,
262
+ user_agent: Optional[str] = None,
263
+ http_client: Optional[httpx.Client] = None,
264
+ ) -> None:
265
+ self._transport = SyncTransport(
266
+ http=http_client,
267
+ api_key=api_key,
268
+ base_url=base_url,
269
+ timeout=timeout,
270
+ max_retries=max_retries,
271
+ backoff_base=backoff_base,
272
+ backoff_max=backoff_max,
273
+ user_agent=user_agent,
274
+ )
275
+ self._init_endpoints(self._transport)
276
+
277
+ def request(self, method: str, path: str, params: Optional[Mapping[str, Any]] = None, **kw: Any) -> Response[Any]:
278
+ """Low-level call for any ``/v1`` path (e.g. a newer endpoint not yet in the SDK)."""
279
+ return self._transport.request(method, path, params, **kw)
280
+
281
+ def raw(self, method: str, path: str, params: Optional[Mapping[str, Any]] = None) -> httpx.Response:
282
+ """Unparsed response, e.g. for ``format=csv``. No retries."""
283
+ return self._transport.raw(method, path, params)
284
+
285
+ def close(self) -> None:
286
+ self._transport.close()
287
+
288
+ def __enter__(self) -> PTB:
289
+ return self
290
+
291
+ def __exit__(self, *exc: Any) -> None:
292
+ self.close()
293
+
294
+
295
+ class AsyncPTB(_AsyncEndpoints):
296
+ """Asyncio client for the PTB Public API. Same surface as :class:`PTB`, with ``await``."""
297
+
298
+ def __init__(
299
+ self,
300
+ api_key: Optional[str] = None,
301
+ *,
302
+ base_url: Optional[str] = None,
303
+ timeout: float = 30.0,
304
+ max_retries: int = 3,
305
+ backoff_base: float = 0.5,
306
+ backoff_max: float = 30.0,
307
+ user_agent: Optional[str] = None,
308
+ http_client: Optional[httpx.AsyncClient] = None,
309
+ ) -> None:
310
+ self._transport = AsyncTransport(
311
+ http=http_client,
312
+ api_key=api_key,
313
+ base_url=base_url,
314
+ timeout=timeout,
315
+ max_retries=max_retries,
316
+ backoff_base=backoff_base,
317
+ backoff_max=backoff_max,
318
+ user_agent=user_agent,
319
+ )
320
+ self._init_endpoints(self._transport)
321
+ self.api_key = self._transport.api_key
322
+ self.base_url = self._transport.base_url
323
+
324
+ async def request(self, method: str, path: str, params: Optional[Mapping[str, Any]] = None, **kw: Any) -> Response[Any]:
325
+ return await self._transport.request(method, path, params, **kw)
326
+
327
+ async def raw(self, method: str, path: str, params: Optional[Mapping[str, Any]] = None) -> httpx.Response:
328
+ return await self._transport.raw(method, path, params)
329
+
330
+ async def aclose(self) -> None:
331
+ await self._transport.aclose()
332
+
333
+ async def __aenter__(self) -> AsyncPTB:
334
+ return self
335
+
336
+ async def __aexit__(self, *exc: Any) -> None:
337
+ await self.aclose()