polaris-data 0.1.0

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.
@@ -0,0 +1,323 @@
1
+ /** Accepts ISO 8601 strings, `Date` instances, or Unix epoch microseconds. */
2
+ type TimeInput = string | Date | number;
3
+ /** Shape of the global `fetch` function so consumers can inject a custom one. */
4
+ type FetchLike = typeof globalThis.fetch;
5
+ type AuthMode = "none" | "if-available" | "required";
6
+ interface PaginatedResponse<T = Record<string, unknown>> {
7
+ data: T[];
8
+ next_cursor: string | null;
9
+ has_more: boolean;
10
+ }
11
+ interface CatalogResponse {
12
+ sources: CatalogSource[];
13
+ updatedAt: string;
14
+ }
15
+ interface CatalogSource {
16
+ id: string;
17
+ markets: CatalogMarket[];
18
+ }
19
+ interface CatalogMarket {
20
+ id: string;
21
+ start?: string;
22
+ end?: string;
23
+ source?: string;
24
+ categories?: string[];
25
+ access?: {
26
+ status: string;
27
+ public_cutoff_date?: string;
28
+ };
29
+ }
30
+ interface StandardEvent {
31
+ timestamp: number;
32
+ venue: string;
33
+ symbol: string;
34
+ type: string;
35
+ data: Record<string, unknown>;
36
+ }
37
+ interface TradeData {
38
+ price: number;
39
+ quantity: number;
40
+ side: string;
41
+ [key: string]: unknown;
42
+ }
43
+ interface TradeEvent extends StandardEvent {
44
+ type: "trade";
45
+ data: TradeData;
46
+ }
47
+ type OhlcvInterval = "100ms" | "1s" | "10s" | "1m" | "5m" | "15m" | "1h";
48
+ interface OhlcvBar {
49
+ timestamp: number;
50
+ open: number;
51
+ high: number;
52
+ low: number;
53
+ close: number;
54
+ volume: number;
55
+ trades: number;
56
+ }
57
+ interface TradingViewCandle {
58
+ t: number;
59
+ o: number;
60
+ h: number;
61
+ l: number;
62
+ c: number;
63
+ }
64
+ interface TradingViewVolume {
65
+ t: number;
66
+ v: number;
67
+ trades?: number;
68
+ }
69
+ interface TradingViewOhlcvResponse {
70
+ candles: TradingViewCandle[];
71
+ volumes: TradingViewVolume[];
72
+ }
73
+ interface SnapshotEntry {
74
+ date: string;
75
+ key: string;
76
+ filename: string;
77
+ }
78
+ interface SnapshotsResponse {
79
+ source: string;
80
+ market: string;
81
+ access?: {
82
+ status: string;
83
+ public_cutoff_date?: string;
84
+ };
85
+ total: number;
86
+ total_bytes: number;
87
+ limit: number;
88
+ has_more: boolean;
89
+ next_cursor: string | null;
90
+ snapshots: SnapshotEntry[];
91
+ }
92
+ interface DownloadUrlResponse {
93
+ url: string;
94
+ filename?: string;
95
+ expires_in_seconds?: number;
96
+ }
97
+ interface PolarisClientOptions {
98
+ /** Polaris API key. Falls back to `POLARIS_API_KEY` env var. */
99
+ apiKey?: string;
100
+ /** API base URL. Defaults to `https://api.polaris.supply`. */
101
+ baseUrl?: string;
102
+ /** Request timeout in milliseconds. Defaults to `30 000` (30 s). */
103
+ timeout?: number;
104
+ /** Custom fetch implementation (useful for testing or proxies). */
105
+ fetch?: FetchLike;
106
+ /**
107
+ * Override the local dataset root directory.
108
+ * Defaults to the platform-specific Polaris app-data directory,
109
+ * overridable globally via `POLARIS_ROOT` env var.
110
+ */
111
+ datasetRoot?: string;
112
+ }
113
+ interface CatalogOptions {
114
+ source?: string;
115
+ market?: string;
116
+ }
117
+ /** Options for snapshot-based historical data methods. `from` and `to` are required. */
118
+ interface HistoricalQueryOptions {
119
+ source: string;
120
+ market: string;
121
+ from: TimeInput;
122
+ to: TimeInput;
123
+ }
124
+ interface ListSnapshotsOptions {
125
+ source: string;
126
+ market: string;
127
+ from?: TimeInput;
128
+ to?: TimeInput;
129
+ limit?: number;
130
+ }
131
+ /** Options for the /raw endpoint. `from`/`to` are optional (defaults to 24 h lookback). */
132
+ interface RawQueryOptions {
133
+ source: string;
134
+ market: string;
135
+ from?: TimeInput;
136
+ to?: TimeInput;
137
+ limit?: number;
138
+ format?: string;
139
+ }
140
+ interface OhlcvOptions extends HistoricalQueryOptions {
141
+ interval: OhlcvInterval;
142
+ }
143
+ interface ReplayOptions {
144
+ source: string;
145
+ market: string;
146
+ from: TimeInput;
147
+ to: TimeInput;
148
+ /** `true` (default) streams standardised events from local snapshots. */
149
+ standard?: boolean;
150
+ }
151
+ interface DownloadSnapshotOptions {
152
+ key: string;
153
+ filename?: string;
154
+ mode?: "url" | "json";
155
+ }
156
+
157
+ type Json = Record<string, unknown>;
158
+ declare class PolarisClient {
159
+ private readonly _apiKey;
160
+ private readonly _baseUrl;
161
+ private readonly _timeout;
162
+ private readonly _fetch;
163
+ private readonly _root;
164
+ private _layout;
165
+ constructor(options?: PolarisClientOptions);
166
+ /** Check API availability. */
167
+ health(): Promise<Json>;
168
+ /**
169
+ * Browse supported sources and markets.
170
+ *
171
+ * If neither `source` nor `market` is provided, returns the full catalog.
172
+ * `market` requires `source`.
173
+ */
174
+ catalog(options?: CatalogOptions): Promise<CatalogResponse>;
175
+ /**
176
+ * List available snapshot files for a source and market over a time range.
177
+ * Auto-paginates to return **all** matching entries.
178
+ */
179
+ listSnapshots(options: ListSnapshotsOptions): Promise<SnapshotEntry[]>;
180
+ /**
181
+ * Return all standardised historical events for a time range.
182
+ *
183
+ * Reads from locally-cached daily `.jsonl.zst` snapshot files.
184
+ * Missing daily artifacts are discovered via `GET /snapshots` and
185
+ * downloaded automatically.
186
+ */
187
+ events(options: HistoricalQueryOptions): Promise<Json[]>;
188
+ /**
189
+ * Return all standardised trade events for a time range.
190
+ *
191
+ * Reads from locally-cached daily snapshot files, filtering to
192
+ * `type === "trade"`.
193
+ */
194
+ trades(options: HistoricalQueryOptions): Promise<Json[]>;
195
+ /**
196
+ * Aggregate OHLCV bars from standardised trade data.
197
+ *
198
+ * Reads from locally-cached daily snapshot files and aggregates in memory
199
+ * using the same interval-bucketing strategy as the Python SDK.
200
+ */
201
+ ohlcv(options: OhlcvOptions): Promise<OhlcvBar[]>;
202
+ /**
203
+ * Return a TradingView-shaped OHLCV response.
204
+ *
205
+ * Aggregates bars from local snapshot data and reshapes to
206
+ * `{ candles, volumes }`.
207
+ */
208
+ ohlcvTradingView(options: OhlcvOptions): Promise<TradingViewOhlcvResponse>;
209
+ /**
210
+ * Stream historical events as an async iterable.
211
+ *
212
+ * Defaults to standardised events from local snapshots (`standard: true`).
213
+ * Pass `standard: false` to stream raw payloads via the `/raw` endpoint.
214
+ *
215
+ * @example
216
+ * ```ts
217
+ * for await (const row of client.replay({
218
+ * source: "binance",
219
+ * market: "BTC-USDT",
220
+ * from: "2024-01-01T00:00:00Z",
221
+ * to: "2024-01-01T01:00:00Z",
222
+ * })) {
223
+ * console.log(row);
224
+ * }
225
+ * ```
226
+ */
227
+ replay(options: ReplayOptions): AsyncGenerator<Json>;
228
+ /**
229
+ * Return raw venue-native payloads for a time range.
230
+ * Requires an API key. Uses the `/raw` endpoint with pagination.
231
+ */
232
+ raw(options: RawQueryOptions): Promise<Json[]>;
233
+ /**
234
+ * Download a single snapshot file by key.
235
+ *
236
+ * Returns the native `Response` so you can consume the body as needed
237
+ * (`.arrayBuffer()`, `.blob()`, or pipe to a writable stream).
238
+ */
239
+ downloadSnapshot(options: DownloadSnapshotOptions): Promise<Response>;
240
+ /**
241
+ * Get a pre-signed download URL for a snapshot file
242
+ * without fetching the file itself.
243
+ */
244
+ getSnapshotDownloadUrl(options: DownloadSnapshotOptions): Promise<DownloadUrlResponse>;
245
+ /** Release resources. Currently a no-op (reserved for future use). */
246
+ close(): void;
247
+ /** Async disposable support (Node ≥ 18 / TypeScript ≥ 5.2). */
248
+ [Symbol.asyncDispose](): Promise<void>;
249
+ /**
250
+ * Core routine: ensure daily `.jsonl.zst` artifacts exist, decompress them,
251
+ * and yield matching events one at a time.
252
+ */
253
+ private _readDailyEvents;
254
+ /**
255
+ * Ensure every requested date has a materialised daily artifact.
256
+ * Downloads missing snapshots and materialises them into `daily/`.
257
+ */
258
+ private _ensureDailyArtifacts;
259
+ /**
260
+ * Download a snapshot to `data/` and create a hardlink (or copy) into
261
+ * `daily/`.
262
+ */
263
+ private _downloadAndMaterialise;
264
+ private _streamRaw;
265
+ private _getJson;
266
+ private _fetchRaw;
267
+ private _buildHeaders;
268
+ private _buildUrl;
269
+ private _paginateAll;
270
+ private _getLayout;
271
+ }
272
+
273
+ declare class PolarisError extends Error {
274
+ readonly name: string;
275
+ /** HTTP status code, if the error originated from an API response. */
276
+ readonly statusCode: number | undefined;
277
+ /** Raw response body string. */
278
+ readonly body: string | undefined;
279
+ constructor(message: string, statusCode?: number, body?: string);
280
+ toString(): string;
281
+ }
282
+ declare class UnauthorizedError extends PolarisError {
283
+ readonly name: string;
284
+ }
285
+ declare class NotFoundError extends PolarisError {
286
+ readonly name: string;
287
+ }
288
+ declare class RateLimitedError extends PolarisError {
289
+ readonly name: string;
290
+ /** ISO 8601 timestamp (or epoch) indicating when the rate limit resets. */
291
+ readonly resetAt: string | undefined;
292
+ constructor(message: string, statusCode?: number, body?: string, resetAt?: string);
293
+ }
294
+ declare class StreamDecodeError extends PolarisError {
295
+ readonly name: string;
296
+ }
297
+ declare class DownloadNotAllowedError extends PolarisError {
298
+ readonly name: string;
299
+ }
300
+
301
+ /**
302
+ * In-memory OHLCV bar aggregator that buckets trades by timestamp into
303
+ * fixed-width intervals.
304
+ *
305
+ * Volume is accumulated as `quantity × 1e12` (rounded to integer) to match the
306
+ * precision strategy used by the Python SDK's `_LocalOhlcvAggregator`.
307
+ */
308
+ declare class OhlcvAggregator {
309
+ private readonly _intervalUs;
310
+ private readonly _bars;
311
+ constructor(interval: OhlcvInterval);
312
+ /** Ingest a single trade event. */
313
+ add(timestamp: number, price: number, quantity: number): void;
314
+ /**
315
+ * Finalise the aggregation and return sorted bars.
316
+ *
317
+ * The `open` of each subsequent bar is overwritten with the `close` of the
318
+ * previous bar, matching the convention used by the Python SDK.
319
+ */
320
+ finish(): OhlcvBar[];
321
+ }
322
+
323
+ export { type AuthMode, type CatalogMarket, type CatalogOptions, type CatalogResponse, type CatalogSource, DownloadNotAllowedError, type DownloadSnapshotOptions, type DownloadUrlResponse, type FetchLike, type HistoricalQueryOptions, type ListSnapshotsOptions, NotFoundError, OhlcvAggregator, type OhlcvBar, type OhlcvInterval, type OhlcvOptions, type PaginatedResponse, PolarisClient, type PolarisClientOptions, PolarisError, RateLimitedError, type RawQueryOptions, type ReplayOptions, type SnapshotEntry, type SnapshotsResponse, type StandardEvent, StreamDecodeError, type TimeInput, type TradeData, type TradeEvent, type TradingViewCandle, type TradingViewOhlcvResponse, type TradingViewVolume, UnauthorizedError };