@perpbrain/sdk 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +16 -2
- package/dist/cjs/card.d.ts +2 -0
- package/dist/cjs/card.js +311 -0
- package/dist/cjs/cli.d.ts +3 -0
- package/dist/cjs/cli.js +33 -0
- package/dist/cjs/guarded.d.ts +12 -0
- package/dist/cjs/guarded.js +52 -0
- package/dist/cjs/guards.d.ts +154 -0
- package/dist/cjs/guards.js +855 -0
- package/dist/cjs/index.d.ts +15 -0
- package/dist/cjs/index.js +56 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/receipt.d.ts +13 -0
- package/dist/cjs/receipt.js +660 -0
- package/dist/cjs/study.d.ts +29 -0
- package/dist/cjs/study.js +259 -0
- package/dist/cjs/vendor/costs.d.ts +64 -0
- package/dist/cjs/vendor/costs.js +247 -0
- package/dist/cjs/vendor/execution.d.ts +44 -0
- package/dist/cjs/vendor/execution.js +132 -0
- package/dist/cjs/vendor/fees.d.ts +17 -0
- package/dist/cjs/vendor/fees.js +82 -0
- package/dist/cjs/vendor/funding_adapter.d.ts +11 -0
- package/dist/cjs/vendor/funding_adapter.js +33 -0
- package/dist/cjs/vendor/info.d.ts +24 -0
- package/dist/cjs/vendor/info.js +55 -0
- package/dist/cjs/vendor/queries.d.ts +69 -0
- package/dist/cjs/vendor/queries.js +210 -0
- package/dist/cjs/vendor/rateLimit.d.ts +14 -0
- package/dist/cjs/vendor/rateLimit.js +57 -0
- package/dist/cjs/vendor/simDefaults.d.ts +31 -0
- package/dist/cjs/vendor/simDefaults.js +49 -0
- package/dist/cjs/vendor/simulate.d.ts +130 -0
- package/dist/cjs/vendor/simulate.js +610 -0
- package/dist/esm/card.d.ts +2 -0
- package/dist/esm/card.js +308 -0
- package/dist/esm/cli.d.ts +3 -0
- package/dist/esm/cli.js +31 -0
- package/dist/esm/guarded.d.ts +12 -0
- package/dist/esm/guarded.js +49 -0
- package/dist/esm/guards.d.ts +154 -0
- package/dist/esm/guards.js +841 -0
- package/dist/esm/index.d.ts +15 -0
- package/dist/esm/index.js +20 -0
- package/dist/esm/receipt.d.ts +13 -0
- package/dist/esm/receipt.js +653 -0
- package/dist/esm/study.d.ts +29 -0
- package/dist/esm/study.js +249 -0
- package/dist/esm/vendor/costs.d.ts +64 -0
- package/dist/esm/vendor/costs.js +240 -0
- package/dist/esm/vendor/execution.d.ts +44 -0
- package/dist/esm/vendor/execution.js +122 -0
- package/dist/esm/vendor/fees.d.ts +17 -0
- package/dist/esm/vendor/fees.js +74 -0
- package/dist/esm/vendor/funding_adapter.d.ts +11 -0
- package/dist/esm/vendor/funding_adapter.js +30 -0
- package/dist/esm/vendor/info.d.ts +24 -0
- package/dist/esm/vendor/info.js +49 -0
- package/dist/esm/vendor/queries.d.ts +69 -0
- package/dist/esm/vendor/queries.js +196 -0
- package/dist/esm/vendor/rateLimit.d.ts +14 -0
- package/dist/esm/vendor/rateLimit.js +53 -0
- package/dist/esm/vendor/simDefaults.d.ts +31 -0
- package/dist/esm/vendor/simDefaults.js +44 -0
- package/dist/esm/vendor/simulate.d.ts +130 -0
- package/dist/esm/vendor/simulate.js +605 -0
- package/package.json +64 -4
|
@@ -0,0 +1,605 @@
|
|
|
1
|
+
/** Honest simulator. Decisions use a closed bar. Fills use the next bar and the book. */
|
|
2
|
+
import { executionCost } from "./costs.js";
|
|
3
|
+
import { applySlippageFloor, bookLabels, checkBookTime, minStopBps, minTakerBps, normalizedExecution, volatilityScale, } from "./execution.js";
|
|
4
|
+
import { feeAmount, feeSchedule, feeScheduleAtTime, formatDecimal, parseDecimal, } from "./fees.js";
|
|
5
|
+
import { CURRENT_SIM_DEFAULTS, FEE_VERSION_AUTO_BY_TIME, simDefaults } from "./simDefaults.js";
|
|
6
|
+
export function fundingGridTime(stamp, interval) {
|
|
7
|
+
return Math.floor(stamp / interval) * interval;
|
|
8
|
+
}
|
|
9
|
+
export const NOT_MODELLED = "NOT_MODELLED";
|
|
10
|
+
export const HL_FUNDING_INTERVAL_MS = 3_600_000;
|
|
11
|
+
export function simulate(market, decision, bars, book, feeVersion = null, guard = null, guardContext = null, funding = null, fundingIntervalMs = HL_FUNDING_INTERVAL_MS, execution = null, atrAtDecision = null, minStopAtrMultiple = "1.0", simDefaultsProfile = CURRENT_SIM_DEFAULTS) {
|
|
12
|
+
if (market === "") {
|
|
13
|
+
throw new Error("market is required");
|
|
14
|
+
}
|
|
15
|
+
const interval = fundingInterval(fundingIntervalMs);
|
|
16
|
+
const execCfg = normalizedExecution(execution);
|
|
17
|
+
const warnings = [];
|
|
18
|
+
const labels = bookLabels(book);
|
|
19
|
+
const defaults = simDefaults(simDefaultsProfile);
|
|
20
|
+
const schedule = feeSchedule(feeVersion === FEE_VERSION_AUTO_BY_TIME ? null : feeVersion);
|
|
21
|
+
const size = positive(decision.size, "size");
|
|
22
|
+
if (decision.barIndex < 0 || decision.barIndex >= bars.length) {
|
|
23
|
+
throw new Error("decision bar is out of range");
|
|
24
|
+
}
|
|
25
|
+
checkSide(decision.side);
|
|
26
|
+
const entryKind = entryKindOf(decision);
|
|
27
|
+
const entryStop = entryStopOf(decision, entryKind);
|
|
28
|
+
const atr = optionalAtr(atrAtDecision, minStopAtrMultiple);
|
|
29
|
+
const result = emptyResult(market, schedule.version, schedule.takerBps, schedule.makerBps, size, interval);
|
|
30
|
+
const entryPlan = findEntry(decision.side, entryKind, entryStop, bars, decision.barIndex);
|
|
31
|
+
if (entryPlan === null) {
|
|
32
|
+
return finish(result, book, labels, warnings);
|
|
33
|
+
}
|
|
34
|
+
const entryIndex = entryPlan.index;
|
|
35
|
+
const entrySide = orderSide(decision.side, false);
|
|
36
|
+
const anchor = entryPlan.anchor;
|
|
37
|
+
const entryRequested = legLiquidity(decision, "entry");
|
|
38
|
+
const walked = entryLegs(entryRequested, entrySide, size, anchor, book);
|
|
39
|
+
const filled = size - walked.unfilled;
|
|
40
|
+
result.unfilledEntry = formatDecimal(walked.unfilled);
|
|
41
|
+
if (filled <= 0n) {
|
|
42
|
+
return finish(result, book, labels, warnings);
|
|
43
|
+
}
|
|
44
|
+
const entryBar = bars[entryIndex];
|
|
45
|
+
if (entryBar !== undefined) {
|
|
46
|
+
checkBookTime(book, entryBar, execCfg, warnings);
|
|
47
|
+
}
|
|
48
|
+
const entryLegsFloored = slippageFloor(execCfg, defaults, walked.liquidity, entryPlan.reason, entrySide, anchor, walked.legs, entryBar);
|
|
49
|
+
const entrySchedule = scheduleForFill(feeVersion, entryBar, defaults);
|
|
50
|
+
const entry = fill("entry", entrySide, entryPlan.reason, anchor, entryLegsFloored, entrySchedule, walked.liquidity, defaults.per_fill_fees, recordedStopFloor(execCfg, defaults, entryPlan.reason));
|
|
51
|
+
applySchedule(result, entrySchedule);
|
|
52
|
+
if (atr !== null && entryStop !== null) {
|
|
53
|
+
requireStopAtr(entry, entryStop, atr);
|
|
54
|
+
}
|
|
55
|
+
const entryBlocked = blocked(market, entry, guard, guardContext, true);
|
|
56
|
+
if (entryBlocked !== null) {
|
|
57
|
+
result.unfilledEntry = formatDecimal(size);
|
|
58
|
+
result.guardViolations = entryBlocked;
|
|
59
|
+
return finish(result, book, labels, warnings);
|
|
60
|
+
}
|
|
61
|
+
if (guard !== null) {
|
|
62
|
+
result.guardViolations = [];
|
|
63
|
+
}
|
|
64
|
+
result.fills.push(entry);
|
|
65
|
+
const exitPlan = findExit(decision, bars, entryIndex);
|
|
66
|
+
if (exitPlan === null) {
|
|
67
|
+
result.openSize = formatDecimal(filled);
|
|
68
|
+
chargeFunding(result, decision.side, filled, null, 0n, bars, entryIndex, funding, interval, defaults.funding_off_grid, defaults.funding_published);
|
|
69
|
+
return finish(result, book, labels, warnings);
|
|
70
|
+
}
|
|
71
|
+
const exitSide = orderSide(decision.side, true);
|
|
72
|
+
const exitRequested = legLiquidity(decision, "exit");
|
|
73
|
+
const exitWalk = entryLegs(exitRequested, exitSide, filled, exitPlan.anchor, book);
|
|
74
|
+
const exited = filled - exitWalk.unfilled;
|
|
75
|
+
if (exited <= 0n) {
|
|
76
|
+
result.openSize = formatDecimal(filled);
|
|
77
|
+
chargeFunding(result, decision.side, filled, null, 0n, bars, entryIndex, funding, interval, defaults.funding_off_grid, defaults.funding_published);
|
|
78
|
+
return finish(result, book, labels, warnings);
|
|
79
|
+
}
|
|
80
|
+
const exitBar = bars[exitPlan.index];
|
|
81
|
+
if (exitBar !== undefined) {
|
|
82
|
+
checkBookTime(book, exitBar, execCfg, warnings);
|
|
83
|
+
}
|
|
84
|
+
const exitLegsFloored = slippageFloor(execCfg, defaults, exitWalk.liquidity, exitPlan.reason, exitSide, exitPlan.anchor, exitWalk.legs, exitBar);
|
|
85
|
+
const exitSchedule = scheduleForFill(feeVersion, exitBar, defaults);
|
|
86
|
+
const exitFill = fill("exit", exitSide, exitPlan.reason, exitPlan.anchor, exitLegsFloored, exitSchedule, exitWalk.liquidity, defaults.per_fill_fees, recordedStopFloor(execCfg, defaults, exitPlan.reason));
|
|
87
|
+
if (atr !== null && exitPlan.reason === "stopped" && decision.stop !== null) {
|
|
88
|
+
requireStopAtr(exitFill, decision.stop, atr);
|
|
89
|
+
}
|
|
90
|
+
const exitBlocked = blocked(market, exitFill, guard, guardContext, false);
|
|
91
|
+
if (exitBlocked !== null) {
|
|
92
|
+
result.openSize = formatDecimal(filled);
|
|
93
|
+
result.guardViolations = exitBlocked;
|
|
94
|
+
chargeFunding(result, decision.side, filled, null, 0n, bars, entryIndex, funding, interval, defaults.funding_off_grid, defaults.funding_published);
|
|
95
|
+
return finish(result, book, labels, warnings);
|
|
96
|
+
}
|
|
97
|
+
result.fills.push(exitFill);
|
|
98
|
+
result.openSize = formatDecimal(exitWalk.unfilled);
|
|
99
|
+
chargeFunding(result, decision.side, filled, exitPlan.index, exitWalk.unfilled, bars, entryIndex, funding, interval, defaults.funding_off_grid, defaults.funding_published);
|
|
100
|
+
return finish(result, book, labels, warnings);
|
|
101
|
+
}
|
|
102
|
+
function blocked(market, order, guard, context, opening) {
|
|
103
|
+
if (guard === null) {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
const notional = notionalOf(order);
|
|
107
|
+
const intent = {
|
|
108
|
+
coin: market,
|
|
109
|
+
notionalUsd: notional,
|
|
110
|
+
leverage: context?.leverage ?? "1",
|
|
111
|
+
openPositions: context?.openPositions ?? (opening ? 1 : 0),
|
|
112
|
+
dailyLossUsd: context?.dailyLossUsd ?? "0",
|
|
113
|
+
slippageBps: slippageBps(order.slippage, notional),
|
|
114
|
+
ageMs: context?.ageMs ?? 0,
|
|
115
|
+
opening,
|
|
116
|
+
orderSide: order.side,
|
|
117
|
+
dailyLossPct: context?.dailyLossPct ?? "0",
|
|
118
|
+
nowMs: context?.nowMs ?? 0,
|
|
119
|
+
};
|
|
120
|
+
const verdict = guard(intent);
|
|
121
|
+
if (verdict.ok) {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
return [...verdict.violations];
|
|
125
|
+
}
|
|
126
|
+
function notionalOf(order) {
|
|
127
|
+
let total = 0n;
|
|
128
|
+
const scale = 10n ** 18n;
|
|
129
|
+
for (const leg of order.legs) {
|
|
130
|
+
total += (parseDecimal(leg.size) * parseDecimal(leg.price)) / scale;
|
|
131
|
+
}
|
|
132
|
+
return formatDecimal(total);
|
|
133
|
+
}
|
|
134
|
+
function slippageBps(slippage, notional) {
|
|
135
|
+
const notion = parseDecimal(notional);
|
|
136
|
+
if (notion === 0n) {
|
|
137
|
+
return "0";
|
|
138
|
+
}
|
|
139
|
+
const scale = 10n ** 18n;
|
|
140
|
+
return formatDecimal((parseDecimal(slippage) * 10000n * scale) / notion);
|
|
141
|
+
}
|
|
142
|
+
function emptyResult(market, version, takerBps, makerBps, size, interval) {
|
|
143
|
+
return {
|
|
144
|
+
label: "SIMULATED",
|
|
145
|
+
market,
|
|
146
|
+
fills: [],
|
|
147
|
+
fillSource: "exchange",
|
|
148
|
+
feeVersion: version,
|
|
149
|
+
takerBps,
|
|
150
|
+
makerBps,
|
|
151
|
+
fundingIntervalMs: interval,
|
|
152
|
+
fundingPayments: [],
|
|
153
|
+
unfilledEntry: formatDecimal(size),
|
|
154
|
+
openSize: "0",
|
|
155
|
+
queue_position: NOT_MODELLED,
|
|
156
|
+
liquidation: NOT_MODELLED,
|
|
157
|
+
cost_breakdown: executionCost({ fills: [], fundingPayments: [] }, { bids: [], asks: [] }),
|
|
158
|
+
receipt: {
|
|
159
|
+
fills: [],
|
|
160
|
+
funding_payments: [],
|
|
161
|
+
queue_position: NOT_MODELLED,
|
|
162
|
+
liquidation: NOT_MODELLED,
|
|
163
|
+
cost_breakdown: executionCost({ fills: [], fundingPayments: [] }, { bids: [], asks: [] }),
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
function finish(result, book, labels, warnings) {
|
|
168
|
+
result.queue_position = NOT_MODELLED;
|
|
169
|
+
result.liquidation = NOT_MODELLED;
|
|
170
|
+
if (labels.length > 0) {
|
|
171
|
+
result.simLabels = labels;
|
|
172
|
+
}
|
|
173
|
+
if (warnings.length > 0) {
|
|
174
|
+
result.simWarnings = warnings;
|
|
175
|
+
}
|
|
176
|
+
const breakdown = executionCost(result, book);
|
|
177
|
+
result.cost_breakdown = breakdown;
|
|
178
|
+
result.receipt = {
|
|
179
|
+
fills: [...result.fills],
|
|
180
|
+
funding_payments: [...result.fundingPayments],
|
|
181
|
+
queue_position: NOT_MODELLED,
|
|
182
|
+
liquidation: NOT_MODELLED,
|
|
183
|
+
cost_breakdown: breakdown,
|
|
184
|
+
};
|
|
185
|
+
return result;
|
|
186
|
+
}
|
|
187
|
+
function scheduleForFill(feeVersion, bar, defaults) {
|
|
188
|
+
const byTime = feeVersion === FEE_VERSION_AUTO_BY_TIME || (feeVersion === null && defaults.fee_when_unset === "by_time");
|
|
189
|
+
if (!byTime) {
|
|
190
|
+
return feeSchedule(feeVersion);
|
|
191
|
+
}
|
|
192
|
+
const stamp = bar?.timeMs;
|
|
193
|
+
if (stamp !== undefined && Number.isInteger(stamp) && stamp >= 0) {
|
|
194
|
+
return feeScheduleAtTime(stamp);
|
|
195
|
+
}
|
|
196
|
+
return feeSchedule(null);
|
|
197
|
+
}
|
|
198
|
+
function applySchedule(result, schedule) {
|
|
199
|
+
result.feeVersion = schedule.version;
|
|
200
|
+
result.takerBps = schedule.takerBps;
|
|
201
|
+
result.makerBps = schedule.makerBps;
|
|
202
|
+
}
|
|
203
|
+
function slippageFloor(config, defaults, liquidity, reason, side, anchor, legs, bar) {
|
|
204
|
+
const vol = volatilityScale(config);
|
|
205
|
+
if (STOP_FLOOR_REASONS.has(reason)) {
|
|
206
|
+
return applySlippageFloor(side, anchor, legs, minStopBps(config, defaults.min_stop_slippage_bps), bar ?? null, vol);
|
|
207
|
+
}
|
|
208
|
+
if (liquidity === "taker") {
|
|
209
|
+
return applySlippageFloor(side, anchor, legs, minTakerBps(config), bar ?? null, vol);
|
|
210
|
+
}
|
|
211
|
+
return legs;
|
|
212
|
+
}
|
|
213
|
+
const STOP_FLOOR_REASONS = new Set(["stopped", "stop"]);
|
|
214
|
+
/** Stop floor applied to a fill, recorded on receipt v4+ fills (null before). */
|
|
215
|
+
function recordedStopFloor(config, defaults, reason) {
|
|
216
|
+
if (!defaults.record_stop_floor) {
|
|
217
|
+
return null;
|
|
218
|
+
}
|
|
219
|
+
if (STOP_FLOOR_REASONS.has(reason)) {
|
|
220
|
+
return formatDecimal(parseDecimal(minStopBps(config, defaults.min_stop_slippage_bps)));
|
|
221
|
+
}
|
|
222
|
+
return "0";
|
|
223
|
+
}
|
|
224
|
+
function fill(kind, side, reason, anchor, legs, schedule, liquidity, perFillFees = true, stopFloorBps = null) {
|
|
225
|
+
let filled = 0n;
|
|
226
|
+
let notional = 0n;
|
|
227
|
+
let slippage = 0n;
|
|
228
|
+
const scale = 10n ** 18n;
|
|
229
|
+
for (const leg of legs) {
|
|
230
|
+
filled += leg.qty;
|
|
231
|
+
notional += (leg.qty * leg.px) / scale;
|
|
232
|
+
slippage += side === "buy" ? ((leg.px - anchor) * leg.qty) / scale : ((anchor - leg.px) * leg.qty) / scale;
|
|
233
|
+
}
|
|
234
|
+
const price = filled === 0n ? 0n : (notional * scale) / filled;
|
|
235
|
+
const bps = liquidity === "maker" ? schedule.makerBps : schedule.takerBps;
|
|
236
|
+
const row = {
|
|
237
|
+
kind,
|
|
238
|
+
side,
|
|
239
|
+
size: formatDecimal(filled),
|
|
240
|
+
price: formatDecimal(price),
|
|
241
|
+
fee: formatDecimal(feeAmount(notional, bps)),
|
|
242
|
+
slippage: formatDecimal(slippage),
|
|
243
|
+
reason,
|
|
244
|
+
legs: legs.map((leg) => ({ size: formatDecimal(leg.qty), price: formatDecimal(leg.px) })),
|
|
245
|
+
liquidity,
|
|
246
|
+
queue_position: NOT_MODELLED,
|
|
247
|
+
liquidation: NOT_MODELLED,
|
|
248
|
+
};
|
|
249
|
+
if (perFillFees) {
|
|
250
|
+
row.fee_version = schedule.version;
|
|
251
|
+
row.taker_bps = schedule.takerBps;
|
|
252
|
+
row.maker_bps = schedule.makerBps;
|
|
253
|
+
}
|
|
254
|
+
if (stopFloorBps !== null) {
|
|
255
|
+
row.stop_floor_bps = stopFloorBps;
|
|
256
|
+
}
|
|
257
|
+
return row;
|
|
258
|
+
}
|
|
259
|
+
function walk(side, size, anchor, levels) {
|
|
260
|
+
let remaining = size;
|
|
261
|
+
const legs = [];
|
|
262
|
+
for (const level of levels) {
|
|
263
|
+
if (remaining <= 0n) {
|
|
264
|
+
break;
|
|
265
|
+
}
|
|
266
|
+
const available = decimal(level.sz, "level size");
|
|
267
|
+
if (available < 0n) {
|
|
268
|
+
throw new Error("level size must be positive");
|
|
269
|
+
}
|
|
270
|
+
if (available === 0n) {
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
const qty = remaining < available ? remaining : available;
|
|
274
|
+
const levelPx = decimal(level.px, "level price");
|
|
275
|
+
const px = side === "buy" ? max(levelPx, anchor) : min(levelPx, anchor);
|
|
276
|
+
legs.push({ qty, px });
|
|
277
|
+
remaining -= qty;
|
|
278
|
+
}
|
|
279
|
+
return { legs, unfilled: remaining };
|
|
280
|
+
}
|
|
281
|
+
function findExit(decision, bars, start) {
|
|
282
|
+
const stop = decision.stop === null ? null : decimal(decision.stop, "stop");
|
|
283
|
+
const target = decision.target === null ? null : decimal(decision.target, "target");
|
|
284
|
+
for (let index = start; index < bars.length; index += 1) {
|
|
285
|
+
const bar = bars[index];
|
|
286
|
+
if (bar === undefined) {
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
const plan = barExit(decision.side, decimal(bar.open, "open"), decimal(bar.high, "high"), decimal(bar.low, "low"), stop, target);
|
|
290
|
+
if (plan !== null) {
|
|
291
|
+
return { ...plan, index };
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
return null;
|
|
295
|
+
}
|
|
296
|
+
function barExit(side, opened, high, low, stop, target) {
|
|
297
|
+
switch (side) {
|
|
298
|
+
case "long": {
|
|
299
|
+
if (stop !== null && low <= stop) {
|
|
300
|
+
return { reason: "stopped", anchor: opened <= stop ? opened : stop };
|
|
301
|
+
}
|
|
302
|
+
if (target !== null && high >= target) {
|
|
303
|
+
return { reason: "target", anchor: opened >= target ? opened : target };
|
|
304
|
+
}
|
|
305
|
+
return null;
|
|
306
|
+
}
|
|
307
|
+
case "short": {
|
|
308
|
+
if (stop !== null && high >= stop) {
|
|
309
|
+
return { reason: "stopped", anchor: opened >= stop ? opened : stop };
|
|
310
|
+
}
|
|
311
|
+
if (target !== null && low <= target) {
|
|
312
|
+
return { reason: "target", anchor: opened <= target ? opened : target };
|
|
313
|
+
}
|
|
314
|
+
return null;
|
|
315
|
+
}
|
|
316
|
+
default: {
|
|
317
|
+
const unexpected = side;
|
|
318
|
+
throw new Error(`unexpected side ${String(unexpected)}`);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
function orderSide(side, closing) {
|
|
323
|
+
switch (side) {
|
|
324
|
+
case "long":
|
|
325
|
+
return closing ? "sell" : "buy";
|
|
326
|
+
case "short":
|
|
327
|
+
return closing ? "buy" : "sell";
|
|
328
|
+
default: {
|
|
329
|
+
const unexpected = side;
|
|
330
|
+
throw new Error(`unexpected side ${String(unexpected)}`);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
function bookSide(book, side) {
|
|
335
|
+
switch (side) {
|
|
336
|
+
case "buy":
|
|
337
|
+
return book.asks;
|
|
338
|
+
case "sell":
|
|
339
|
+
return book.bids;
|
|
340
|
+
default: {
|
|
341
|
+
const unexpected = side;
|
|
342
|
+
throw new Error(`unexpected side ${String(unexpected)}`);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
function checkSide(side) {
|
|
347
|
+
if (side !== "long" && side !== "short") {
|
|
348
|
+
throw new Error("side must be long or short");
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
function decimal(value, label) {
|
|
352
|
+
try {
|
|
353
|
+
return parseDecimal(value);
|
|
354
|
+
}
|
|
355
|
+
catch {
|
|
356
|
+
throw new Error(`${label} must be a decimal`);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
function positive(value, label) {
|
|
360
|
+
const parsed = decimal(value, label);
|
|
361
|
+
if (parsed <= 0n) {
|
|
362
|
+
throw new Error(`${label} must be positive`);
|
|
363
|
+
}
|
|
364
|
+
return parsed;
|
|
365
|
+
}
|
|
366
|
+
function max(left, right) {
|
|
367
|
+
return left > right ? left : right;
|
|
368
|
+
}
|
|
369
|
+
function min(left, right) {
|
|
370
|
+
return left < right ? left : right;
|
|
371
|
+
}
|
|
372
|
+
function legLiquidity(decision, leg) {
|
|
373
|
+
const raw = leg === "entry"
|
|
374
|
+
? (decision.entryLiquidity ?? decision.liquidity ?? "taker")
|
|
375
|
+
: (decision.exitLiquidity ?? decision.liquidity ?? "taker");
|
|
376
|
+
if (raw === "taker" || raw === "maker") {
|
|
377
|
+
return raw;
|
|
378
|
+
}
|
|
379
|
+
throw new Error("liquidity must be taker or maker");
|
|
380
|
+
}
|
|
381
|
+
function entryLegs(requested, side, size, anchor, book) {
|
|
382
|
+
if (requested === "maker" && !crosses(side, anchor, book)) {
|
|
383
|
+
const passive = side === "buy" ? book.bids : book.asks;
|
|
384
|
+
const rested = rest(size, anchor, passive);
|
|
385
|
+
return { ...rested, liquidity: "maker" };
|
|
386
|
+
}
|
|
387
|
+
const taken = walk(side, size, anchor, bookSide(book, side));
|
|
388
|
+
return { ...taken, liquidity: "taker" };
|
|
389
|
+
}
|
|
390
|
+
function crosses(side, anchor, book) {
|
|
391
|
+
const opposite = bookSide(book, side);
|
|
392
|
+
if (opposite.length === 0) {
|
|
393
|
+
return false;
|
|
394
|
+
}
|
|
395
|
+
const prices = opposite.map((level) => decimal(level.px, "level price"));
|
|
396
|
+
if (side === "buy") {
|
|
397
|
+
return anchor >= prices.reduce((best, price) => min(best, price));
|
|
398
|
+
}
|
|
399
|
+
return anchor <= prices.reduce((best, price) => max(best, price));
|
|
400
|
+
}
|
|
401
|
+
function rest(size, anchor, levels) {
|
|
402
|
+
let remaining = size;
|
|
403
|
+
const legs = [];
|
|
404
|
+
for (const level of levels) {
|
|
405
|
+
if (remaining <= 0n) {
|
|
406
|
+
break;
|
|
407
|
+
}
|
|
408
|
+
const available = decimal(level.sz, "level size");
|
|
409
|
+
if (available < 0n) {
|
|
410
|
+
throw new Error("level size must be positive");
|
|
411
|
+
}
|
|
412
|
+
const levelPx = decimal(level.px, "level price");
|
|
413
|
+
if (levelPx !== anchor || available === 0n) {
|
|
414
|
+
continue;
|
|
415
|
+
}
|
|
416
|
+
const qty = remaining < available ? remaining : available;
|
|
417
|
+
legs.push({ qty, px: levelPx });
|
|
418
|
+
remaining -= qty;
|
|
419
|
+
}
|
|
420
|
+
return { legs, unfilled: remaining };
|
|
421
|
+
}
|
|
422
|
+
function fundingInterval(value) {
|
|
423
|
+
if (!Number.isInteger(value) || value <= 0) {
|
|
424
|
+
throw new Error("funding_interval_ms must be a positive integer");
|
|
425
|
+
}
|
|
426
|
+
return value;
|
|
427
|
+
}
|
|
428
|
+
function chargeFunding(result, side, filled, exitIndex, exitLeft, bars, entryIndex, funding, interval, offGrid, publishedRule) {
|
|
429
|
+
if (funding === null || funding.length === 0) {
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
const entryTime = timeMs(bars[entryIndex]);
|
|
433
|
+
const last = bars[bars.length - 1];
|
|
434
|
+
if (last === undefined) {
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
const lastTime = timeMs(last);
|
|
438
|
+
const segments = [];
|
|
439
|
+
if (exitIndex === null) {
|
|
440
|
+
segments.push({ start: entryTime, end: lastTime, size: filled });
|
|
441
|
+
}
|
|
442
|
+
else {
|
|
443
|
+
const exitTime = timeMs(bars[exitIndex]);
|
|
444
|
+
segments.push({ start: entryTime, end: exitTime, size: filled });
|
|
445
|
+
if (exitLeft > 0n && lastTime > exitTime) {
|
|
446
|
+
segments.push({ start: exitTime, end: lastTime, size: exitLeft });
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
result.fundingPayments = payments(side, segments, funding, interval, offGrid, publishedRule);
|
|
450
|
+
}
|
|
451
|
+
function payments(side, segments, funding, interval, offGrid, publishedRule) {
|
|
452
|
+
const sign = side === "long" ? -1n : 1n;
|
|
453
|
+
const seen = new Set();
|
|
454
|
+
const rows = [];
|
|
455
|
+
const ordered = [...funding].sort((left, right) => left.timeMs - right.timeMs);
|
|
456
|
+
const scale = 10n ** 18n;
|
|
457
|
+
for (const sample of ordered) {
|
|
458
|
+
if (!Number.isInteger(sample.timeMs) || sample.timeMs < 0) {
|
|
459
|
+
throw new Error("funding time_ms must be a positive integer");
|
|
460
|
+
}
|
|
461
|
+
if (offGrid === "skip" && sample.timeMs % interval !== 0) {
|
|
462
|
+
// Receipt versions 1-3 (before #18) ignored samples off the interval grid.
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
const gridTime = fundingGridTime(sample.timeMs, interval);
|
|
466
|
+
if (seen.has(gridTime)) {
|
|
467
|
+
throw new Error("duplicate funding time");
|
|
468
|
+
}
|
|
469
|
+
seen.add(gridTime);
|
|
470
|
+
const size = sizeAt(segments, gridTime);
|
|
471
|
+
if (size <= 0n) {
|
|
472
|
+
continue;
|
|
473
|
+
}
|
|
474
|
+
if (publishedRule === "charge_time") {
|
|
475
|
+
const published = publishedAt(sample);
|
|
476
|
+
if (published !== null && published > sample.timeMs) {
|
|
477
|
+
throw new Error("funding published after its charge time");
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
const rate = decimal(sample.ratePerHour, "rate_per_hour");
|
|
481
|
+
const oracle = positive(sample.oraclePxUsd, "oracle_px_usd");
|
|
482
|
+
const notion = (size * oracle) / scale;
|
|
483
|
+
const payment = (sign * notion * rate) / scale;
|
|
484
|
+
rows.push({
|
|
485
|
+
time_ms: gridTime,
|
|
486
|
+
rate_per_hour: formatDecimal(rate),
|
|
487
|
+
oracle_px_usd: formatDecimal(oracle),
|
|
488
|
+
payment_usd: formatDecimal(payment),
|
|
489
|
+
size_coin: formatDecimal(size),
|
|
490
|
+
queue_position: NOT_MODELLED,
|
|
491
|
+
liquidation: NOT_MODELLED,
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
return rows;
|
|
495
|
+
}
|
|
496
|
+
function sizeAt(segments, stamp) {
|
|
497
|
+
for (const segment of segments) {
|
|
498
|
+
if (segment.start < stamp && stamp <= segment.end && segment.size > 0n) {
|
|
499
|
+
return segment.size;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
return 0n;
|
|
503
|
+
}
|
|
504
|
+
function timeMs(bar) {
|
|
505
|
+
if (bar === undefined || bar.timeMs === undefined || !Number.isInteger(bar.timeMs) || bar.timeMs < 0) {
|
|
506
|
+
throw new Error("bar time_ms is required when funding is set");
|
|
507
|
+
}
|
|
508
|
+
return bar.timeMs;
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* Explicit publication time, or null when the sample has none. Charging realised
|
|
512
|
+
* funding at the hour it is paid is not lookahead: the decision is fixed before the
|
|
513
|
+
* simulator runs and never reads funding. A sample that carries published_at_ms is
|
|
514
|
+
* chargeable once published_at_ms is at or before its own charge time (time_ms, the
|
|
515
|
+
* exchange settlement stamp before grid flooring). Samples without it (receipt v1/v2
|
|
516
|
+
* inputs, fundingHistory adapter output) are charged at their settlement time.
|
|
517
|
+
*/
|
|
518
|
+
function publishedAt(sample) {
|
|
519
|
+
const raw = sample.publishedAtMs;
|
|
520
|
+
if (raw === undefined) {
|
|
521
|
+
return null;
|
|
522
|
+
}
|
|
523
|
+
if (!Number.isInteger(raw) || raw < 0) {
|
|
524
|
+
throw new Error("funding published_at_ms must be a positive integer");
|
|
525
|
+
}
|
|
526
|
+
return raw;
|
|
527
|
+
}
|
|
528
|
+
function entryKindOf(decision) {
|
|
529
|
+
const raw = decision.entry ?? "market";
|
|
530
|
+
if (raw === "market" || raw === "stop") {
|
|
531
|
+
return raw;
|
|
532
|
+
}
|
|
533
|
+
throw new Error("entry must be market or stop");
|
|
534
|
+
}
|
|
535
|
+
function entryStopOf(decision, entryKind) {
|
|
536
|
+
if (entryKind === "market") {
|
|
537
|
+
return null;
|
|
538
|
+
}
|
|
539
|
+
if (decision.entryStop === null || decision.entryStop === undefined) {
|
|
540
|
+
throw new Error("entry_stop is required for a stop entry");
|
|
541
|
+
}
|
|
542
|
+
return decimal(decision.entryStop, "entry_stop");
|
|
543
|
+
}
|
|
544
|
+
function optionalAtr(atrAtDecision, minStopAtrMultiple) {
|
|
545
|
+
if (atrAtDecision === null) {
|
|
546
|
+
return null;
|
|
547
|
+
}
|
|
548
|
+
const atr = positive(atrAtDecision, "atr_at_decision");
|
|
549
|
+
const multiple = positive(minStopAtrMultiple, "min_stop_atr_multiple");
|
|
550
|
+
const scale = 10n ** 18n;
|
|
551
|
+
return (atr * multiple) / scale;
|
|
552
|
+
}
|
|
553
|
+
function requireStopAtr(order, stop, minimumDistance) {
|
|
554
|
+
const stopPx = typeof stop === "bigint" ? stop : decimal(stop, "stop");
|
|
555
|
+
const fillPx = decimal(order.price, "price");
|
|
556
|
+
const gap = fillPx >= stopPx ? fillPx - stopPx : stopPx - fillPx;
|
|
557
|
+
if (gap < minimumDistance) {
|
|
558
|
+
throw new Error("stop distance below minimum ATR multiple");
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
function findEntry(side, entryKind, entryStop, bars, decisionIndex) {
|
|
562
|
+
const start = decisionIndex + 1;
|
|
563
|
+
if (start >= bars.length) {
|
|
564
|
+
return null;
|
|
565
|
+
}
|
|
566
|
+
if (entryKind === "market") {
|
|
567
|
+
const bar = bars[start];
|
|
568
|
+
if (bar === undefined) {
|
|
569
|
+
return null;
|
|
570
|
+
}
|
|
571
|
+
return { index: start, anchor: decimal(bar.open, "open"), reason: "next_bar" };
|
|
572
|
+
}
|
|
573
|
+
if (entryStop === null) {
|
|
574
|
+
throw new Error("entry_stop is required for a stop entry");
|
|
575
|
+
}
|
|
576
|
+
for (let index = start; index < bars.length; index += 1) {
|
|
577
|
+
const bar = bars[index];
|
|
578
|
+
if (bar === undefined) {
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
const anchor = stopCrossFill(side, decimal(bar.open, "open"), decimal(bar.high, "high"), decimal(bar.low, "low"), entryStop, true);
|
|
582
|
+
if (anchor !== null) {
|
|
583
|
+
return { index, anchor, reason: "stop" };
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
return null;
|
|
587
|
+
}
|
|
588
|
+
function stopCrossFill(side, opened, high, low, stop, opening) {
|
|
589
|
+
if (opening) {
|
|
590
|
+
if (side === "long" && high >= stop) {
|
|
591
|
+
return opened >= stop ? opened : stop;
|
|
592
|
+
}
|
|
593
|
+
if (side === "short" && low <= stop) {
|
|
594
|
+
return opened <= stop ? opened : stop;
|
|
595
|
+
}
|
|
596
|
+
return null;
|
|
597
|
+
}
|
|
598
|
+
if (side === "long" && low <= stop) {
|
|
599
|
+
return opened <= stop ? opened : stop;
|
|
600
|
+
}
|
|
601
|
+
if (side === "short" && high >= stop) {
|
|
602
|
+
return opened >= stop ? opened : stop;
|
|
603
|
+
}
|
|
604
|
+
return null;
|
|
605
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,66 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@perpbrain/sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": false,
|
|
5
|
+
"publishConfig": {
|
|
6
|
+
"access": "public"
|
|
7
|
+
},
|
|
8
|
+
"description": "TypeScript SDK for PERPBRAIN read tools, simulation, and the MCP launcher. Verified and reproducible. Phase 1 has no live trading.",
|
|
9
|
+
"license": "MIT",
|
|
10
|
+
"homepage": "https://perpbrain.com/",
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "git+https://github.com/PERPBRAIN/perpbrain.git",
|
|
14
|
+
"directory": "sdk"
|
|
15
|
+
},
|
|
16
|
+
"bugs": {
|
|
17
|
+
"url": "https://github.com/PERPBRAIN/perpbrain/issues"
|
|
18
|
+
},
|
|
19
|
+
"keywords": [
|
|
20
|
+
"hyperliquid",
|
|
21
|
+
"perps",
|
|
22
|
+
"trading agent",
|
|
23
|
+
"mcp",
|
|
24
|
+
"simulation",
|
|
25
|
+
"receipts",
|
|
26
|
+
"verifiable",
|
|
27
|
+
"perpbrain"
|
|
28
|
+
],
|
|
29
|
+
"mcpName": "io.github.PERPBRAIN/perpbrain",
|
|
30
|
+
"type": "module",
|
|
31
|
+
"main": "./dist/cjs/index.js",
|
|
32
|
+
"types": "./dist/cjs/index.d.ts",
|
|
33
|
+
"engines": {
|
|
34
|
+
"node": ">=22"
|
|
35
|
+
},
|
|
36
|
+
"bin": {
|
|
37
|
+
"perpbrain-mcp": "dist/esm/cli.js"
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"dist",
|
|
41
|
+
"README.md",
|
|
42
|
+
"LICENSE"
|
|
43
|
+
],
|
|
44
|
+
"exports": {
|
|
45
|
+
".": {
|
|
46
|
+
"import": {
|
|
47
|
+
"types": "./dist/esm/index.d.ts",
|
|
48
|
+
"default": "./dist/esm/index.js"
|
|
49
|
+
},
|
|
50
|
+
"require": {
|
|
51
|
+
"types": "./dist/cjs/index.d.ts",
|
|
52
|
+
"default": "./dist/cjs/index.js"
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
"./package.json": "./package.json"
|
|
56
|
+
},
|
|
57
|
+
"scripts": {
|
|
58
|
+
"build": "node scripts/build.mjs",
|
|
59
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
60
|
+
"test": "node --experimental-strip-types --test ../ts/mcp-server/src/guards.test.ts"
|
|
61
|
+
},
|
|
62
|
+
"devDependencies": {
|
|
63
|
+
"@types/node": "22.20.5",
|
|
64
|
+
"typescript": "5.9.3"
|
|
65
|
+
}
|
|
66
|
+
}
|