@bizjaya/finclient 0.1.1 → 0.2.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.
package/dist/index.js CHANGED
@@ -20,9 +20,6 @@ async function* readAllChanges(readPage, cursor, signal) {
20
20
  }
21
21
  }
22
22
 
23
- // src/http-transport.ts
24
- import { randomUUID } from "crypto";
25
-
26
23
  // src/api-error.ts
27
24
  var FinApiError = class extends Error {
28
25
  /** The HTTP status code returned by the API, or 0 when no response arrived (timeout or network failure). */
@@ -46,21 +43,49 @@ var FinApiError = class extends Error {
46
43
  }
47
44
  };
48
45
 
46
+ // src/sse.ts
47
+ var FinSseParser = class {
48
+ eventName = null;
49
+ data = [];
50
+ /** Adds one line (without its line break). Returns the event the line completed, if any. */
51
+ add(line) {
52
+ if (!line) return this.flush();
53
+ if (line.startsWith(":")) return null;
54
+ const separator = line.indexOf(":");
55
+ const field = separator < 0 ? line : line.slice(0, separator);
56
+ const value = separator < 0 ? "" : line.slice(separator + 1).replace(/^ /, "");
57
+ if (field === "event") this.eventName = value;
58
+ else if (field === "data") this.data.push(value);
59
+ return null;
60
+ }
61
+ /** Ends the stream: an event still being read is returned when it carries data. */
62
+ complete() {
63
+ return this.data.length ? this.flush() : null;
64
+ }
65
+ flush() {
66
+ const item = this.data.length ? { event: this.eventName ?? "message", data: this.data.join("\n") } : null;
67
+ this.eventName = null;
68
+ this.data = [];
69
+ return item;
70
+ }
71
+ };
72
+
49
73
  // src/http-transport.ts
50
74
  var retryableStatuses = /* @__PURE__ */ new Set([429, 502, 503, 504]);
51
75
  var writeMethods = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
52
76
  var FinHttpTransport = class {
53
77
  apiKey;
54
78
  baseUrl;
79
+ credentials;
55
80
  timeoutMs;
56
81
  maxRetries;
57
82
  fetcher;
58
83
  delay;
59
84
  random;
60
85
  constructor(options) {
61
- if (!options.apiKey?.trim()) throw new TypeError("apiKey is required.");
62
- this.apiKey = options.apiKey;
63
- this.baseUrl = (options.baseUrl ?? "https://api.fincopy.io").replace(/\/+$/, "");
86
+ this.apiKey = options.apiKey?.trim() ?? "";
87
+ if (!this.apiKey && !options.fetch) throw new TypeError("apiKey is required unless a custom fetch authenticates the member session.");
88
+ this.baseUrl = (options.baseUrl ?? "https://api.fincopy.pro").replace(/\/+$/, "");
64
89
  const base = new URL(this.baseUrl);
65
90
  if (!/^https?:$/.test(base.protocol) || base.search || base.hash) {
66
91
  throw new TypeError("baseUrl must be an absolute HTTP or HTTPS URL without a query or fragment.");
@@ -70,6 +95,7 @@ var FinHttpTransport = class {
70
95
  if (!Number.isFinite(this.timeoutMs) || this.timeoutMs <= 0) throw new RangeError("timeoutMs must be positive.");
71
96
  if (!Number.isInteger(this.maxRetries) || this.maxRetries < 0) throw new RangeError("maxRetries cannot be negative.");
72
97
  this.fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
98
+ this.credentials = options.credentials ?? (this.apiKey ? "same-origin" : "include");
73
99
  this.delay = options.retryDelay ?? ((milliseconds, signal) => new Promise((resolve, reject) => {
74
100
  if (signal?.aborted) {
75
101
  reject(signal.reason);
@@ -112,14 +138,16 @@ var FinHttpTransport = class {
112
138
  let response;
113
139
  let raw;
114
140
  try {
115
- const headers = new Headers({ "X-Api-Key": this.apiKey, Accept: "application/json" });
141
+ const headers = new Headers({ Accept: "application/json" });
142
+ if (this.apiKey) headers.set("X-Api-Key", this.apiKey);
116
143
  if (bodyText !== void 0) headers.set("Content-Type", "application/json");
117
144
  if (idempotencyKey !== void 0) headers.set("Idempotency-Key", idempotencyKey);
118
145
  response = await this.fetcher(url, {
119
146
  method: verb,
120
147
  headers,
121
148
  body: bodyText,
122
- signal: controller.signal
149
+ signal: controller.signal,
150
+ credentials: this.credentials
123
151
  });
124
152
  raw = await response.text();
125
153
  } catch (error) {
@@ -184,6 +212,79 @@ var FinHttpTransport = class {
184
212
  chksum: envelope.chksum ?? null
185
213
  };
186
214
  }
215
+ /** Reads the event stream until the server closes it or the caller aborts. It does not reconnect. */
216
+ async *requestEvents(path, requestOptions = {}) {
217
+ const url = new URL(path.replace(/^\//, ""), `${this.baseUrl}/`);
218
+ const headers = new Headers({ Accept: "text/event-stream" });
219
+ if (this.apiKey) headers.set("X-Api-Key", this.apiKey);
220
+ let response;
221
+ try {
222
+ response = await this.fetcher(url, {
223
+ method: "GET",
224
+ headers,
225
+ signal: requestOptions.signal,
226
+ credentials: this.credentials
227
+ });
228
+ } catch (error) {
229
+ if (requestOptions.signal?.aborted) throw error;
230
+ throw new FinApiError(0, "The FinCopy event stream could not be opened.", null, [], { errorCode: "network", cause: error });
231
+ }
232
+ if (!response.ok) {
233
+ const raw = await response.text();
234
+ let envelope = null;
235
+ try {
236
+ envelope = raw ? JSON.parse(raw) : null;
237
+ } catch {
238
+ }
239
+ const fallback = `The FinCopy API request failed with HTTP ${response.status}.`;
240
+ throw new FinApiError(
241
+ response.status,
242
+ envelope?.message || fallback,
243
+ envelope?.code ?? null,
244
+ errorsOf(envelope?.errors),
245
+ {
246
+ errorCode: response.status === 429 ? "rate_limited" : null,
247
+ retryAfterMs: retryAfterMsOf(response.headers.get("Retry-After"))
248
+ }
249
+ );
250
+ }
251
+ if (!response.body) throw new FinApiError(response.status, "The FinCopy API returned an empty event stream.", null, [], { errorCode: "empty_response" });
252
+ const reader = response.body.getReader();
253
+ const decoder = new TextDecoder();
254
+ const parser = new FinSseParser();
255
+ let buffer = "";
256
+ try {
257
+ while (true) {
258
+ if (requestOptions.signal?.aborted) throw requestOptions.signal.reason;
259
+ let next;
260
+ try {
261
+ next = await reader.read();
262
+ } catch (error) {
263
+ if (requestOptions.signal?.aborted) throw error;
264
+ throw new FinApiError(0, "The FinCopy event stream was interrupted.", null, [], { errorCode: "network", cause: error });
265
+ }
266
+ buffer += decoder.decode(next.value, { stream: !next.done });
267
+ const lines = buffer.split(/\r?\n/);
268
+ buffer = lines.pop() ?? "";
269
+ for (const line of lines) {
270
+ const item = parser.add(line);
271
+ if (item) yield item;
272
+ }
273
+ if (next.done) {
274
+ if (buffer) {
275
+ const item = parser.add(buffer);
276
+ if (item) yield item;
277
+ }
278
+ const final = parser.complete();
279
+ if (final) yield final;
280
+ return;
281
+ }
282
+ }
283
+ } finally {
284
+ await reader.cancel().catch(() => void 0);
285
+ reader.releaseLock();
286
+ }
287
+ }
187
288
  backoff(retry) {
188
289
  return Math.min(maxBackoffMs, 250 * 2 ** retry * (0.75 + this.random() * 0.5));
189
290
  }
@@ -211,128 +312,192 @@ function errorsOf(errors) {
211
312
  }
212
313
  function idempotencyKeyOf(supplied) {
213
314
  const key = supplied?.trim();
214
- if (!key) return randomUUID();
315
+ if (!key) return newIdempotencyKey();
215
316
  if (key.length > 120 || /[\u0000-\u001f\u007f]/.test(key)) {
216
317
  throw new TypeError("idempotencyKey must be 1-120 characters without control characters.");
217
318
  }
218
319
  return key;
219
320
  }
321
+ function newIdempotencyKey() {
322
+ const webCrypto = globalThis.crypto;
323
+ if (typeof webCrypto?.randomUUID === "function") return webCrypto.randomUUID();
324
+ const bytes = new Uint8Array(16);
325
+ if (typeof webCrypto?.getRandomValues === "function") webCrypto.getRandomValues(bytes);
326
+ else for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
327
+ bytes[6] = bytes[6] & 15 | 64;
328
+ bytes[8] = bytes[8] & 63 | 128;
329
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
330
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
331
+ }
220
332
 
221
333
  // src/resources.ts
222
334
  function pageQuery(query = {}) {
223
335
  const params = new URLSearchParams();
224
- const scalarKeys = ["PageNo", "PageSize", "PageOff", "IsAsc", "SortCol", "SortDir", "SrchCol", "SrchVal"];
225
- for (const key of scalarKeys) {
226
- const value2 = query[key];
227
- if (value2 !== void 0) params.append(key, String(value2));
336
+ for (const key of ["PageNo", "PageSize"]) {
337
+ const value = query[key];
338
+ if (value !== void 0) params.append(key, String(value));
228
339
  }
229
340
  if (query.Search !== void 0) params.append("search", query.Search);
230
- for (const key of ["SortBy", "SrchBy", "Include"]) {
231
- for (const value2 of query[key] ?? []) params.append(key, value2);
232
- }
233
- const value = params.toString();
234
- return value ? `?${value}` : "";
341
+ for (const key of ["SortBy", "SrchBy"])
342
+ (query[key] ?? []).forEach((clause, index) => clause.forEach((value, part) => params.append(`${key}[${index}][${part}]`, value)));
343
+ for (const value of query.Include ?? []) params.append("Include", value);
344
+ return params.toString();
345
+ }
346
+ function queryPath(path, page, filters = {}) {
347
+ const params = new URLSearchParams(pageQuery(page));
348
+ for (const [key, value] of Object.entries(filters)) if (value !== void 0 && value !== null) params.set(key, String(value));
349
+ const suffix = params.toString();
350
+ return suffix ? `${path}?${suffix}` : path;
235
351
  }
236
- function accountPath(accountId) {
237
- if (!accountId?.trim()) throw new TypeError("accountId is required.");
238
- return `v1/accounts/${encodeURIComponent(accountId)}`;
352
+ function accountPath(acno) {
353
+ if (!Number.isSafeInteger(acno) || acno <= 0) throw new RangeError("acno must be a positive safe integer.");
354
+ return `v1/fxs/accounts/${acno}`;
239
355
  }
240
- function numericId(value, name) {
241
- if (!Number.isSafeInteger(value) || value < 0) throw new RangeError(`${name} must be a non-negative safe integer.`);
356
+ function numericId(value, name, allowZero = true) {
357
+ if (!Number.isSafeInteger(value) || value < (allowZero ? 0 : 1)) throw new RangeError(`${name} is out of range.`);
242
358
  return String(value);
243
359
  }
244
- function dateQuery(value) {
360
+ function dateValue(value) {
245
361
  return value instanceof Date ? value.toISOString() : value;
246
362
  }
363
+ function dateFilters(query) {
364
+ return {
365
+ fromDt: query.fromDt === void 0 ? void 0 : dateValue(query.fromDt),
366
+ toDt: query.toDt === void 0 ? void 0 : dateValue(query.toDt)
367
+ };
368
+ }
247
369
  var AccountsResource = class {
248
370
  constructor(http) {
249
371
  this.http = http;
250
372
  }
251
373
  http;
252
- /** Lists the accounts this API key can reach. */
253
- list(options = {}) {
254
- return this.http.request("GET", "v1/accounts", void 0, options);
374
+ /** Lists reachable accounts, optionally filtered by external reference. */
375
+ list(page = {}, externalRef, options = {}) {
376
+ return this.http.requestPage("GET", queryPath("v1/fxs/accounts", page, { externalRef }), options);
255
377
  }
256
- /** Adds a hosted account for the key's owner. */
378
+ /** Adds a hosted account. */
257
379
  make(command, options = {}) {
258
- return this.http.request("POST", "v1/accounts/make", command, options);
380
+ return this.http.request("POST", "v1/fxs/accounts", command, options);
381
+ }
382
+ /** Creates a demo account. */
383
+ makeDemo(command, options = {}) {
384
+ return this.http.request("POST", "v1/fxs/accounts/demo", command, options);
259
385
  }
260
- /** Reads one account and its latest state. */
261
- get(accountId, options = {}) {
262
- return this.http.request("GET", accountPath(accountId), void 0, options);
386
+ /** Reads demo availability for one platform. */
387
+ demoAvailability(platform, options = {}) {
388
+ return this.http.request("GET", queryPath("v1/fxs/accounts/demo-availability", void 0, { platform }), void 0, options);
389
+ }
390
+ /** Reads one account by ACNO. */
391
+ get(acno, options = {}) {
392
+ return this.http.request("GET", accountPath(acno), void 0, options);
263
393
  }
264
394
  /** Sets or clears the account's external reference. */
265
- setExternalRef(accountId, command, options = {}) {
266
- return this.http.request("PUT", `${accountPath(accountId)}/external-ref`, command, options);
395
+ setExternalRef(acno, command, options = {}) {
396
+ return this.http.request("PUT", `${accountPath(acno)}/external-ref`, command, options);
397
+ }
398
+ /** Reads account settings. */
399
+ getSettings(acno, options = {}) {
400
+ return this.http.request("GET", `${accountPath(acno)}/settings`, void 0, options);
401
+ }
402
+ /** Changes account settings. */
403
+ patchSettings(acno, command, options = {}) {
404
+ return this.http.request("PATCH", `${accountPath(acno)}/settings`, command, options);
405
+ }
406
+ /** Lists pairs for one account. */
407
+ pairs(acno, page = {}, search, options = {}) {
408
+ return this.http.requestPage("GET", queryPath(`${accountPath(acno)}/pairs`, page, { search }), options);
409
+ }
410
+ /** Reads one pair by PRNO. */
411
+ pair(acno, prno, options = {}) {
412
+ return this.http.request("GET", `${accountPath(acno)}/pairs/${numericId(prno, "prno")}`, void 0, options);
267
413
  }
268
- /** Reads the account's trading settings. */
269
- getTrading(accountId, options = {}) {
270
- return this.http.request("GET", `${accountPath(accountId)}/fxs`, void 0, options);
414
+ /** Changes one pair's settings. */
415
+ patchPair(acno, prno, command, options = {}) {
416
+ return this.http.request("PATCH", `${accountPath(acno)}/pairs/${numericId(prno, "prno")}`, command, options);
271
417
  }
272
- /** Changes the account's trading settings. */
273
- patchTrading(accountId, command, options = {}) {
274
- return this.http.request("PATCH", `${accountPath(accountId)}/fxs`, command, options);
418
+ /** Reads the broker symbols and enabled list. */
419
+ symbols(acno, options = {}) {
420
+ return this.http.request("GET", `${accountPath(acno)}/symbols`, void 0, options);
275
421
  }
276
- /** Lists the account's symbols and their BUY and SELL books. */
277
- listPairs(accountId, query = {}, options = {}) {
278
- return this.http.requestPage("GET", `${accountPath(accountId)}/pairs${pageQuery(query)}`, options);
422
+ /** Adds or removes enabled symbols. */
423
+ editSymbols(acno, command, options = {}) {
424
+ return this.http.request("PUT", `${accountPath(acno)}/symbols`, command, options);
279
425
  }
280
- /** Reads one symbol and its settings. */
281
- getPair(accountId, prno, options = {}) {
282
- return this.http.request("GET", `${accountPath(accountId)}/pairs/${numericId(prno, "prno")}`, void 0, options);
426
+ /** Reads a symbol's broker specification and latest quote. */
427
+ quote(acno, symbol, options = {}) {
428
+ if (!symbol.trim()) throw new TypeError("symbol is required.");
429
+ return this.http.request("GET", `${accountPath(acno)}/quotes/${encodeURIComponent(symbol)}`, void 0, options);
430
+ }
431
+ /** Lists live orders for one account. */
432
+ orders(acno, page = {}, search, options = {}) {
433
+ return this.http.requestPage("GET", queryPath(`${accountPath(acno)}/orders`, page, { search }), options);
434
+ }
435
+ /** Reads one live or settled order. */
436
+ order(acno, oid, options = {}) {
437
+ return this.http.request("GET", `${accountPath(acno)}/orders/${numericId(oid, "oid")}`, void 0, options);
283
438
  }
284
- /** Changes one symbol's settings. */
285
- patchPair(accountId, prno, command, options = {}) {
286
- return this.http.request("PATCH", `${accountPath(accountId)}/pairs/${numericId(prno, "prno")}`, command, options);
439
+ /** Lists settled orders. */
440
+ history(acno, page = {}, search, options = {}) {
441
+ return this.http.requestPage("GET", queryPath(`${accountPath(acno)}/history`, page, { search }), options);
442
+ }
443
+ /** Reads one settled order by OID. */
444
+ historyItem(acno, oid, options = {}) {
445
+ return this.http.request("GET", `${accountPath(acno)}/history/${numericId(oid, "oid")}`, void 0, options);
287
446
  }
288
447
  /** Lists HYBRID DCA proposals waiting for an answer. */
289
- dcaQueue(accountId, options = {}) {
290
- return this.http.request("GET", `${accountPath(accountId)}/dca-queue`, void 0, options);
448
+ dcaQueue(acno, options = {}) {
449
+ return this.http.request("GET", `${accountPath(acno)}/dca`, void 0, options);
291
450
  }
292
- /** Reads broker symbols and the account's enabled symbols. */
293
- symbols(accountId, options = {}) {
294
- return this.http.request("GET", `${accountPath(accountId)}/symbols`, void 0, options);
451
+ /** Lists daily performance rows. */
452
+ performance(acno, query = {}) {
453
+ return this.http.request("GET", queryPath(`${accountPath(acno)}/performance`, void 0, dateFilters(query)), void 0, query);
295
454
  }
296
- /** Adds and removes symbols from the account's enabled list. */
297
- editSymbols(accountId, command, options = {}) {
298
- return this.http.request("PUT", `${accountPath(accountId)}/symbols`, command, options);
455
+ /** Reads the account's performance window. */
456
+ performanceWindow(acno, options = {}) {
457
+ return this.http.request("GET", `${accountPath(acno)}/performance/window`, void 0, options);
299
458
  }
300
- /** Reads a symbol's broker specification and latest quote. */
301
- quote(accountId, symbol, options = {}) {
302
- if (!symbol?.trim()) throw new TypeError("symbol is required.");
303
- return this.http.request("GET", `${accountPath(accountId)}/quotes/${encodeURIComponent(symbol)}`, void 0, options);
304
- }
305
- /** Reads daily performance rows for one account and optional UTC date range. */
306
- performance(accountId, query = {}) {
307
- const params = new URLSearchParams();
308
- if (query.fromDt !== void 0) params.set("fromDt", dateQuery(query.fromDt));
309
- if (query.toDt !== void 0) params.set("toDt", dateQuery(query.toDt));
310
- const encoded = params.toString();
311
- const suffix = encoded ? `?${encoded}` : "";
312
- return this.http.request("GET", `${accountPath(accountId)}/performance${suffix}`, void 0, query);
313
- }
314
- /** Reads recent activity for one account. */
315
- activity(accountId, options = {}) {
316
- return this.http.request("GET", `${accountPath(accountId)}/activity`, void 0, options);
317
- }
318
- /** Queues a start operation for the hosted terminal. */
319
- start(accountId, options = {}) {
320
- return this.operation(accountId, "start", options);
321
- }
322
- /** Queues a stop operation for the hosted terminal. */
323
- stop(accountId, options = {}) {
324
- return this.operation(accountId, "stop", options);
325
- }
326
- /** Queues a restart operation for the hosted terminal. */
327
- restart(accountId, options = {}) {
328
- return this.operation(accountId, "restart", options);
329
- }
330
- /** Queues removal of the hosted account and its terminal. */
331
- remove(accountId, options = {}) {
332
- return this.operation(accountId, "remove", options);
333
- }
334
- operation(accountId, operation, options) {
335
- return this.http.request("POST", `${accountPath(accountId)}/${operation}`, void 0, options);
459
+ /** Reads performance bars for an optional UTC date range. */
460
+ performanceBars(acno, query = {}) {
461
+ return this.http.request("GET", queryPath(`${accountPath(acno)}/performance/bars`, void 0, dateFilters(query)), void 0, query);
462
+ }
463
+ /** Lists paged account activity. */
464
+ activity(acno, page = {}, search, options = {}) {
465
+ return this.http.requestPage("GET", queryPath(`${accountPath(acno)}/activity`, page, { search }), options);
466
+ }
467
+ /** Previews applying a strategy (the account owner's or a FinCopy preset): what each symbol would change. Nothing changes. */
468
+ previewStrategy(acno, command, options = {}) {
469
+ return this.http.request("POST", `${accountPath(acno)}/strategy/preview`, command, options);
470
+ }
471
+ /** Applies a strategy to the account and its symbols; a side holding orders keeps what it must keep. */
472
+ applyStrategy(acno, command, options = {}) {
473
+ return this.http.request("POST", `${accountPath(acno)}/strategy/apply`, command, options);
474
+ }
475
+ /** Lists recent terminal operations. */
476
+ operations(acno, page = {}, options = {}) {
477
+ return this.http.requestPage("GET", queryPath(`${accountPath(acno)}/operations`, page), options);
478
+ }
479
+ /** Queues a broker-password change. */
480
+ changePassword(acno, command, options = {}) {
481
+ return this.http.request("POST", `${accountPath(acno)}/password`, command, options);
482
+ }
483
+ /** Queues a terminal start. */
484
+ start(acno, options = {}) {
485
+ return this.operation(acno, "start", options);
486
+ }
487
+ /** Queues a terminal stop. */
488
+ stop(acno, options = {}) {
489
+ return this.operation(acno, "stop", options);
490
+ }
491
+ /** Queues a terminal restart. */
492
+ restart(acno, options = {}) {
493
+ return this.operation(acno, "restart", options);
494
+ }
495
+ /** Queues account removal. */
496
+ remove(acno, options = {}) {
497
+ return this.http.request("DELETE", accountPath(acno), void 0, options);
498
+ }
499
+ operation(acno, action, options) {
500
+ return this.http.request("POST", `${accountPath(acno)}/${action}`, void 0, options);
336
501
  }
337
502
  };
338
503
  var OrdersResource = class {
@@ -340,45 +505,110 @@ var OrdersResource = class {
340
505
  this.http = http;
341
506
  }
342
507
  http;
343
- /** Lists live, queued and pending orders. */
344
- list(accountId, query = {}, options = {}) {
345
- return this.http.requestPage("GET", `${accountPath(accountId)}/orders${pageQuery(query)}`, options);
508
+ /** Preflights a trade request. */
509
+ preInfo(acno, command, options = {}) {
510
+ return this.http.request("POST", `${accountPath(acno)}/trade/preinfo`, command, options);
346
511
  }
347
- /** Lists settled orders, newest first. */
348
- history(accountId, query = {}, options = {}) {
349
- return this.http.requestPage("GET", `${accountPath(accountId)}/orders/history${pageQuery(query)}`, options);
512
+ /** Sends one trade action. */
513
+ make(acno, command, options = {}) {
514
+ return this.http.request("POST", `${accountPath(acno)}/trade`, command, options);
350
515
  }
351
- /** Reads one settled order. */
352
- historyItem(accountId, oid, options = {}) {
353
- return this.http.request("GET", `${accountPath(accountId)}/orders/history/${numericId(oid, "oid")}`, void 0, options);
516
+ /** Sends paired BUY and SELL actions. */
517
+ hedge(acno, command, options = {}) {
518
+ return this.http.request("POST", `${accountPath(acno)}/trade/hedge`, command, options);
354
519
  }
355
- /** Reads one live or settled order. */
356
- get(accountId, oid, options = {}) {
357
- return this.http.request("GET", `${accountPath(accountId)}/orders/${numericId(oid, "oid")}`, void 0, options);
520
+ /** Modifies a trade or pending order. */
521
+ modify(acno, command, options = {}) {
522
+ return this.http.request("POST", `${accountPath(acno)}/trade/modify`, command, options);
358
523
  }
359
- /** Sends one FXS action. A successful response means queued for the terminal, not filled. */
360
- make(accountId, command, options = {}) {
361
- return this.http.request("POST", `${accountPath(accountId)}/orders`, command, options);
524
+ /** Cancels an order that has not reached the terminal. */
525
+ cancelWaiting(acno, command, options = {}) {
526
+ return this.http.request("POST", `${accountPath(acno)}/trade/cancel`, command, options);
362
527
  }
363
- /** Accepts or rejects one HYBRID DCA proposal. */
364
- answerDca(accountId, oid, command, options = {}) {
365
- return this.http.request("POST", `${accountPath(accountId)}/dca/${numericId(oid, "oid")}/answer`, command, options);
528
+ /** Accepts or rejects one DCA proposal. */
529
+ answerDca(acno, oid, command, options = {}) {
530
+ return this.http.request("POST", `${accountPath(acno)}/dca/${numericId(oid, "oid")}`, command, options);
366
531
  }
367
- /** Reads the quote, limits, books and settings used by the trade ticket. */
368
- preInfo(accountId, command, options = {}) {
369
- return this.http.request("POST", `${accountPath(accountId)}/orders/preinfo`, command, options);
532
+ };
533
+ var FxResource = class {
534
+ constructor(http) {
535
+ this.http = http;
370
536
  }
371
- /** Sends a BUY and SELL trade together. A successful response means queued, not filled. */
372
- hedge(accountId, command, options = {}) {
373
- return this.http.request("POST", `${accountPath(accountId)}/orders/hedge`, command, options);
537
+ http;
538
+ /** Lists pairs across reachable accounts. */
539
+ pairs(query = {}, options = {}) {
540
+ return this.http.requestPage("GET", listPath("v1/fxs/pairs", query), options);
541
+ }
542
+ /** Lists open orders across reachable accounts. */
543
+ orders(query = {}, options = {}) {
544
+ return this.http.requestPage("GET", listPath("v1/fxs/orders", query), options);
545
+ }
546
+ /** Lists settled orders across reachable accounts. */
547
+ history(query = {}, options = {}) {
548
+ return this.http.requestPage("GET", listPath("v1/fxs/history", query), options);
549
+ }
550
+ /** Lists activity across reachable accounts. */
551
+ activity(query = {}, options = {}) {
552
+ return this.http.requestPage("GET", listPath("v1/fxs/activity", query), options);
553
+ }
554
+ /** HYBRID DCA proposals waiting for an answer across reachable accounts, newest first. */
555
+ dca(acno, options = {}) {
556
+ return this.http.request("GET", queryPath("v1/fxs/dca", void 0, { acno }), void 0, options);
557
+ }
558
+ /** The newest terminal operations across reachable accounts. */
559
+ operations(page = {}, acno, options = {}) {
560
+ return this.http.requestPage("GET", queryPath("v1/fxs/operations", page, { acno }), options);
561
+ }
562
+ /** The last 30 days by currency book across reachable accounts. */
563
+ performanceWindow(query = {}) {
564
+ return this.http.request("GET", queryPath("v1/fxs/performance/window", void 0, { acno: query.acno, demo: query.demo }), void 0, query);
565
+ }
566
+ /** Daily performance bars across reachable accounts for an optional UTC date range. */
567
+ performanceBars(query = {}) {
568
+ return this.http.request("GET", queryPath(
569
+ "v1/fxs/performance/bars",
570
+ void 0,
571
+ { acno: query.acno, demo: query.demo, ...dateFilters(query) }
572
+ ), void 0, query);
573
+ }
574
+ /** Lists the strategies you can apply: your own and FinCopy's presets; with `acno`, that account owner's. */
575
+ strategies(acno, options = {}) {
576
+ return this.http.request("GET", queryPath("v1/fxs/strategies", void 0, { acno }), void 0, options);
577
+ }
578
+ /** Reads one strategy. */
579
+ strategy(isno, options = {}) {
580
+ return this.http.request("GET", strategyPath(isno), void 0, options);
581
+ }
582
+ /** Creates one of your own strategies. */
583
+ makeStrategy(command, options = {}) {
584
+ return this.http.request("POST", "v1/fxs/strategies", command, options);
585
+ }
586
+ /** Changes one of your own strategies; fields left unset keep their values. */
587
+ patchStrategy(isno, command, options = {}) {
588
+ return this.http.request("PATCH", strategyPath(isno), command, options);
589
+ }
590
+ /** Deletes one of your own strategies. */
591
+ deleteStrategy(isno, options = {}) {
592
+ return this.http.request("DELETE", strategyPath(isno), void 0, options);
593
+ }
594
+ /** Reads the signals shown for enabled symbols. */
595
+ signals(options = {}) {
596
+ return this.http.request("GET", "v1/fxs/signals", void 0, options);
597
+ }
598
+ /** Lists warning and error activity. */
599
+ alerts(page = {}, options = {}) {
600
+ return this.http.requestPage("GET", queryPath("v1/fxs/alerts", page), options);
374
601
  }
375
- /** Changes an order's TP field, SL field, expiry or pending price. */
376
- modify(accountId, command, options = {}) {
377
- return this.http.request("POST", `${accountPath(accountId)}/trades/modify`, command, options);
602
+ /**
603
+ * Opens the live event stream for reachable accounts. It does not reconnect: it ends when the server closes it (about
604
+ * every 30 minutes) or the connection breaks, so open it again in a loop, waiting a few seconds between attempts.
605
+ */
606
+ stream(options = {}) {
607
+ return this.http.requestEvents("v1/fxs/stream", options);
378
608
  }
379
- /** Cancels an order that has not yet been delivered to the terminal. */
380
- cancelWaiting(accountId, command, options = {}) {
381
- return this.http.request("POST", `${accountPath(accountId)}/trades/cancel-waiting`, command, options);
609
+ /** Searches broker servers available when adding an account. */
610
+ brokers(query, platform, demosOnly, options = {}) {
611
+ return this.http.request("GET", queryPath("v1/brokers", void 0, { Q: query, Platform: platform, DemosOnly: demosOnly }), void 0, options);
382
612
  }
383
613
  };
384
614
  var ChangesResource = class {
@@ -389,18 +619,13 @@ var ChangesResource = class {
389
619
  /** Reads one changes page using an optional cursor. */
390
620
  get(cursor, take = 500, options = {}) {
391
621
  if (!Number.isInteger(take) || take < 1 || take > 1e3) throw new RangeError("take must be between 1 and 1000.");
392
- const params = new URLSearchParams({ take: String(take) });
393
- if (cursor) params.set("cursor", cursor);
394
- return this.http.request("GET", `v1/accounts/changes?${params}`, void 0, options);
622
+ return this.http.request("GET", queryPath("v1/changes", void 0, { cursor, take }), void 0, options);
395
623
  }
396
- /**
397
- * Streams the available changes page by page, following each returned cursor. Save each page's `Cursor` after handling
398
- * its `Changes`, so a restart resumes from there.
399
- */
624
+ /** Reads changes page by page, following each cursor. */
400
625
  readPages(cursor, take = 500, signal) {
401
626
  return readChangePages((next, nextSignal) => this.page(next, take, nextSignal), cursor, signal);
402
627
  }
403
- /** Streams every currently available change, following each returned cursor. Use `readPages` to save the cursor. */
628
+ /** Streams all available changes. Use readPages to retain a resume cursor. */
404
629
  readAll(cursor, take = 500, signal) {
405
630
  return readAllChanges((next, nextSignal) => this.page(next, take, nextSignal), cursor, signal);
406
631
  }
@@ -416,21 +641,27 @@ var WebhooksResource = class {
416
641
  http;
417
642
  /** Reads this key's webhook configuration. */
418
643
  get(options = {}) {
419
- return this.http.request("GET", "v1/accounts/webhook", void 0, options);
644
+ return this.http.request("GET", "v1/webhook", void 0, options);
420
645
  }
421
- /** Sets the HTTPS destination and returns its signing secret once. */
646
+ /** Sets the webhook destination and returns its signing secret once. */
422
647
  set(command, options = {}) {
423
- return this.http.request("PUT", "v1/accounts/webhook", command, options);
648
+ return this.http.request("PUT", "v1/webhook", command, options);
424
649
  }
425
650
  /** Removes this key's webhook. */
426
651
  delete(options = {}) {
427
- return this.http.request("DELETE", "v1/accounts/webhook", void 0, options);
652
+ return this.http.request("DELETE", "v1/webhook", void 0, options);
428
653
  }
429
- /** Sends a signed test POST to this key's webhook. */
654
+ /** Sends a signed test delivery. */
430
655
  ping(options = {}) {
431
- return this.http.request("POST", "v1/accounts/webhook/ping", void 0, options);
656
+ return this.http.request("POST", "v1/webhook/ping", void 0, options);
432
657
  }
433
658
  };
659
+ function strategyPath(isno) {
660
+ return `v1/fxs/strategies/${numericId(isno, "isno")}`;
661
+ }
662
+ function listPath(path, query) {
663
+ return queryPath(path, query.page, { acno: query.acno, prno: query.prno, demo: query.demo, platform: query.platform, search: query.search });
664
+ }
434
665
 
435
666
  // src/client.ts
436
667
  var FinClient = class {
@@ -440,40 +671,19 @@ var FinClient = class {
440
671
  this.copy = {
441
672
  accounts: new AccountsResource(transport),
442
673
  orders: new OrdersResource(transport),
674
+ fx: new FxResource(transport),
443
675
  changes: new ChangesResource(transport),
444
676
  webhooks: new WebhooksResource(transport)
445
677
  };
446
678
  }
447
679
  };
448
-
449
- // src/webhook.ts
450
- import { createHmac, timingSafeEqual } from "crypto";
451
- var FinWebhook = class {
452
- static allowedSkewSeconds = 300;
453
- /** Verify X-FinCopy-Signature over the timestamp and the exact raw request body. */
454
- static verify(secret, timestamp, body, signature) {
455
- if (!secret || !signature) return false;
456
- const timestampText = String(timestamp);
457
- if (!/^\d+$/.test(timestampText)) return false;
458
- const seconds = Number(timestampText);
459
- if (!Number.isSafeInteger(seconds)) return false;
460
- const now = Math.floor(Date.now() / 1e3);
461
- if (now - seconds > this.allowedSkewSeconds || seconds - now > this.allowedSkewSeconds) return false;
462
- const suppliedHex = signature.startsWith("sha256=") ? signature.slice(7) : signature;
463
- if (!/^[a-fA-F0-9]{64}$/.test(suppliedHex)) return false;
464
- const supplied = Buffer.from(suppliedHex, "hex");
465
- const signedBody = Buffer.isBuffer(body) ? body : Buffer.from(body);
466
- const expected = createHmac("sha256", Buffer.from(secret, "utf8")).update(Buffer.from(`${timestampText}.`, "utf8")).update(signedBody).digest();
467
- return supplied.length === expected.length && timingSafeEqual(supplied, expected);
468
- }
469
- };
470
680
  export {
471
681
  AccountsResource,
472
682
  ChangesResource,
473
683
  FinApiError,
474
684
  FinClient,
475
685
  FinHttpTransport,
476
- FinWebhook,
686
+ FxResource,
477
687
  OrdersResource,
478
688
  WebhooksResource,
479
689
  readAllChanges,