-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolylayer.mjs
More file actions
executable file
·643 lines (609 loc) · 19.3 KB
/
Copy pathpolylayer.mjs
File metadata and controls
executable file
·643 lines (609 loc) · 19.3 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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
#!/usr/bin/env node
import {
chmodSync,
mkdirSync,
readFileSync,
writeFileSync,
} from "node:fs";
import { homedir } from "node:os";
import { basename, dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { randomUUID } from "node:crypto";
import { createInterface } from "node:readline/promises";
export const VERSION = "0.1.1";
const DEFAULT_BASE = "https://polylayer.xyz";
const DOCS_BASE = "https://polylayer.gitbook.io/docs";
const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
const VALUE_FLAGS = new Set([
"base",
"coin",
"cursor",
"idempotency-key",
"key",
"limit",
"output",
"platform",
"since",
"status",
]);
const BOOLEAN_FLAGS = new Set(["help", "version", "yes"]);
export function parseArgs(argv) {
const args = [];
const flags = {};
for (let index = 0; index < argv.length; index++) {
const raw = argv[index];
if (raw === "-h") {
flags.help = true;
continue;
}
if (raw === "-V") {
flags.version = true;
continue;
}
if (raw === "-y") {
flags.yes = true;
continue;
}
if (!raw.startsWith("--")) {
args.push(raw);
continue;
}
const [name, inline] = raw.slice(2).split("=", 2);
if (BOOLEAN_FLAGS.has(name)) {
flags[name] = true;
continue;
}
if (!VALUE_FLAGS.has(name)) {
throw new Error(`unknown option: --${name}`);
}
const value = inline ?? argv[++index];
if (!value || value.startsWith("--")) {
throw new Error(`--${name} requires a value`);
}
flags[name] = value;
}
return { args, flags };
}
function configPath(env = process.env) {
const root =
env.POLYLAYER_CONFIG_HOME ||
env.XDG_CONFIG_HOME ||
join(homedir(), ".config");
return join(root, "polylayer", "config.json");
}
function loadConfig(path) {
try {
const parsed = JSON.parse(readFileSync(path, "utf8"));
return parsed && typeof parsed === "object" ? parsed : {};
} catch {
return {};
}
}
function saveConfig(path, config) {
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
chmodSync(dirname(path), 0o700);
writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
chmodSync(path, 0o600);
}
function validateBaseUrl(value) {
let url;
try {
url = new URL(value);
} catch {
throw new Error(`invalid base URL: ${value}`);
}
const local = ["localhost", "127.0.0.1", "::1"].includes(url.hostname);
if (url.protocol !== "https:" && !(local && url.protocol === "http:")) {
throw new Error("base URL must use HTTPS (HTTP is allowed only for localhost)");
}
return url.toString().replace(/\/+$/, "");
}
function readJsonInput(value) {
if (!value) {
throw new Error("missing JSON: pass a file, inline JSON, or - for stdin");
}
const text =
value === "-"
? readFileSync(0, "utf8")
: value.trimStart().startsWith("{") ||
value.trimStart().startsWith("[")
? value
: readFileSync(value, "utf8");
try {
return JSON.parse(text);
} catch (error) {
throw new Error(`invalid JSON: ${error.message}`);
}
}
function required(value, label) {
if (value === undefined || value === null || String(value).trim() === "") {
throw new Error(`missing ${label}`);
}
return String(value);
}
function queryString(values) {
const query = new URLSearchParams();
for (const [key, value] of Object.entries(values)) {
if (value !== undefined) query.set(key, String(value));
}
const encoded = query.toString();
return encoded ? `?${encoded}` : "";
}
function formatOutput(value, output = "pretty") {
if (typeof value === "string") return value;
return JSON.stringify(value, null, output === "compact" ? 0 : 2);
}
function normalizeApiPath(path) {
if (!path?.startsWith("/")) {
throw new Error("API path must start with /");
}
if (/^https?:\/\//i.test(path)) {
throw new Error("absolute API URLs are not allowed");
}
return path.startsWith("/api/") ? path : `/api/v1${path}`;
}
export function createApiClient({
apiKey,
baseUrl,
fetchImpl = globalThis.fetch,
idempotencyKey,
}) {
if (!fetchImpl) throw new Error("Node 18+ with global fetch is required");
const base = validateBaseUrl(baseUrl);
return async function request(
method,
path,
body,
{ auth = true, raw = false } = {},
) {
if (auth && !apiKey) {
throw new Error(
"no API key; run `polylayer login`, set POLYLAYER_API_KEY, or pass --key",
);
}
if (!path.startsWith("/")) throw new Error("request path must start with /");
const headers = { Accept: raw ? "text/plain, */*" : "application/json" };
if (auth) headers.Authorization = `Bearer ${apiKey}`;
if (body !== undefined) headers["Content-Type"] = "application/json";
const write = !["GET", "HEAD"].includes(method);
if (write) headers["Idempotency-Key"] = idempotencyKey || randomUUID();
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 30_000);
let response;
try {
response = await fetchImpl(`${base}${path}`, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
signal: controller.signal,
cache: "no-store",
});
} finally {
clearTimeout(timer);
}
const text = await response.text();
if (raw) return { status: response.status, data: text };
let data;
try {
data = text ? JSON.parse(text) : null;
} catch {
data = {
error: {
code: `http_${response.status}`,
message: text.slice(0, 500) || `HTTP ${response.status}`,
},
};
}
return { status: response.status, data };
};
}
async function confirmWrite(description, assumeYes) {
if (assumeYes) return;
if (!process.stdin.isTTY || !process.stderr.isTTY) {
throw new Error(
`${description} requires confirmation; rerun with --yes in noninteractive use`,
);
}
const prompt = createInterface({ input: process.stdin, output: process.stderr });
const answer = await prompt.question(`${description}\nType yes to continue: `);
prompt.close();
if (answer.trim().toLowerCase() !== "yes") {
throw new Error("cancelled");
}
}
const HELP = `Polylayer CLI ${VERSION}
Usage
polylayer <command> [arguments] [options]
plyr <command> [arguments] [options]
Authentication
login [plyr_key] Store a key with owner-only permissions
logout Remove the stored key
whoami Validate the active key
config show|path|set-base <url>
doctor Check runtime, docs, API, and authentication
Reads
positions [--platform venue]
orders [--platform venue]
fills [--platform venue] [--since unix] [--cursor value]
Paper trading
paper accounts
paper create <json>
paper get|portfolio|fills <account_id>
paper update <account_id> <json>
paper delete <account_id> --yes
paper orders <account_id> [--status status]
paper order <account_id> <json>
paper cancel <account_id> <order_id>
Automations
strategies list|get <id>|schema
strategies validate <json>
strategies create <json> --yes
strategies patch <id> <json> --yes
strategies cancel <id> --yes
Live trading (all writes require --yes)
polymarket order <json> | cancel <id> | split|merge|redeem <json>
hyperliquid order|bulk|modify|leverage|margin|transfer|withdraw <json>
hyperliquid cancel <cloid_or_oid> --coin BTC
jupiter markets | open|close|modify|tpsl <json>
yield list | deposit|withdraw <json>
Reference and escape hatch
docs Print official GitBook llms.txt
openapi Print the bundled OpenAPI document
api <METHOD> </v1/path> [json] Call any v1 route; writes require --yes
Global options
--key <key> Overrides POLYLAYER_API_KEY and config
--base <url> Overrides POLYLAYER_BASE_URL and config
--idempotency-key <value> Stable key for a write/retry
--output pretty|compact JSON formatting (default: pretty)
--yes, -y Confirm a live/destructive write
--help, -h Show help
--version, -V Show version
JSON may be an inline object/array, a file path, or - for stdin.
Official docs: ${DOCS_BASE}/`;
async function execute(argv, env = process.env) {
const { args, flags } = parseArgs(argv);
if (flags.version) return VERSION;
if (!args[0] || flags.help) return HELP;
if (flags.output && !["pretty", "compact"].includes(flags.output)) {
throw new Error("--output must be pretty or compact");
}
const path = configPath(env);
const config = loadConfig(path);
const base = validateBaseUrl(
flags.base ||
env.POLYLAYER_BASE_URL ||
config.base_url ||
DEFAULT_BASE,
);
const key = flags.key || env.POLYLAYER_API_KEY || config.api_key;
const request = createApiClient({
apiKey: key,
baseUrl: base,
idempotencyKey: flags["idempotency-key"],
});
const yes = Boolean(flags.yes);
const checked = async (promise) => {
const result = await promise;
if (result.status >= 400) {
const error = new Error(
result.data?.error?.message || `HTTP ${result.status}`,
);
error.result = result;
throw error;
}
return result.data;
};
const api = (method, route, body) =>
checked(request(method, normalizeApiPath(route), body));
const write = async (description, method, route, body) => {
await confirmWrite(description, yes);
return api(method, route, body);
};
const [command, sub, third, fourth] = args;
if (command === "login") {
const entered = sub || key;
if (!entered?.startsWith("plyr_")) {
throw new Error(
"provide a plyr_ key as an argument, through --key, or POLYLAYER_API_KEY",
);
}
const validate = createApiClient({ apiKey: entered, baseUrl: base });
const result = await validate("GET", "/api/v1/strategies");
if (result.status >= 400) {
throw new Error(
result.data?.error?.message || `API rejected the key (${result.status})`,
);
}
saveConfig(path, {
...config,
api_key: entered,
...(flags.base ? { base_url: base } : {}),
});
return { ok: true, stored: path };
}
if (command === "logout") {
delete config.api_key;
saveConfig(path, config);
return { ok: true };
}
if (command === "config") {
if (sub === "path") return { path };
if (sub === "show") {
return {
path,
base_url: base,
key_configured: Boolean(key),
key_source: flags.key
? "flag"
: env.POLYLAYER_API_KEY
? "environment"
: config.api_key
? "config"
: null,
};
}
if (sub === "set-base") {
const configured = validateBaseUrl(third);
saveConfig(path, { ...config, base_url: configured });
return { ok: true, base_url: configured };
}
throw new Error("usage: polylayer config show|path|set-base <url>");
}
if (command === "whoami") {
const strategies = await api("GET", "/strategies");
return {
ok: true,
base_url: base,
key_configured: true,
visible_automations: strategies.strategies?.length ?? 0,
};
}
if (command === "doctor") {
const docsStatus = await fetch(`${DOCS_BASE}/llms.txt`, {
headers: { Accept: "text/markdown" },
})
.then((response) => response.status)
.catch(() => 0);
let authStatus = null;
if (key) {
authStatus = (await request("GET", "/api/v1/strategies")).status;
}
return {
ok: docsStatus === 200 && (!key || authStatus < 400),
node: process.version,
base_url: base,
docs: `${DOCS_BASE}/`,
docs_reachable: docsStatus === 200,
key_configured: Boolean(key),
auth_status: authStatus,
};
}
if (command === "docs") {
const response = await fetch(`${DOCS_BASE}/llms.txt`, {
headers: { Accept: "text/markdown" },
});
if (!response.ok) throw new Error(`docs fetch failed (${response.status})`);
return await response.text();
}
if (command === "openapi") {
return JSON.parse(readFileSync(join(MODULE_DIR, "openapi.json"), "utf8"));
}
if (command === "positions") {
return api("GET", `/positions${queryString({ platform: flags.platform })}`);
}
if (command === "orders") {
return api("GET", `/orders/open${queryString({ platform: flags.platform })}`);
}
if (command === "fills") {
return api(
"GET",
`/fills${queryString({
platform: flags.platform,
since: flags.since,
cursor: flags.cursor,
})}`,
);
}
if (command === "strategies") {
if (sub === "list") return api("GET", "/strategies");
if (sub === "get") {
return api(
"GET",
`/strategies/${encodeURIComponent(required(third, "strategy id"))}`,
);
}
if (sub === "schema") {
return checked(request("GET", "/api/v1/strategies/schema", undefined, { auth: false }));
}
if (sub === "validate") {
return api("POST", "/strategies/validate", readJsonInput(third));
}
if (sub === "create") {
return write(
"Arm this automation? It may execute trades when its condition fires.",
"POST",
"/strategies",
readJsonInput(third),
);
}
if (sub === "patch") {
const strategyId = required(third, "strategy id");
return write(
`Replace armed automation ${strategyId}?`,
"PATCH",
`/strategies/${encodeURIComponent(strategyId)}`,
readJsonInput(fourth),
);
}
if (sub === "cancel") {
const strategyId = required(third, "strategy id");
return write(
`Cancel automation ${strategyId}?`,
"DELETE",
`/strategies/${encodeURIComponent(strategyId)}`,
);
}
throw new Error("usage: polylayer strategies list|get|schema|validate|create|patch|cancel");
}
if (command === "paper") {
if (sub === "accounts") return api("GET", "/paper/accounts");
if (sub === "create") return api("POST", "/paper/accounts", readJsonInput(third));
const accountId = [
"get",
"update",
"delete",
"portfolio",
"fills",
"orders",
"order",
"cancel",
].includes(sub)
? required(third, "paper account id")
: null;
if (sub === "get") {
return api("GET", `/paper/accounts/${encodeURIComponent(accountId)}`);
}
if (sub === "update") {
return api(
"PATCH",
`/paper/accounts/${encodeURIComponent(accountId)}`,
readJsonInput(fourth),
);
}
if (sub === "delete") {
return write(
`Permanently delete paper sandbox ${accountId}?`,
"DELETE",
`/paper/accounts/${encodeURIComponent(accountId)}`,
);
}
if (sub === "portfolio") {
return api("GET", `/paper/accounts/${encodeURIComponent(accountId)}/portfolio`);
}
if (sub === "fills") {
return api("GET", `/paper/accounts/${encodeURIComponent(accountId)}/fills`);
}
if (sub === "orders") {
return api(
"GET",
`/paper/accounts/${encodeURIComponent(accountId)}/orders${queryString({ status: flags.status })}`,
);
}
if (sub === "order") {
return api(
"POST",
`/paper/accounts/${encodeURIComponent(accountId)}/orders`,
readJsonInput(fourth),
);
}
if (sub === "cancel") {
const orderId = required(fourth, "paper order id");
return api(
"DELETE",
`/paper/accounts/${encodeURIComponent(accountId)}/orders/${encodeURIComponent(orderId)}`,
);
}
throw new Error("usage: polylayer paper accounts|create|get|update|delete|portfolio|fills|orders|order|cancel");
}
const liveJsonWrite = async (venue, action, route) => {
if (sub !== action) return undefined;
return write(
`${venue} ${action} will affect live funds. Continue?`,
"POST",
route,
readJsonInput(third),
);
};
if (command === "polymarket") {
if (sub === "cancel") {
const orderId = required(third, "Polymarket order id");
return write(
`Cancel live Polymarket order ${orderId}?`,
"DELETE",
`/polymarket/orders/${encodeURIComponent(orderId)}`,
);
}
const routes = {
order: "/polymarket/orders",
split: "/polymarket/split",
merge: "/polymarket/merge",
redeem: "/polymarket/redeem",
};
if (routes[sub]) return liveJsonWrite("Polymarket", sub, routes[sub]);
throw new Error("usage: polylayer polymarket order|cancel|split|merge|redeem");
}
if (command === "hyperliquid") {
if (sub === "cancel") {
if (!flags.coin) throw new Error("hyperliquid cancel requires --coin");
const orderId = required(third, "Hyperliquid order id");
return write(
`Cancel live Hyperliquid order ${orderId} on ${flags.coin}?`,
"DELETE",
`/hyperliquid/orders/${encodeURIComponent(orderId)}${queryString({ coin: flags.coin })}`,
);
}
const routes = {
order: "/hyperliquid/orders",
bulk: "/hyperliquid/bulk-orders",
modify: "/hyperliquid/modify-order",
leverage: "/hyperliquid/leverage",
margin: "/hyperliquid/isolated-margin",
transfer: "/hyperliquid/transfer",
withdraw: "/hyperliquid/withdraw",
};
if (routes[sub]) return liveJsonWrite("Hyperliquid", sub, routes[sub]);
throw new Error("usage: polylayer hyperliquid order|bulk|modify|leverage|margin|transfer|withdraw|cancel");
}
if (command === "jupiter") {
if (sub === "markets") return api("GET", "/jupiter/markets");
const routes = {
open: "/jupiter/positions/open",
close: "/jupiter/positions/close",
modify: "/jupiter/positions/modify",
tpsl: "/jupiter/positions/tpsl",
};
if (routes[sub]) return liveJsonWrite("Jupiter", sub, routes[sub]);
throw new Error("usage: polylayer jupiter markets|open|close|modify|tpsl");
}
if (command === "yield") {
if (sub === "list") return api("GET", "/yield");
if (sub === "deposit" || sub === "withdraw") {
return liveJsonWrite("Yield", sub, `/yield/${sub}`);
}
throw new Error("usage: polylayer yield list|deposit|withdraw");
}
if (command === "api") {
const method = (sub || "").toUpperCase();
if (!["GET", "POST", "PATCH", "PUT", "DELETE"].includes(method)) {
throw new Error("usage: polylayer api <GET|POST|PATCH|PUT|DELETE> </v1/path> [json]");
}
const route = normalizeApiPath(required(third, "API path"));
const body = fourth === undefined ? undefined : readJsonInput(fourth);
if (!["GET", "HEAD"].includes(method)) {
await confirmWrite(`Call ${method} ${route}?`, yes);
}
return checked(request(method, route, body));
}
throw new Error(`unknown command: ${command}`);
}
export async function run(argv = process.argv.slice(2), env = process.env) {
const { flags } = parseArgs(argv);
try {
const result = await execute(argv, env);
process.stdout.write(`${formatOutput(result, flags.output)}\n`);
return 0;
} catch (error) {
if (error.result?.data) {
process.stderr.write(`${formatOutput(error.result.data, flags.output)}\n`);
} else {
process.stderr.write(`error: ${error.message || String(error)}\n`);
}
return 1;
}
}
if (
process.argv[1] &&
["polylayer", "plyr", "polylayer.mjs"].includes(basename(process.argv[1]))
) {
process.exitCode = await run();
}