@deeptick/client 0.1.1

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.
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@deeptick/client",
3
+ "version": "0.1.1",
4
+ "description": "DeepTick TypeScript SDK — high-frequency crypto market data",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": "./dist/index.js",
10
+ "./streaming": "./dist/streaming.js",
11
+ "./feed": "./dist/feed.js",
12
+ "./cache": "./dist/cache.js",
13
+ "./types": "./dist/types.js"
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "src",
18
+ "README.md"
19
+ ],
20
+ "scripts": {
21
+ "build": "tsc",
22
+ "dev": "tsc --watch",
23
+ "clean": "rm -rf dist"
24
+ },
25
+ "dependencies": {
26
+ "ws": "^8.18.0"
27
+ },
28
+ "devDependencies": {
29
+ "typescript": "^5.5.0",
30
+ "@types/ws": "^8.5.12",
31
+ "@types/node": "^22.0.0"
32
+ },
33
+ "peerDependencies": {
34
+ "apache-arrow": ">=15.0.0",
35
+ "parquet-wasm": ">=0.6.0"
36
+ },
37
+ "peerDependenciesMeta": {
38
+ "apache-arrow": { "optional": true },
39
+ "parquet-wasm": { "optional": true }
40
+ },
41
+ "keywords": [
42
+ "deeptick",
43
+ "crypto",
44
+ "market-data",
45
+ "order-book",
46
+ "websocket",
47
+ "streaming",
48
+ "parquet",
49
+ "hft"
50
+ ],
51
+ "license": "MIT",
52
+ "author": "DeepTick",
53
+ "repository": {
54
+ "type": "git",
55
+ "url": "https://github.com/deeptick/deeptick"
56
+ }
57
+ }
package/src/cache.ts ADDED
@@ -0,0 +1,206 @@
1
+ /**
2
+ * DeepTick TypeScript Client — Caching + Parallel Downloads.
3
+ *
4
+ * Disk-based cache for downloaded data so repeat queries are instant.
5
+ * Parallel multi-day fetches via Promise.all.
6
+ *
7
+ * Usage:
8
+ * import { CachedClient } from '@deeptick/client';
9
+ *
10
+ * const client = new CachedClient('https://deeptick.lacertalabs.xyz');
11
+ *
12
+ * // First call: downloads from server, caches locally
13
+ * const trades = await client.loadTrades('hyperliquid', 'BTC', '2026-05-01', '2026-05-07');
14
+ *
15
+ * // Second call: instant from disk cache
16
+ * const trades2 = await client.loadTrades('hyperliquid', 'BTC', '2026-05-01', '2026-05-07');
17
+ */
18
+
19
+ import * as fs from 'fs';
20
+ import * as path from 'path';
21
+ import * as os from 'os';
22
+ import * as crypto from 'crypto';
23
+
24
+ export interface CacheStats {
25
+ cacheDir: string;
26
+ cacheHits: number;
27
+ cacheMisses: number;
28
+ hitRatePct: number;
29
+ bytesDownloaded: number;
30
+ bytesFromCache: number;
31
+ }
32
+
33
+ export class CachedClient {
34
+ private baseUrl: string;
35
+ private cacheDir: string;
36
+ private maxConcurrency: number;
37
+ private apiKey: string;
38
+
39
+ cacheHits = 0;
40
+ cacheMisses = 0;
41
+ bytesDownloaded = 0;
42
+ bytesFromCache = 0;
43
+
44
+ constructor(
45
+ baseUrl: string = 'https://deeptick.lacertalabs.xyz',
46
+ cacheDir?: string,
47
+ maxConcurrency: number = 8,
48
+ apiKey: string = process.env.DEEPTICK_API_KEY ?? '',
49
+ ) {
50
+ this.baseUrl = baseUrl.replace(/\/$/, '');
51
+ this.cacheDir = cacheDir || path.join(os.homedir(), '.deeptick', 'cache');
52
+ this.maxConcurrency = maxConcurrency;
53
+ this.apiKey = apiKey;
54
+ fs.mkdirSync(this.cacheDir, { recursive: true });
55
+ }
56
+
57
+ // ─── Cache Key ────────────────────────────────────────────────────
58
+
59
+ private cachePath(
60
+ exchange: string, dataType: string, symbol: string, date: string,
61
+ columns?: string[],
62
+ ): string {
63
+ const safeSymbol = symbol.replace(/\//g, '-').replace(/:/g, '-');
64
+ let colHash = '';
65
+ if (columns && columns.length > 0) {
66
+ const sorted = [...columns].sort().join(',');
67
+ colHash = '_' + crypto.createHash('md5').update(sorted).digest('hex').slice(0, 8);
68
+ }
69
+ return path.join(
70
+ this.cacheDir, exchange, dataType, safeSymbol,
71
+ `${date}${colHash}.bin`,
72
+ );
73
+ }
74
+
75
+ private isCached(filePath: string): boolean {
76
+ return fs.existsSync(filePath);
77
+ }
78
+
79
+ // ─── Download ─────────────────────────────────────────────────────
80
+
81
+ private async downloadDate(
82
+ exchange: string, dataType: string, symbol: string, date: string,
83
+ columns?: string[], format: string = 'csv',
84
+ ): Promise<string | null> {
85
+ const cp = this.cachePath(exchange, dataType, symbol, date, columns);
86
+
87
+ if (this.isCached(cp)) {
88
+ this.cacheHits++;
89
+ this.bytesFromCache += fs.statSync(cp).size;
90
+ return fs.readFileSync(cp, 'utf-8');
91
+ }
92
+
93
+ this.cacheMisses++;
94
+
95
+ let url = `${this.baseUrl}/v1/data/${exchange}/${dataType}/${symbol}/${date}?format=${format}`;
96
+ if (columns && columns.length > 0) {
97
+ url += `&columns=${columns.join(',')}`;
98
+ }
99
+
100
+ try {
101
+ const headers: Record<string, string> = {};
102
+ if (this.apiKey) {
103
+ headers['X-API-Key'] = this.apiKey;
104
+ }
105
+ const resp = await fetch(url, { headers });
106
+ if (!resp.ok) {
107
+ if (resp.status === 404) return null;
108
+ throw new Error(`HTTP ${resp.status}`);
109
+ }
110
+
111
+ const data = await resp.text();
112
+ this.bytesDownloaded += Buffer.byteLength(data);
113
+
114
+ // Cache to disk
115
+ const dir = path.dirname(cp);
116
+ fs.mkdirSync(dir, { recursive: true });
117
+ fs.writeFileSync(cp, data);
118
+
119
+ return data;
120
+ } catch (err) {
121
+ console.error(`[cache] Download error for ${exchange}/${dataType}/${symbol}/${date}:`, err);
122
+ return null;
123
+ }
124
+ }
125
+
126
+ // ─── Parallel Multi-Day Loader ────────────────────────────────────
127
+
128
+ private dateRange(start: string, end: string): string[] {
129
+ const dates: string[] = [];
130
+ const current = new Date(start + 'T00:00:00Z');
131
+ const endDate = new Date(end + 'T00:00:00Z');
132
+
133
+ while (current <= endDate) {
134
+ dates.push(current.toISOString().split('T')[0]);
135
+ current.setUTCDate(current.getUTCDate() + 1);
136
+ }
137
+ return dates;
138
+ }
139
+
140
+ async load(
141
+ dataType: string,
142
+ exchange: string,
143
+ symbol: string,
144
+ startDate: string,
145
+ endDate?: string,
146
+ columns?: string[],
147
+ ): Promise<string[]> {
148
+ const end = endDate || startDate;
149
+ const dates = this.dateRange(startDate, end);
150
+
151
+ // Parallel download with concurrency limit
152
+ const results: (string | null)[] = [];
153
+ for (let i = 0; i < dates.length; i += this.maxConcurrency) {
154
+ const batch = dates.slice(i, i + this.maxConcurrency);
155
+ const batchResults = await Promise.all(
156
+ batch.map(d => this.downloadDate(exchange, dataType, symbol, d, columns)),
157
+ );
158
+ results.push(...batchResults);
159
+ }
160
+
161
+ return results.filter((r): r is string => r !== null);
162
+ }
163
+
164
+ async loadTrades(
165
+ exchange: string, symbol: string, startDate: string, endDate?: string,
166
+ ): Promise<string[]> {
167
+ return this.load('trades', exchange, symbol, startDate, endDate);
168
+ }
169
+
170
+ async loadBookDeltas(
171
+ exchange: string, symbol: string, startDate: string, endDate?: string,
172
+ ): Promise<string[]> {
173
+ return this.load('book_l2_delta', exchange, symbol, startDate, endDate);
174
+ }
175
+
176
+ async loadDerivativeTicker(
177
+ exchange: string, symbol: string, startDate: string, endDate?: string,
178
+ ): Promise<string[]> {
179
+ return this.load('derivative_ticker', exchange, symbol, startDate, endDate);
180
+ }
181
+
182
+ async loadFunding(
183
+ exchange: string, symbol: string, startDate: string, endDate?: string,
184
+ ): Promise<string[]> {
185
+ return this.loadDerivativeTicker(exchange, symbol, startDate, endDate);
186
+ }
187
+
188
+ // ─── Cache Management ────────────────────────────────────────────
189
+
190
+ getStats(): CacheStats {
191
+ const total = this.cacheHits + this.cacheMisses;
192
+ return {
193
+ cacheDir: this.cacheDir,
194
+ cacheHits: this.cacheHits,
195
+ cacheMisses: this.cacheMisses,
196
+ hitRatePct: total > 0 ? Math.round((this.cacheHits / total) * 1000) / 10 : 0,
197
+ bytesDownloaded: this.bytesDownloaded,
198
+ bytesFromCache: this.bytesFromCache,
199
+ };
200
+ }
201
+
202
+ clearCache(): void {
203
+ fs.rmSync(this.cacheDir, { recursive: true, force: true });
204
+ fs.mkdirSync(this.cacheDir, { recursive: true });
205
+ }
206
+ }
package/src/feed.ts ADDED
@@ -0,0 +1,290 @@
1
+ /**
2
+ * DeepTick TypeScript Unified Feed — Seamless Live ↔ Replay switching.
3
+ *
4
+ * Same interface for both live streaming and historical replay.
5
+ * Backtest code = production code.
6
+ *
7
+ * Usage:
8
+ * import { DeepTickFeed, FeedMode } from '@deeptick/client';
9
+ *
10
+ * // Live mode
11
+ * const feed = DeepTickFeed.live('wss://deeptick.lacertalabs.xyz/v1/stream');
12
+ * feed.onData((topic, data) => console.log(topic, data));
13
+ * await feed.connect();
14
+ * await feed.subscribe(['hyperliquid.trades.BTC']);
15
+ *
16
+ * // Replay mode — same callback, historical data
17
+ * const feed = DeepTickFeed.replay('wss://deeptick.lacertalabs.xyz/v1/replay/ws', {
18
+ * sources: ['hyperliquid:trades:BTC'],
19
+ * from: '2026-05-01',
20
+ * to: '2026-05-03',
21
+ * speed: 10,
22
+ * });
23
+ * feed.onData((topic, data) => console.log(topic, data)); // Same handler!
24
+ * await feed.connect();
25
+ *
26
+ * // Auto mode — replay then switch to live
27
+ * const feed = DeepTickFeed.auto('wss://deeptick.lacertalabs.xyz', {
28
+ * sources: ['hyperliquid:trades:BTC'],
29
+ * from: '2026-05-01',
30
+ * });
31
+ */
32
+
33
+ import WebSocket from 'ws';
34
+
35
+ export enum FeedMode {
36
+ LIVE = 'live',
37
+ REPLAY = 'replay',
38
+ AUTO = 'auto',
39
+ }
40
+
41
+ export interface FeedOptions {
42
+ channels?: string[];
43
+ sources?: string[];
44
+ from?: string;
45
+ to?: string;
46
+ speed?: number;
47
+ reconnect?: boolean;
48
+ apiKey?: string;
49
+ }
50
+
51
+ export interface FeedStats {
52
+ mode: FeedMode;
53
+ currentMode: FeedMode;
54
+ messagesReceived: number;
55
+ connected: boolean;
56
+ url: string;
57
+ }
58
+
59
+ type DataCallback = (topic: string, data: Record<string, any>) => void;
60
+ type ReplayEndCallback = (stats: { totalEvents: number; durationS: number }) => void;
61
+ type ModeChangeCallback = (from: FeedMode, to: FeedMode) => void;
62
+
63
+ export class DeepTickFeed {
64
+ private mode: FeedMode;
65
+ private currentMode: FeedMode;
66
+ private url: string;
67
+ private options: FeedOptions;
68
+ private ws: WebSocket | null = null;
69
+ private messagesReceived = 0;
70
+ private connected = false;
71
+
72
+ private dataCallbacks: DataCallback[] = [];
73
+ private replayEndCallbacks: ReplayEndCallback[] = [];
74
+ private modeChangeCallbacks: ModeChangeCallback[] = [];
75
+
76
+ private constructor(mode: FeedMode, url: string, options: FeedOptions = {}) {
77
+ this.mode = mode;
78
+ this.currentMode = mode;
79
+ this.url = url;
80
+ this.options = options;
81
+ }
82
+
83
+ // ─── Factory Methods ─────────────────────────────────────────────
84
+
85
+ static live(url: string = 'wss://deeptick.lacertalabs.xyz/v1/stream', options: FeedOptions = {}): DeepTickFeed {
86
+ return new DeepTickFeed(FeedMode.LIVE, url, options);
87
+ }
88
+
89
+ static replay(url: string = 'wss://deeptick.lacertalabs.xyz/v1/replay/ws', options: FeedOptions = {}): DeepTickFeed {
90
+ return new DeepTickFeed(FeedMode.REPLAY, url, options);
91
+ }
92
+
93
+ static auto(baseUrl: string = 'wss://deeptick.lacertalabs.xyz', options: FeedOptions = {}): DeepTickFeed {
94
+ const today = new Date().toISOString().split('T')[0];
95
+ return new DeepTickFeed(FeedMode.AUTO, `${baseUrl}/v1/replay/ws`, {
96
+ ...options,
97
+ to: today,
98
+ });
99
+ }
100
+
101
+ // ─── Callbacks ───────────────────────────────────────────────────
102
+
103
+ /** Register a callback for data events (works identically for live and replay) */
104
+ onData(cb: DataCallback): this {
105
+ this.dataCallbacks.push(cb);
106
+ return this;
107
+ }
108
+
109
+ /** Register a callback for replay completion */
110
+ onReplayEnd(cb: ReplayEndCallback): this {
111
+ this.replayEndCallbacks.push(cb);
112
+ return this;
113
+ }
114
+
115
+ /** Register a callback for mode changes (replay → live in auto mode) */
116
+ onModeChange(cb: ModeChangeCallback): this {
117
+ this.modeChangeCallbacks.push(cb);
118
+ return this;
119
+ }
120
+
121
+ // ─── Connection ──────────────────────────────────────────────────
122
+
123
+ async connect(): Promise<void> {
124
+ return new Promise((resolve, reject) => {
125
+ const urlWithKey = this.options.apiKey
126
+ ? `${this.url}?api_key=${this.options.apiKey}`
127
+ : this.url;
128
+
129
+ this.ws = new WebSocket(urlWithKey);
130
+
131
+ this.ws.on('open', () => {
132
+ this.connected = true;
133
+ });
134
+
135
+ this.ws.on('message', (raw: WebSocket.Data) => {
136
+ const frame = JSON.parse(raw.toString());
137
+ this.messagesReceived++;
138
+
139
+ switch (frame.type) {
140
+ case 'welcome':
141
+ // Start feed based on mode
142
+ if (this.mode === FeedMode.LIVE) {
143
+ this.startLive();
144
+ } else {
145
+ this.startReplay();
146
+ }
147
+ resolve();
148
+ break;
149
+
150
+ case 'data':
151
+ for (const cb of this.dataCallbacks) {
152
+ cb(frame.topic, frame.data);
153
+ }
154
+ break;
155
+
156
+ case 'replay_end':
157
+ for (const cb of this.replayEndCallbacks) {
158
+ cb({
159
+ totalEvents: frame.total_events,
160
+ durationS: frame.duration_s,
161
+ });
162
+ }
163
+
164
+ if (this.currentMode === FeedMode.AUTO) {
165
+ // Switch to live
166
+ this.switchToLive();
167
+ }
168
+ break;
169
+
170
+ case 'subscribed':
171
+ case 'replay_start':
172
+ case 'heartbeat':
173
+ break;
174
+
175
+ case 'error':
176
+ console.error('[feed] Server error:', frame.message);
177
+ break;
178
+ }
179
+ });
180
+
181
+ this.ws.on('close', () => {
182
+ this.connected = false;
183
+ });
184
+
185
+ this.ws.on('error', (err) => {
186
+ if (!this.connected) {
187
+ reject(err);
188
+ }
189
+ });
190
+ });
191
+ }
192
+
193
+ async disconnect(): Promise<void> {
194
+ this.connected = false;
195
+ if (this.ws) {
196
+ this.ws.close();
197
+ this.ws = null;
198
+ }
199
+ }
200
+
201
+ async subscribe(channels: string[]): Promise<void> {
202
+ this.options.channels = channels;
203
+ if (this.connected && this.currentMode === FeedMode.LIVE && this.ws) {
204
+ this.ws.send(JSON.stringify({ action: 'subscribe', channels }));
205
+ }
206
+ }
207
+
208
+ // ─── Internal ────────────────────────────────────────────────────
209
+
210
+ private startLive(): void {
211
+ if (this.options.channels && this.ws) {
212
+ this.ws.send(JSON.stringify({
213
+ action: 'subscribe',
214
+ channels: this.options.channels,
215
+ }));
216
+ }
217
+ this.currentMode = FeedMode.LIVE;
218
+ }
219
+
220
+ private startReplay(): void {
221
+ if (this.ws) {
222
+ this.ws.send(JSON.stringify({
223
+ action: 'replay',
224
+ sources: this.options.sources || [],
225
+ from: this.options.from || '',
226
+ to: this.options.to || '',
227
+ speed: this.options.speed || 0,
228
+ }));
229
+ }
230
+ this.currentMode = FeedMode.REPLAY;
231
+ }
232
+
233
+ private async switchToLive(): Promise<void> {
234
+ const oldMode = this.currentMode;
235
+
236
+ // Close replay connection
237
+ if (this.ws) {
238
+ this.ws.close();
239
+ }
240
+
241
+ // Connect to live endpoint
242
+ const liveUrl = this.url.replace('/v1/replay/ws', '/v1/stream');
243
+ const urlWithKey = this.options.apiKey
244
+ ? `${liveUrl}?api_key=${this.options.apiKey}`
245
+ : liveUrl;
246
+
247
+ return new Promise((resolve) => {
248
+ this.ws = new WebSocket(urlWithKey);
249
+
250
+ this.ws.on('open', () => {
251
+ this.connected = true;
252
+ });
253
+
254
+ this.ws.on('message', (raw: WebSocket.Data) => {
255
+ const frame = JSON.parse(raw.toString());
256
+ this.messagesReceived++;
257
+
258
+ if (frame.type === 'welcome') {
259
+ // Build channels from sources
260
+ if (!this.options.channels && this.options.sources) {
261
+ this.options.channels = this.options.sources.map(s => s.replace(/:/g, '.'));
262
+ }
263
+ this.startLive();
264
+ for (const cb of this.modeChangeCallbacks) {
265
+ cb(oldMode, FeedMode.LIVE);
266
+ }
267
+ resolve();
268
+ } else if (frame.type === 'data') {
269
+ for (const cb of this.dataCallbacks) {
270
+ cb(frame.topic, frame.data);
271
+ }
272
+ }
273
+ });
274
+
275
+ this.ws.on('close', () => {
276
+ this.connected = false;
277
+ });
278
+ });
279
+ }
280
+
281
+ getStats(): FeedStats {
282
+ return {
283
+ mode: this.mode,
284
+ currentMode: this.currentMode,
285
+ messagesReceived: this.messagesReceived,
286
+ connected: this.connected,
287
+ url: this.url,
288
+ };
289
+ }
290
+ }
package/src/index.ts ADDED
@@ -0,0 +1,45 @@
1
+ /**
2
+ * @deeptick/client — TypeScript SDK for DeepTick market data
3
+ *
4
+ * Three layers:
5
+ * 1. CachedClient — Download + cache daily archives
6
+ * 2. DeepTickStream — Real-time WebSocket streaming
7
+ * 3. DeepTickFeed — Unified live/replay feed
8
+ * 4. derive — Client-side derived computations
9
+ *
10
+ * Usage:
11
+ * import { DeepTickStream } from '@deeptick/client';
12
+ * import { CachedClient } from '@deeptick/client/cache';
13
+ * import { DeepTickFeed } from '@deeptick/client/feed';
14
+ * import { derive } from '@deeptick/client/types';
15
+ */
16
+
17
+ // Re-export everything
18
+ export { DeepTickStream } from './streaming.js';
19
+ export type {
20
+ StreamFrame,
21
+ StreamTrade,
22
+ StreamBookTicker,
23
+ StreamBookDelta,
24
+ StreamDerivativeTicker,
25
+ DataCallback,
26
+ DeepTickStreamOptions,
27
+ } from './streaming.js';
28
+
29
+ export { DeepTickFeed, FeedMode } from './feed.js';
30
+ export type { FeedOptions, FeedStats } from './feed.js';
31
+
32
+ export { CachedClient } from './cache.js';
33
+ export type { CacheStats } from './cache.js';
34
+
35
+ export { derive, unpackLevels } from './types.js';
36
+ export type {
37
+ TradeRecord,
38
+ BookDeltaRecord,
39
+ BBORecord,
40
+ CandleRecord,
41
+ BookSnapshot,
42
+ VolumeProfileBucket,
43
+ ImbalanceRecord,
44
+ FundingCrossRecord,
45
+ } from './types.js';