-
-
Notifications
You must be signed in to change notification settings - Fork 236
Expand file tree
/
Copy pathindex.ts
More file actions
313 lines (267 loc) · 10.9 KB
/
Copy pathindex.ts
File metadata and controls
313 lines (267 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
import {
PredictionMarketExchange,
MarketFilterParams,
EventFetchParams,
OHLCVParams,
TradesParams,
ExchangeCredentials,
MyTradesParams,
} from '../../BaseExchange';
import {
UnifiedMarket,
UnifiedEvent,
OrderBook,
PriceCandle,
Trade,
UserTrade,
Balance,
Position,
Order,
CreateOrderParams,
BuiltOrder,
} from '../../types';
import { AuthenticationError } from '../../errors';
import { getHyperliquidConfig, HyperliquidApiConfig } from './config';
import { HyperliquidFetcher } from './fetcher';
import { HyperliquidNormalizer } from './normalizer';
import { HyperliquidAuth, floatToWire } from './auth';
import { hyperliquidErrorMapper } from './errors';
import { FetcherContext } from '../interfaces';
import { fromMarketId } from './utils';
export interface HyperliquidExchangeOptions {
credentials?: ExchangeCredentials;
testnet?: boolean;
}
export class HyperliquidExchange extends PredictionMarketExchange {
protected override readonly capabilityOverrides = {
fetchSeries: false as const,
};
private readonly config: HyperliquidApiConfig;
private readonly fetcher: HyperliquidFetcher;
private readonly normalizer: HyperliquidNormalizer;
private readonly walletAddress?: string;
private readonly auth?: HyperliquidAuth;
constructor(credentials?: ExchangeCredentials | HyperliquidExchangeOptions) {
const opts = credentials && 'credentials' in credentials
? credentials as HyperliquidExchangeOptions
: { credentials: credentials as ExchangeCredentials | undefined };
super(opts.credentials);
this.rateLimit = 200;
const testnet = 'testnet' in (opts as any) ? (opts as HyperliquidExchangeOptions).testnet : false;
this.config = getHyperliquidConfig(opts.credentials?.baseUrl, testnet);
// Initialize auth if privateKey is provided (needed for trading)
if (opts.credentials?.privateKey) {
this.auth = new HyperliquidAuth(opts.credentials, this.config.testnet);
this.walletAddress = this.auth.getAddress();
} else {
// For read-only usage, users can pass walletAddress as apiKey
this.walletAddress = opts.credentials?.apiKey || undefined;
}
const ctx: FetcherContext = {
http: this.http,
callApi: this.callApi.bind(this),
getHeaders: () => ({}),
};
this.fetcher = new HyperliquidFetcher(ctx, this.config.baseUrl);
this.normalizer = new HyperliquidNormalizer();
}
get name(): string {
return 'Hyperliquid';
}
// -------------------------------------------------------------------------
// Auth helpers
// -------------------------------------------------------------------------
private requireWallet(): string {
if (!this.walletAddress) {
throw new AuthenticationError(
'This operation requires a wallet address. ' +
'Initialize HyperliquidExchange with credentials (apiKey = wallet address, or privateKey for trading).',
'Hyperliquid',
);
}
return this.walletAddress;
}
private requireAuth(): HyperliquidAuth {
if (!this.auth) {
throw new AuthenticationError(
'Trading requires a privateKey for EIP-712 signing. ' +
'Initialize HyperliquidExchange with credentials including privateKey.',
'Hyperliquid',
);
}
return this.auth;
}
// -------------------------------------------------------------------------
// Market Data
// -------------------------------------------------------------------------
protected async fetchMarketsImpl(
params?: MarketFilterParams,
): Promise<UnifiedMarket[]> {
const rawOutcomes = await this.fetcher.fetchRawMarkets(params);
return rawOutcomes
.map(r => this.normalizer.normalizeMarket(r))
.filter((m): m is UnifiedMarket => m !== null);
}
protected async fetchEventsImpl(
params: EventFetchParams,
): Promise<UnifiedEvent[]> {
// Venue does not expose a series concept; honoring `params.series` by returning [] rather than ignoring the filter.
if (params.series !== undefined) {
return [];
}
const [rawQuestions, meta, mids] = await Promise.all([
this.fetcher.fetchRawEvents(params),
this.fetcher.fetchOutcomeMeta(),
this.fetcher.fetchAllMids(),
]);
return rawQuestions
.map(q => this.normalizer.normalizeEventWithMarkets(q, meta, mids))
.filter((e): e is UnifiedEvent => e !== null);
}
async fetchOrderBook(outcomeId: string, _limit?: number, _params?: Record<string, any>): Promise<OrderBook> {
const resolved = await this.resolveOutcomeAlias(outcomeId, _params);
outcomeId = resolved.outcomeId;
_params = resolved.params;
const raw = await this.fetcher.fetchRawOrderBook(outcomeId);
return this.normalizer.normalizeOrderBook(raw, outcomeId);
}
async fetchOHLCV(outcomeId: string, params: OHLCVParams = { resolution: '1h' }): Promise<PriceCandle[]> {
const raw = await this.fetcher.fetchRawOHLCV(outcomeId, params);
return this.normalizer.normalizeOHLCV(raw, params);
}
async fetchTrades(outcomeId: string, params?: TradesParams): Promise<Trade[]> {
const raw = await this.fetcher.fetchRawTrades(outcomeId, params || {});
return raw.map((r, i) => this.normalizer.normalizeTrade(r, i));
}
// -------------------------------------------------------------------------
// User Data
// -------------------------------------------------------------------------
async fetchBalance(): Promise<Balance[]> {
const wallet = this.requireWallet();
const raw = await this.fetcher.fetchRawUserState(wallet);
return this.normalizer.normalizeBalance(raw);
}
async fetchPositions(): Promise<Position[]> {
const wallet = this.requireWallet();
const raw = await this.fetcher.fetchRawUserState(wallet);
return raw.assetPositions
.filter(ap => ap.position.coin.startsWith('#'))
.map(ap => this.normalizer.normalizePosition(ap.position));
}
async fetchOpenOrders(): Promise<Order[]> {
const wallet = this.requireWallet();
const raw = await this.fetcher.fetchRawOpenOrders(wallet);
return raw
.filter(o => o.coin.startsWith('#'))
.map(o => this.normalizer.normalizeOpenOrder(o));
}
async fetchMyTrades(params?: MyTradesParams): Promise<UserTrade[]> {
const wallet = this.requireWallet();
const raw = await this.fetcher.fetchRawUserFills(wallet);
return raw
.filter(f => f.coin.startsWith('#'))
.map((f, i) => this.normalizer.normalizeUserTrade(f, i));
}
// -------------------------------------------------------------------------
// Trading (EIP-712 signing required)
// -------------------------------------------------------------------------
async buildOrder(params: CreateOrderParams): Promise<BuiltOrder> {
const assetId = parseInt(params.outcomeId, 10);
// Key order matters for msgpack hash: a, b, p, s, r, t, c
const orderWire: Record<string, unknown> = {
a: assetId,
b: params.side === 'buy',
p: params.price !== undefined ? floatToWire(params.price) : '0.5',
s: floatToWire(params.amount),
r: false,
t: params.type === 'market'
? { limit: { tif: 'Ioc' } }
: { limit: { tif: 'Gtc' } },
};
// Key order matters for msgpack hash: type, orders, grouping
const action: Record<string, unknown> = {
type: 'order',
orders: [orderWire],
grouping: 'na',
};
return {
exchange: this.name,
params,
raw: action,
};
}
async submitOrder(built: BuiltOrder): Promise<Order> {
const auth = this.requireAuth();
const action = built.raw as Record<string, unknown>;
try {
const requestBody = await auth.signExchangeRequest(action);
const response = await this.http.post(
`${this.config.baseUrl}/exchange`,
requestBody,
);
const data = response.data;
if (data.status === 'err') {
throw hyperliquidErrorMapper.mapError(
new Error(data.response || 'Order submission failed'),
);
}
const resting = data.response?.data?.statuses?.[0];
return {
id: resting?.resting?.oid ? String(resting.resting.oid) : 'unknown',
marketId: built.params.marketId,
outcomeId: built.params.outcomeId,
side: built.params.side,
type: built.params.type,
price: built.params.price,
amount: built.params.amount,
status: resting?.resting ? 'open' : 'filled',
filled: resting?.filled?.totalSz ? parseFloat(resting.filled.totalSz) : 0,
remaining: built.params.amount - (resting?.filled?.totalSz ? parseFloat(resting.filled.totalSz) : 0),
timestamp: Date.now(),
};
} catch (error: any) {
throw hyperliquidErrorMapper.mapError(error);
}
}
async createOrder(params: CreateOrderParams): Promise<Order> {
const built = await this.buildOrder(params);
return this.submitOrder(built);
}
async cancelOrder(orderId: string): Promise<Order> {
const auth = this.requireAuth();
// Key order matters for msgpack hash: type, cancels
// Each cancel entry: a (asset), o (order id)
const action: Record<string, unknown> = {
type: 'cancel',
cancels: [{ a: 0, o: parseInt(orderId, 10) }],
};
try {
const requestBody = await auth.signExchangeRequest(action);
const response = await this.http.post(
`${this.config.baseUrl}/exchange`,
requestBody,
);
const data = response.data;
if (data.status === 'err') {
throw new Error(data.response || 'Cancel failed');
}
return {
id: orderId,
marketId: '',
outcomeId: '',
side: 'buy',
type: 'limit',
amount: 0,
status: 'canceled',
filled: 0,
remaining: 0,
timestamp: Date.now(),
};
} catch (error: any) {
throw hyperliquidErrorMapper.mapError(error);
}
}
async close(): Promise<void> {
// No persistent connections to clean up
}
}