@forgezero/runtime 0.1.14 → 0.1.15

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.
@@ -1,251 +0,0 @@
1
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
- }) : x)(function(x) {
4
- if (typeof require !== "undefined")
5
- return require.apply(this, arguments);
6
- throw Error('Dynamic require of "' + x + '" is not supported');
7
- });
8
-
9
- // src/finance/money.ts
10
- class MoneyError extends Error {
11
- code;
12
- constructor(code, message) {
13
- super(message);
14
- this.code = code;
15
- this.name = "MoneyError";
16
- }
17
- }
18
- var ASSETS = [
19
- { code: "USDT", decimals: 6 },
20
- { code: "USDC", decimals: 6 },
21
- { code: "BTC", decimals: 8 },
22
- { code: "ETH", decimals: 18 },
23
- { code: "BNB", decimals: 18 },
24
- { code: "EUR", decimals: 2 },
25
- { code: "USD", decimals: 2 }
26
- ];
27
- var REGISTRY = new Map(ASSETS.map((asset) => [asset.code, asset]));
28
- function defineAsset(spec) {
29
- if (spec.decimals < 0 || spec.decimals > 30 || !Number.isInteger(spec.decimals)) {
30
- throw new MoneyError("UNKNOWN_ASSET", `${spec.code}: decimals must be an integer 0–30.`);
31
- }
32
- REGISTRY.set(spec.code, spec);
33
- }
34
- function assetSpec(code) {
35
- const spec = REGISTRY.get(code);
36
- if (!spec)
37
- throw new MoneyError("UNKNOWN_ASSET", `Unknown asset "${code}". Call defineAsset first.`);
38
- return spec;
39
- }
40
- var money = (units, asset) => {
41
- assetSpec(asset);
42
- return { units, asset };
43
- };
44
- var zero = (asset) => money(0n, asset);
45
- function parseAmount(value, asset) {
46
- const spec = assetSpec(asset);
47
- const text = value.trim();
48
- if (!/^-?\d+(\.\d+)?$/.test(text)) {
49
- throw new MoneyError("NOT_FINITE", `"${value}" is not a plain decimal amount.`);
50
- }
51
- const negative = text.startsWith("-");
52
- const [whole, fraction = ""] = text.replace("-", "").split(".");
53
- if (fraction.length > spec.decimals) {
54
- throw new MoneyError("PRECISION_LOSS", `${asset} has ${spec.decimals} decimals; "${value}" has ${fraction.length}.`);
55
- }
56
- const padded = fraction.padEnd(spec.decimals, "0");
57
- const units = BigInt(whole + padded);
58
- return { units: negative ? -units : units, asset };
59
- }
60
- function formatAmount(amount, options = {}) {
61
- const spec = assetSpec(amount.asset);
62
- const negative = amount.units < 0n;
63
- const digits = (negative ? -amount.units : amount.units).toString().padStart(spec.decimals + 1, "0");
64
- const whole = digits.slice(0, digits.length - spec.decimals);
65
- let fraction = spec.decimals === 0 ? "" : digits.slice(digits.length - spec.decimals);
66
- if (options.trim && fraction)
67
- fraction = fraction.replace(/0+$/, "");
68
- return `${negative ? "-" : ""}${whole}${fraction ? `.${fraction}` : ""}`;
69
- }
70
- function sameAsset(a, b) {
71
- if (a.asset !== b.asset) {
72
- throw new MoneyError("ASSET_MISMATCH", `Cannot combine ${a.asset} and ${b.asset}.`);
73
- }
74
- }
75
- function add(a, b) {
76
- sameAsset(a, b);
77
- return { units: a.units + b.units, asset: a.asset };
78
- }
79
- function subtract(a, b) {
80
- sameAsset(a, b);
81
- return { units: a.units - b.units, asset: a.asset };
82
- }
83
- var negate = (amount) => ({ units: -amount.units, asset: amount.asset });
84
- var abs = (amount) => ({
85
- units: amount.units < 0n ? -amount.units : amount.units,
86
- asset: amount.asset
87
- });
88
- var isZero = (amount) => amount.units === 0n;
89
- var isNegative = (amount) => amount.units < 0n;
90
- function compare(a, b) {
91
- sameAsset(a, b);
92
- return a.units < b.units ? -1 : a.units > b.units ? 1 : 0;
93
- }
94
- var equals = (a, b) => a.asset === b.asset && a.units === b.units;
95
- var ROUNDING = ["down", "up", "half-up"];
96
- function divideRounded(numerator, denominator, mode) {
97
- if (denominator === 0n)
98
- throw new MoneyError("DIVIDE_BY_ZERO", "Division by zero.");
99
- const negative = numerator < 0n !== denominator < 0n;
100
- const a = numerator < 0n ? -numerator : numerator;
101
- const b = denominator < 0n ? -denominator : denominator;
102
- const quotient = a / b;
103
- const remainder = a % b;
104
- if (remainder === 0n)
105
- return negative ? -quotient : quotient;
106
- let result = quotient;
107
- if (mode === "up")
108
- result += 1n;
109
- else if (mode === "half-up" && remainder * 2n >= b)
110
- result += 1n;
111
- return negative ? -result : result;
112
- }
113
- function mulRate(amount, rate, mode = "down") {
114
- if (!/^-?\d+(\.\d+)?$/.test(rate.trim())) {
115
- throw new MoneyError("NOT_FINITE", `"${rate}" is not a plain decimal rate.`);
116
- }
117
- const [whole, fraction = ""] = rate.trim().replace("-", "").split(".");
118
- const scale = 10n ** BigInt(fraction.length);
119
- const scaled = BigInt(whole + fraction) * (rate.trim().startsWith("-") ? -1n : 1n);
120
- return { units: divideRounded(amount.units * scaled, scale, mode), asset: amount.asset };
121
- }
122
- function convert(amount, to, rate, mode = "down") {
123
- const from = assetSpec(amount.asset);
124
- const target = assetSpec(to);
125
- const asTarget = mulRate({ units: amount.units, asset: to }, rate, mode);
126
- const shift = target.decimals - from.decimals;
127
- if (shift === 0)
128
- return asTarget;
129
- if (shift > 0)
130
- return { units: asTarget.units * 10n ** BigInt(shift), asset: to };
131
- return { units: divideRounded(asTarget.units, 10n ** BigInt(-shift), mode), asset: to };
132
- }
133
- function allocate(amount, parts) {
134
- if (parts < 1)
135
- throw new MoneyError("NOT_FINITE", "Cannot allocate into fewer than one part.");
136
- const each = divideRounded(amount.units, BigInt(parts), "down");
137
- const allocated = Array.from({ length: parts }, () => each);
138
- let remainder = amount.units - each * BigInt(parts);
139
- const step = remainder < 0n ? -1n : 1n;
140
- for (let index = 0;remainder !== 0n; index = (index + 1) % parts) {
141
- allocated[index] += step;
142
- remainder -= step;
143
- }
144
- return allocated.map((units) => ({ units, asset: amount.asset }));
145
- }
146
- function toStep(amount, step, mode = "down") {
147
- const stepUnits = parseAmount(step, amount.asset).units;
148
- if (stepUnits <= 0n)
149
- throw new MoneyError("NOT_FINITE", "A step must be positive.");
150
- return { units: divideRounded(amount.units, stepUnits, mode) * stepUnits, asset: amount.asset };
151
- }
152
- var VERSION = "0.1.0";
153
-
154
- // src/finance/venues.ts
155
- var MARKET_TYPES = ["spot", "margin", "futures"];
156
- var ORDER_SIDES = ["buy", "sell"];
157
- var ORDER_TYPES = ["market", "limit", "stop-limit"];
158
- var TIME_IN_FORCE = ["gtc", "ioc", "fok"];
159
- var VENUES = [
160
- {
161
- key: "binance",
162
- label: "Binance",
163
- markets: ["spot", "margin", "futures"],
164
- rateLimit: { perMinute: 6000, counts: "weight" },
165
- clientOrderIds: true,
166
- note: "Publishes no AAAA records, so every endpoint is IPv4-only and the budget is per IP."
167
- }
168
- ];
169
- var venue = (key) => VENUES.find((entry) => entry.key === key);
170
- var venuesFor = (type) => VENUES.filter((entry) => entry.markets.includes(type));
171
- var symbolOf = (base, quote) => `${base.toUpperCase()}/${quote.toUpperCase()}`;
172
- function parseSymbol(symbol) {
173
- const [base, quote] = symbol.toUpperCase().split("/");
174
- if (!base || !quote)
175
- throw new VenueError("BAD_SYMBOL", `"${symbol}" is not BASE/QUOTE.`);
176
- return { base, quote };
177
- }
178
-
179
- class VenueError extends Error {
180
- code;
181
- constructor(code, message) {
182
- super(message);
183
- this.code = code;
184
- this.name = "VenueError";
185
- }
186
- }
187
- function notionalOf(request, market) {
188
- const price = request.price;
189
- if (!price)
190
- return parseAmount("0", market.quote);
191
- const quantity = Number(formatAmount(request.quantity));
192
- const priceText = formatAmount(price);
193
- return parseAmount((quantity * Number(priceText)).toFixed(0) === "NaN" ? "0" : String(quantity * Number(priceText)), market.quote);
194
- }
195
- function validateOrder(request, market) {
196
- const spec = venue(request.venue);
197
- if (!spec)
198
- throw new VenueError("UNKNOWN_VENUE", `Unknown venue "${request.venue}".`);
199
- if (!spec.markets.includes(request.type)) {
200
- throw new VenueError("MARKET_UNSUPPORTED", `${spec.label} does not offer ${request.type}.`);
201
- }
202
- if (market.venue !== request.venue || market.type !== request.type || market.symbol !== request.symbol) {
203
- throw new VenueError("UNKNOWN_MARKET", "The market does not describe this order.");
204
- }
205
- if (request.orderType !== "market" && !request.price) {
206
- throw new VenueError("PRICE_REQUIRED", `A ${request.orderType} order needs a price.`);
207
- }
208
- const snapped = toStep(request.quantity, market.lotStep);
209
- if (compare(snapped, request.quantity) !== 0) {
210
- throw new VenueError("LOT_STEP", `Quantity ${formatAmount(request.quantity, { trim: true })} is not a multiple of ${market.lotStep}.`);
211
- }
212
- if (request.price) {
213
- const onTick = toStep(request.price, market.tickStep);
214
- if (compare(onTick, request.price) !== 0) {
215
- throw new VenueError("TICK_STEP", `Price ${formatAmount(request.price, { trim: true })} is not a multiple of ${market.tickStep}.`);
216
- }
217
- const notional = notionalOf(request, market);
218
- if (compare(notional, parseAmount(market.minNotional, market.quote)) < 0) {
219
- throw new VenueError("MIN_NOTIONAL", `Order is worth ${formatAmount(notional, { trim: true })} ${market.quote}; the minimum is ${market.minNotional}.`);
220
- }
221
- }
222
- if (request.leverage !== undefined) {
223
- if (request.type === "spot" || market.maxLeverage === undefined) {
224
- throw new VenueError("LEVERAGE_UNSUPPORTED", `${request.type} markets have no leverage.`);
225
- }
226
- if (request.leverage < 1 || request.leverage > market.maxLeverage) {
227
- throw new VenueError("LEVERAGE_TOO_HIGH", `Leverage ${request.leverage}× exceeds the ${market.maxLeverage}× maximum on this market.`);
228
- }
229
- }
230
- }
231
- async function submitOrder(adapter, request, market) {
232
- validateOrder(request, market);
233
- return adapter.placeOrder(request, market);
234
- }
235
- var VERSION2 = "0.1.0";
236
- export {
237
- venuesFor,
238
- venue,
239
- validateOrder,
240
- symbolOf,
241
- submitOrder,
242
- parseSymbol,
243
- notionalOf,
244
- VenueError,
245
- VERSION2 as VERSION,
246
- VENUES,
247
- TIME_IN_FORCE,
248
- ORDER_TYPES,
249
- ORDER_SIDES,
250
- MARKET_TYPES
251
- };