@metamask-previews/perps-controller 24.1.0-preview-e9ac9ffe1 → 24.1.0-preview-70269bbdb
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/CHANGELOG.md +50 -0
- package/dist/PerpsController-method-action-types.d.ts +26 -1
- package/dist/PerpsController-method-action-types.d.ts.map +1 -1
- package/dist/PerpsController-method-action-types.js.map +1 -1
- package/dist/PerpsController.d.ts +20 -1
- package/dist/PerpsController.d.ts.map +1 -1
- package/dist/PerpsController.js +159 -2
- package/dist/PerpsController.js.map +1 -1
- package/dist/constants/eventNames.d.ts +0 -6
- package/dist/constants/eventNames.d.ts.map +1 -1
- package/dist/constants/eventNames.js +0 -13
- package/dist/constants/eventNames.js.map +1 -1
- package/dist/constants/hyperLiquidConfig.d.ts +19 -3
- package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
- package/dist/constants/hyperLiquidConfig.js +21 -5
- package/dist/constants/hyperLiquidConfig.js.map +1 -1
- package/dist/constants/performanceMetrics.d.ts +2 -14
- package/dist/constants/performanceMetrics.d.ts.map +1 -1
- package/dist/constants/performanceMetrics.js +1 -17
- package/dist/constants/performanceMetrics.js.map +1 -1
- package/dist/constants/perpsConfig.d.ts +27 -0
- package/dist/constants/perpsConfig.d.ts.map +1 -1
- package/dist/constants/perpsConfig.js +27 -0
- package/dist/constants/perpsConfig.js.map +1 -1
- package/dist/index.d.ts +7 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/perpsErrorCodes.d.ts +2 -0
- package/dist/perpsErrorCodes.d.ts.map +1 -1
- package/dist/perpsErrorCodes.js +2 -0
- package/dist/perpsErrorCodes.js.map +1 -1
- package/dist/providers/HyperLiquidProvider.d.ts +7 -3
- package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
- package/dist/providers/HyperLiquidProvider.js +161 -103
- package/dist/providers/HyperLiquidProvider.js.map +1 -1
- package/dist/providers/LighterProvider.d.ts +3 -3
- package/dist/providers/LighterProvider.d.ts.map +1 -1
- package/dist/providers/LighterProvider.js +20 -9
- package/dist/providers/LighterProvider.js.map +1 -1
- package/dist/services/TerminalMarketService.d.ts.map +1 -1
- package/dist/services/TerminalMarketService.js +4 -2
- package/dist/services/TerminalMarketService.js.map +1 -1
- package/dist/services/TradingService.js +11 -9
- package/dist/services/TradingService.js.map +1 -1
- package/dist/types/index.d.ts +107 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js +0 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/advancedOrderLists.d.ts +104 -0
- package/dist/utils/advancedOrderLists.d.ts.map +1 -0
- package/dist/utils/advancedOrderLists.js +421 -0
- package/dist/utils/advancedOrderLists.js.map +1 -0
- package/dist/utils/advancedOrders.d.ts +275 -0
- package/dist/utils/advancedOrders.d.ts.map +1 -0
- package/dist/utils/advancedOrders.js +639 -0
- package/dist/utils/advancedOrders.js.map +1 -0
- package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
- package/dist/utils/hyperLiquidAdapter.js +4 -1
- package/dist/utils/hyperLiquidAdapter.js.map +1 -1
- package/dist/utils/hyperLiquidValidation.d.ts.map +1 -1
- package/dist/utils/hyperLiquidValidation.js +22 -57
- package/dist/utils/hyperLiquidValidation.js.map +1 -1
- package/dist/utils/index.d.ts +2 -0
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +2 -0
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/lighterScaleOrders.d.ts.map +1 -1
- package/dist/utils/lighterScaleOrders.js +16 -65
- package/dist/utils/lighterScaleOrders.js.map +1 -1
- package/dist/utils/perpsFormatters.d.ts +29 -4
- package/dist/utils/perpsFormatters.d.ts.map +1 -1
- package/dist/utils/perpsFormatters.js +51 -5
- package/dist/utils/perpsFormatters.js.map +1 -1
- package/docs/README.md +28 -0
- package/docs/architecture.md +256 -0
- package/docs/contracts/events.md +267 -0
- package/docs/contracts/feature-flags.md +39 -0
- package/docs/contracts/traces.md +83 -0
- package/docs/formatting.md +82 -0
- package/docs/tpsl.md +89 -0
- package/docs/venues/hyperliquid/README.md +27 -0
- package/docs/venues/hyperliquid/init-flow.md +116 -0
- package/docs/venues/hyperliquid/order-types.md +60 -0
- package/docs/venues/hyperliquid/trading-rules.md +77 -0
- package/docs/venues/lighter/api-keys.md +58 -0
- package/docs/venues/lighter/capabilities.md +74 -0
- package/package.json +4 -3
|
@@ -0,0 +1,639 @@
|
|
|
1
|
+
import { BigNumber } from 'bignumber.js';
|
|
2
|
+
import { BASIS_POINTS_DIVISOR } from '../constants/hyperLiquidConfig.js';
|
|
3
|
+
import { CHASE_ORDER_CONFIG, CHASE_ORDER_STATUS, ORDER_PRICE_WARNING_CONFIG, } from '../constants/perpsConfig.js';
|
|
4
|
+
import { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';
|
|
5
|
+
import { splitScaleSizes } from './orderCalculations.js';
|
|
6
|
+
const SECONDS_PER_MINUTE = 60;
|
|
7
|
+
const PERCENT_PER_RATIO = 100;
|
|
8
|
+
/**
|
|
9
|
+
* The venue's rules for one strategy on a market, read from the result of
|
|
10
|
+
* `getOrderCapabilities`.
|
|
11
|
+
*
|
|
12
|
+
* @param capabilities - Order capabilities of the market.
|
|
13
|
+
* @param strategy - Strategy whose rules are wanted.
|
|
14
|
+
* @returns The rules, or `undefined` when the market is unavailable, the
|
|
15
|
+
* venue does not run that strategy there, or it does not report the rules.
|
|
16
|
+
*/
|
|
17
|
+
export function getStrategyRules(capabilities, strategy) {
|
|
18
|
+
if (capabilities?.status !== 'ready' ||
|
|
19
|
+
!capabilities.supportedStrategies.includes(strategy)) {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
return capabilities.strategyRules?.[strategy];
|
|
23
|
+
}
|
|
24
|
+
// ---------------------------------------------------------------------------
|
|
25
|
+
// TWAP
|
|
26
|
+
// ---------------------------------------------------------------------------
|
|
27
|
+
/** TWAP statuses that mean the schedule is still executing. */
|
|
28
|
+
export const TWAP_ORDER_ACTIVE_STATUSES = Object.freeze(['active']);
|
|
29
|
+
/**
|
|
30
|
+
* Whether a TWAP schedule is still executing.
|
|
31
|
+
*
|
|
32
|
+
* @param order - TWAP schedule.
|
|
33
|
+
* @returns True for an active schedule; every other status has ended.
|
|
34
|
+
*/
|
|
35
|
+
export function isTwapOrderActive(order) {
|
|
36
|
+
return TWAP_ORDER_ACTIVE_STATUSES.includes(order.status);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Split TWAP schedules into running and ended ones, keeping their order.
|
|
40
|
+
*
|
|
41
|
+
* @param orders - TWAP schedules.
|
|
42
|
+
* @returns Active and ended schedules.
|
|
43
|
+
*/
|
|
44
|
+
export function partitionTwapOrders(orders) {
|
|
45
|
+
const active = [];
|
|
46
|
+
const ended = [];
|
|
47
|
+
for (const order of orders) {
|
|
48
|
+
(isTwapOrderActive(order) ? active : ended).push(order);
|
|
49
|
+
}
|
|
50
|
+
return { active, ended };
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Bound a TWAP's executed size to its schedule and derive what remains.
|
|
54
|
+
*
|
|
55
|
+
* @param totalSize - Schedule size.
|
|
56
|
+
* @param executedSize - Executed size as reported or proven by fills.
|
|
57
|
+
* @returns Executed size within `[0, totalSize]`, the remaining size and the
|
|
58
|
+
* fill progress in basis points (floored; 0 for an empty schedule).
|
|
59
|
+
*/
|
|
60
|
+
export function boundTwapExecution(totalSize, executedSize) {
|
|
61
|
+
const executed = BigNumber.max(0, BigNumber.min(executedSize, totalSize));
|
|
62
|
+
return {
|
|
63
|
+
executedSize: executed,
|
|
64
|
+
remainingSize: BigNumber.max(totalSize.minus(executed), 0),
|
|
65
|
+
fillProgressBps: totalSize.isGreaterThan(0)
|
|
66
|
+
? executed
|
|
67
|
+
.dividedBy(totalSize)
|
|
68
|
+
.multipliedBy(BASIS_POINTS_DIVISOR)
|
|
69
|
+
.integerValue(BigNumber.ROUND_FLOOR)
|
|
70
|
+
.toNumber()
|
|
71
|
+
: 0,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Whether a TWAP record replaces the one held for the same schedule.
|
|
76
|
+
*
|
|
77
|
+
* A venue reports one lifecycle as an activation plus a terminal record, and
|
|
78
|
+
* `lastUpdated` can tie between them (it folds in slice fills both receive) or
|
|
79
|
+
* favor the activation (a read folds fills in milliseconds, a terminal push
|
|
80
|
+
* carries whole seconds). Terminality therefore decides first, since an ended
|
|
81
|
+
* schedule never runs again; otherwise the strictly newer record wins.
|
|
82
|
+
*
|
|
83
|
+
* @param candidate - Record just received.
|
|
84
|
+
* @param existing - Record already held.
|
|
85
|
+
* @returns True when the candidate replaces the held record.
|
|
86
|
+
*/
|
|
87
|
+
export function supersedesTwapOrder(candidate, existing) {
|
|
88
|
+
const candidateIsTerminal = !isTwapOrderActive(candidate);
|
|
89
|
+
if (candidateIsTerminal !== !isTwapOrderActive(existing)) {
|
|
90
|
+
return candidateIsTerminal;
|
|
91
|
+
}
|
|
92
|
+
return candidate.lastUpdated > existing.lastUpdated;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Raise a TWAP's execution totals to what its slice fills prove executed.
|
|
96
|
+
*
|
|
97
|
+
* A venue can keep reporting zero executed size while slices fill, so the
|
|
98
|
+
* fills are the fresher record. The totals are only ever raised: fills a read
|
|
99
|
+
* did not page in never lower what the venue already reported.
|
|
100
|
+
*
|
|
101
|
+
* @param order - TWAP schedule with the slice fills known for it.
|
|
102
|
+
* @returns The schedule with totals and progress raised from its fills.
|
|
103
|
+
*/
|
|
104
|
+
export function reconcileTwapExecution(order) {
|
|
105
|
+
if (order.fills.length === 0) {
|
|
106
|
+
return order;
|
|
107
|
+
}
|
|
108
|
+
let filledSize = new BigNumber(0);
|
|
109
|
+
let filledNotional = new BigNumber(0);
|
|
110
|
+
for (const fill of order.fills) {
|
|
111
|
+
const size = new BigNumber(fill.size);
|
|
112
|
+
filledSize = filledSize.plus(size);
|
|
113
|
+
filledNotional = filledNotional.plus(size.multipliedBy(fill.price));
|
|
114
|
+
}
|
|
115
|
+
const totalSize = new BigNumber(order.size);
|
|
116
|
+
const reportedSize = new BigNumber(order.executedSize);
|
|
117
|
+
if (!filledSize.isFinite() ||
|
|
118
|
+
!filledNotional.isFinite() ||
|
|
119
|
+
!totalSize.isGreaterThan(0) ||
|
|
120
|
+
!filledSize.isGreaterThan(reportedSize.isFinite() ? reportedSize : 0)) {
|
|
121
|
+
return order;
|
|
122
|
+
}
|
|
123
|
+
const { executedSize, remainingSize, fillProgressBps } = boundTwapExecution(totalSize, filledSize);
|
|
124
|
+
const executedNotional = executedSize.isEqualTo(filledSize)
|
|
125
|
+
? filledNotional
|
|
126
|
+
: filledNotional.multipliedBy(executedSize).dividedBy(filledSize);
|
|
127
|
+
return {
|
|
128
|
+
...order,
|
|
129
|
+
executedSize: executedSize.toFixed(),
|
|
130
|
+
remainingSize: remainingSize.toFixed(),
|
|
131
|
+
executedNotional: executedNotional.toFixed(),
|
|
132
|
+
averagePrice: filledNotional.dividedBy(filledSize).toFixed(),
|
|
133
|
+
fillProgressBps,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Identity of a TWAP schedule across reads and stream pushes.
|
|
138
|
+
*
|
|
139
|
+
* @param order - TWAP schedule.
|
|
140
|
+
* @returns Provider-scoped order key.
|
|
141
|
+
*/
|
|
142
|
+
export const twapOrderKey = (order) => `${order.providerId ?? ''}:${order.orderId}`;
|
|
143
|
+
/**
|
|
144
|
+
* Merge one TWAP record into the one already held for the same schedule.
|
|
145
|
+
* Fills are united by ID; schedule fields come from the record that
|
|
146
|
+
* supersedes (see `supersedesTwapOrder`) or, on an equal version, from the
|
|
147
|
+
* incoming one, and the totals are then raised from the fills.
|
|
148
|
+
*
|
|
149
|
+
* @param retained - Record already held, if any.
|
|
150
|
+
* @param incoming - Newer record from a read or a stream push.
|
|
151
|
+
* @returns The merged record.
|
|
152
|
+
*/
|
|
153
|
+
function mergeTwapOrder(retained, incoming) {
|
|
154
|
+
if (!retained) {
|
|
155
|
+
return reconcileTwapExecution(incoming);
|
|
156
|
+
}
|
|
157
|
+
const fills = new Map(retained.fills.map((fill) => [fill.fillId, fill]));
|
|
158
|
+
for (const fill of incoming.fills) {
|
|
159
|
+
fills.set(fill.fillId, fill);
|
|
160
|
+
}
|
|
161
|
+
// An equal version still carries fresher read-time fields (elapsed time,
|
|
162
|
+
// time progress), so it replaces the held record unless that would turn an
|
|
163
|
+
// ended schedule back into a running one.
|
|
164
|
+
const sameVersion = incoming.lastUpdated === retained.lastUpdated &&
|
|
165
|
+
isTwapOrderActive(incoming) === isTwapOrderActive(retained);
|
|
166
|
+
const schedule = sameVersion || supersedesTwapOrder(incoming, retained)
|
|
167
|
+
? incoming
|
|
168
|
+
: retained;
|
|
169
|
+
return reconcileTwapExecution({
|
|
170
|
+
...schedule,
|
|
171
|
+
fills: [...fills.values()].sort((left, right) => left.timestamp - right.timestamp),
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Merge TWAP records from a read or a stream push into held ones.
|
|
176
|
+
*
|
|
177
|
+
* A record is matched by provider and order ID. Held records missing from
|
|
178
|
+
* `incoming` are kept: a stream carries no fills and caps ended history, so
|
|
179
|
+
* absence there is not proof a schedule is gone.
|
|
180
|
+
*
|
|
181
|
+
* @param retained - Records already held.
|
|
182
|
+
* @param incoming - Records from a read or stream push.
|
|
183
|
+
* @returns Merged records, newest first.
|
|
184
|
+
*/
|
|
185
|
+
export function mergeTwapOrders(retained, incoming) {
|
|
186
|
+
const merged = new Map(retained.map((order) => [twapOrderKey(order), order]));
|
|
187
|
+
for (const order of incoming) {
|
|
188
|
+
const key = twapOrderKey(order);
|
|
189
|
+
merged.set(key, mergeTwapOrder(merged.get(key), order));
|
|
190
|
+
}
|
|
191
|
+
return [...merged.values()].sort((left, right) => right.startedAt - left.startedAt);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Check a TWAP draft against the venue's rules.
|
|
195
|
+
*
|
|
196
|
+
* @param params - Draft values and venue rules.
|
|
197
|
+
* @param params.rules - TWAP rules from `getStrategyRules`; absent means the
|
|
198
|
+
* venue does not run TWAP on this market.
|
|
199
|
+
* @param params.durationMinutes - Running time in whole minutes.
|
|
200
|
+
* @param params.usdAmount - Total order value in USD, when known.
|
|
201
|
+
* @returns Validation result with a `PERPS_ERROR_CODES` error.
|
|
202
|
+
*/
|
|
203
|
+
export function validateTwapOrder(params) {
|
|
204
|
+
const { rules, durationMinutes, usdAmount } = params;
|
|
205
|
+
if (!rules) {
|
|
206
|
+
return {
|
|
207
|
+
isValid: false,
|
|
208
|
+
error: PERPS_ERROR_CODES.ORDER_STRATEGY_MARKET_UNSUPPORTED,
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
if (durationMinutes === undefined) {
|
|
212
|
+
return {
|
|
213
|
+
isValid: false,
|
|
214
|
+
error: PERPS_ERROR_CODES.ORDER_TWAP_DURATION_REQUIRED,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
if (!Number.isInteger(durationMinutes) ||
|
|
218
|
+
durationMinutes < rules.minDurationMinutes ||
|
|
219
|
+
durationMinutes > rules.maxDurationMinutes) {
|
|
220
|
+
return {
|
|
221
|
+
isValid: false,
|
|
222
|
+
error: PERPS_ERROR_CODES.ORDER_TWAP_DURATION_INVALID,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
if (usdAmount !== undefined) {
|
|
226
|
+
const amount = new BigNumber(usdAmount);
|
|
227
|
+
if (!amount.isFinite() || amount.isLessThan(rules.minNotionalUsd)) {
|
|
228
|
+
return {
|
|
229
|
+
isValid: false,
|
|
230
|
+
error: PERPS_ERROR_CODES.ORDER_TWAP_NOTIONAL_TOO_SMALL,
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return { isValid: true };
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Preview how a TWAP is cut into slices on the venue's cadence.
|
|
238
|
+
*
|
|
239
|
+
* The slice size is floored to the venue's size grid, so it is never shown
|
|
240
|
+
* finer than the venue can trade; `isBelowMinimumSize` flags a slice that
|
|
241
|
+
* floors to nothing.
|
|
242
|
+
*
|
|
243
|
+
* @param params - Draft values and venue rules.
|
|
244
|
+
* @param params.rules - TWAP rules from `getStrategyRules`.
|
|
245
|
+
* @param params.durationMinutes - Running time in whole minutes.
|
|
246
|
+
* @param params.size - Total size in base units.
|
|
247
|
+
* @param params.sizeDecimals - Venue size precision of the market.
|
|
248
|
+
* @param params.price - Reference price, to value each slice.
|
|
249
|
+
* @returns The preview, or `undefined` when the rules or inputs are missing.
|
|
250
|
+
*/
|
|
251
|
+
export function computeTwapSlicePreview(params) {
|
|
252
|
+
const { rules, durationMinutes, sizeDecimals } = params;
|
|
253
|
+
if (!rules || durationMinutes === undefined) {
|
|
254
|
+
return undefined;
|
|
255
|
+
}
|
|
256
|
+
const sliceCount = Math.floor((durationMinutes * SECONDS_PER_MINUTE) / rules.sliceIntervalSeconds);
|
|
257
|
+
const size = new BigNumber(params.size ?? Number.NaN);
|
|
258
|
+
if (!Number.isFinite(sliceCount) ||
|
|
259
|
+
sliceCount < 1 ||
|
|
260
|
+
!size.isFinite() ||
|
|
261
|
+
!size.isGreaterThan(0) ||
|
|
262
|
+
!Number.isInteger(sizeDecimals) ||
|
|
263
|
+
sizeDecimals < 0) {
|
|
264
|
+
return undefined;
|
|
265
|
+
}
|
|
266
|
+
const sizePerSlice = size
|
|
267
|
+
.dividedBy(sliceCount)
|
|
268
|
+
.decimalPlaces(sizeDecimals, BigNumber.ROUND_DOWN);
|
|
269
|
+
const minimumSize = new BigNumber(1).shiftedBy(-sizeDecimals);
|
|
270
|
+
const price = new BigNumber(params.price ?? Number.NaN);
|
|
271
|
+
return {
|
|
272
|
+
sliceCount,
|
|
273
|
+
sliceIntervalSeconds: rules.sliceIntervalSeconds,
|
|
274
|
+
sizePerSlice: sizePerSlice.toFixed(),
|
|
275
|
+
sizeDecimals,
|
|
276
|
+
minimumSize: minimumSize.toFixed(),
|
|
277
|
+
isBelowMinimumSize: sizePerSlice.isLessThan(minimumSize),
|
|
278
|
+
...(price.isFinite() &&
|
|
279
|
+
price.isGreaterThan(0) && {
|
|
280
|
+
notionalPerSlice: sizePerSlice.multipliedBy(price).toFixed(),
|
|
281
|
+
}),
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
// ---------------------------------------------------------------------------
|
|
285
|
+
// Chase
|
|
286
|
+
// ---------------------------------------------------------------------------
|
|
287
|
+
/**
|
|
288
|
+
* Chase statuses that belong in the running list: still chasing, or waiting
|
|
289
|
+
* for a cancel to settle.
|
|
290
|
+
*/
|
|
291
|
+
export const CHASE_ORDER_RUNNING_STATUSES = Object.freeze([
|
|
292
|
+
CHASE_ORDER_STATUS.Active,
|
|
293
|
+
CHASE_ORDER_STATUS.TerminationPending,
|
|
294
|
+
]);
|
|
295
|
+
/**
|
|
296
|
+
* Whether a chase belongs in the running list rather than history.
|
|
297
|
+
*
|
|
298
|
+
* @param order - Chase snapshot.
|
|
299
|
+
* @returns True while it chases or its cancel is pending.
|
|
300
|
+
*/
|
|
301
|
+
export function isChaseOrderRunning(order) {
|
|
302
|
+
return CHASE_ORDER_RUNNING_STATUSES.includes(order.status);
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Whether cancelling a chase by its handle can still do something: it is
|
|
306
|
+
* running (a pending cancel may be retried), or it stopped with a child order
|
|
307
|
+
* still resting.
|
|
308
|
+
*
|
|
309
|
+
* @param order - Chase snapshot.
|
|
310
|
+
* @returns True when a cancel should be offered.
|
|
311
|
+
*/
|
|
312
|
+
export function isChaseOrderCancelable(order) {
|
|
313
|
+
return isChaseOrderRunning(order) || order.restingOrderId !== null;
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Check whether another chase can be placed under the venue's cap.
|
|
317
|
+
*
|
|
318
|
+
* Only chases that are still chasing take a slot; one waiting on a cancel or
|
|
319
|
+
* stopped by a cap does not, matching what the provider enforces.
|
|
320
|
+
*
|
|
321
|
+
* @param params - Venue rules and current chase snapshots.
|
|
322
|
+
* @param params.rules - Chase rules from `getStrategyRules`.
|
|
323
|
+
* @param params.chaseOrders - Current chase snapshots for the account.
|
|
324
|
+
* @returns Whether a placement fits, with the counts it was judged on.
|
|
325
|
+
*/
|
|
326
|
+
export function checkChasePlacement(params) {
|
|
327
|
+
const { rules, chaseOrders } = params;
|
|
328
|
+
const activeCount = chaseOrders.filter((order) => order.status === CHASE_ORDER_STATUS.Active).length;
|
|
329
|
+
if (!rules) {
|
|
330
|
+
return {
|
|
331
|
+
canPlace: false,
|
|
332
|
+
activeCount,
|
|
333
|
+
error: PERPS_ERROR_CODES.ORDER_STRATEGY_MARKET_UNSUPPORTED,
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
const { maxActiveSessions } = rules;
|
|
337
|
+
if (maxActiveSessions !== undefined && activeCount >= maxActiveSessions) {
|
|
338
|
+
return {
|
|
339
|
+
canPlace: false,
|
|
340
|
+
activeCount,
|
|
341
|
+
maxActiveSessions,
|
|
342
|
+
error: PERPS_ERROR_CODES.ORDER_CHASE_LIMIT_REACHED,
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
return {
|
|
346
|
+
canPlace: true,
|
|
347
|
+
activeCount,
|
|
348
|
+
...(maxActiveSessions !== undefined && { maxActiveSessions }),
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Identity of a chase session across reads.
|
|
353
|
+
*
|
|
354
|
+
* @param order - Chase snapshot.
|
|
355
|
+
* @returns Provider-scoped handle key.
|
|
356
|
+
*/
|
|
357
|
+
export const chaseOrderKey = (order) => `${order.providerId ?? ''}:${order.handle}`;
|
|
358
|
+
const newestChaseFirst = (left, right) => right.startedAt - left.startedAt || left.handle.localeCompare(right.handle);
|
|
359
|
+
/**
|
|
360
|
+
* Build running and history chase lists from a fresh read, keeping ended
|
|
361
|
+
* chases a provider has since dropped.
|
|
362
|
+
*
|
|
363
|
+
* A chase that vanishes while running is dropped: without its ending the list
|
|
364
|
+
* would show a guess. History is bounded to the newest `historyLimit` rows.
|
|
365
|
+
*
|
|
366
|
+
* @param params - Previous lists and the latest read.
|
|
367
|
+
* @param params.previous - Lists built from the previous read.
|
|
368
|
+
* @param params.current - Chase snapshots from the latest read.
|
|
369
|
+
* @param params.historyLimit - Most ended chases kept.
|
|
370
|
+
* @returns Running and history lists, newest first.
|
|
371
|
+
*/
|
|
372
|
+
export function mergeChaseOrderHistory(params) {
|
|
373
|
+
const { previous, current } = params;
|
|
374
|
+
const historyLimit = params.historyLimit ?? CHASE_ORDER_CONFIG.HistoryLimit;
|
|
375
|
+
const running = [];
|
|
376
|
+
const history = new Map();
|
|
377
|
+
for (const order of previous?.history ?? []) {
|
|
378
|
+
history.set(chaseOrderKey(order), order);
|
|
379
|
+
}
|
|
380
|
+
for (const order of current) {
|
|
381
|
+
if (isChaseOrderRunning(order)) {
|
|
382
|
+
running.push(order);
|
|
383
|
+
}
|
|
384
|
+
else {
|
|
385
|
+
history.set(chaseOrderKey(order), order);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
return {
|
|
389
|
+
running: running.sort(newestChaseFirst),
|
|
390
|
+
history: [...history.values()]
|
|
391
|
+
.sort(newestChaseFirst)
|
|
392
|
+
.slice(0, historyLimit),
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
// ---------------------------------------------------------------------------
|
|
396
|
+
// Scale
|
|
397
|
+
// ---------------------------------------------------------------------------
|
|
398
|
+
/**
|
|
399
|
+
* Parse a positive decimal amount exactly.
|
|
400
|
+
*
|
|
401
|
+
* @param raw - Decimal string.
|
|
402
|
+
* @returns The amount.
|
|
403
|
+
* @throws `ORDER_SIZE_POSITIVE` when it is not a positive decimal.
|
|
404
|
+
*/
|
|
405
|
+
function parsePositiveDecimal(raw) {
|
|
406
|
+
const value = typeof raw === 'string' &&
|
|
407
|
+
/^(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/u.test(raw)
|
|
408
|
+
? new BigNumber(raw)
|
|
409
|
+
: new BigNumber(Number.NaN);
|
|
410
|
+
if (!value.isFinite() || !value.isGreaterThan(0)) {
|
|
411
|
+
throw new Error(PERPS_ERROR_CODES.ORDER_SIZE_POSITIVE);
|
|
412
|
+
}
|
|
413
|
+
return value;
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Size a scale ladder by the one rule every venue applies: an exact base size
|
|
417
|
+
* is split as given; a USD amount buys the largest size on the venue's grid
|
|
418
|
+
* whose ladder value, rung price times rung size, stays within it.
|
|
419
|
+
*
|
|
420
|
+
* @param params - Normalized ladder prices and the sizing intent.
|
|
421
|
+
* @param params.prices - Venue-normalized rung prices, in ladder order.
|
|
422
|
+
* @param params.sizeDecimals - Venue size precision of the market.
|
|
423
|
+
* @param params.skew - Optional rung-size skew, as `splitScaleSizes` takes it.
|
|
424
|
+
* @param params.size - Exact total base size.
|
|
425
|
+
* @param params.usdAmount - Maximum ladder value in USD.
|
|
426
|
+
* @returns Rung sizes and ladder totals.
|
|
427
|
+
* @throws `ORDER_SIZE_POSITIVE` for a missing or non-positive amount, and
|
|
428
|
+
* `ORDER_SCALE_SIZE_TOO_SMALL` when no rung can get a grid unit. The internal
|
|
429
|
+
* guards `ORDER_SCALE_SIZE_CONSERVATION_FAILED` and
|
|
430
|
+
* `ORDER_SCALE_EXPOSURE_EXCEEDS_INTENT` fire only if the split itself breaks.
|
|
431
|
+
*/
|
|
432
|
+
export function sizeScaleLadder(params) {
|
|
433
|
+
const { prices, sizeDecimals: decimals, skew } = params;
|
|
434
|
+
const count = prices.length;
|
|
435
|
+
const budget = params.usdAmount === undefined
|
|
436
|
+
? undefined
|
|
437
|
+
: parsePositiveDecimal(params.usdAmount);
|
|
438
|
+
const lowestPrice = BigNumber.min(...prices.map(parsePositiveDecimal));
|
|
439
|
+
const rawSize = budget
|
|
440
|
+
? budget.dividedBy(lowestPrice)
|
|
441
|
+
: parsePositiveDecimal(params.size);
|
|
442
|
+
const units = rawSize.shiftedBy(decimals).integerValue(BigNumber.ROUND_DOWN);
|
|
443
|
+
if (units.isGreaterThan(Number.MAX_SAFE_INTEGER) || units.isLessThan(count)) {
|
|
444
|
+
throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL);
|
|
445
|
+
}
|
|
446
|
+
// `splitScaleSizes` works in floats, so each split is checked to keep every
|
|
447
|
+
// grid unit and stay on the grid before it can be priced or placed.
|
|
448
|
+
const split = (totalUnits) => {
|
|
449
|
+
const sizes = splitScaleSizes({
|
|
450
|
+
totalSize: new BigNumber(totalUnits).shiftedBy(-decimals).toNumber(),
|
|
451
|
+
count,
|
|
452
|
+
szDecimals: decimals,
|
|
453
|
+
skew,
|
|
454
|
+
});
|
|
455
|
+
const rungUnits = sizes.map((size) => new BigNumber(size).shiftedBy(decimals));
|
|
456
|
+
if (rungUnits.some((unit) => !unit.isInteger()) ||
|
|
457
|
+
!BigNumber.sum(...rungUnits).isEqualTo(totalUnits)) {
|
|
458
|
+
throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_CONSERVATION_FAILED);
|
|
459
|
+
}
|
|
460
|
+
return sizes;
|
|
461
|
+
};
|
|
462
|
+
const value = (sizes) => sizes.reduce((total, size, index) => total.plus(new BigNumber(size).times(prices[index])), new BigNumber(0));
|
|
463
|
+
let totalUnits = units.toNumber();
|
|
464
|
+
if (budget) {
|
|
465
|
+
let low = count;
|
|
466
|
+
let high = totalUnits;
|
|
467
|
+
let feasible;
|
|
468
|
+
while (low <= high) {
|
|
469
|
+
const candidate = low + Math.floor((high - low) / 2);
|
|
470
|
+
let sizes;
|
|
471
|
+
try {
|
|
472
|
+
sizes = split(candidate);
|
|
473
|
+
}
|
|
474
|
+
catch {
|
|
475
|
+
low = candidate + 1;
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
if (value(sizes).isLessThanOrEqualTo(budget)) {
|
|
479
|
+
feasible = candidate;
|
|
480
|
+
low = candidate + 1;
|
|
481
|
+
}
|
|
482
|
+
else {
|
|
483
|
+
high = candidate - 1;
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
if (feasible === undefined) {
|
|
487
|
+
throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL);
|
|
488
|
+
}
|
|
489
|
+
totalUnits = feasible;
|
|
490
|
+
}
|
|
491
|
+
const sizes = split(totalUnits);
|
|
492
|
+
const totalSize = new BigNumber(totalUnits).shiftedBy(-decimals);
|
|
493
|
+
const totalNotional = value(sizes);
|
|
494
|
+
if (totalSize.isGreaterThan(rawSize) ||
|
|
495
|
+
(budget && totalNotional.isGreaterThan(budget))) {
|
|
496
|
+
throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_EXPOSURE_EXCEEDS_INTENT);
|
|
497
|
+
}
|
|
498
|
+
return {
|
|
499
|
+
sizes,
|
|
500
|
+
totalSize: totalSize.toFixed(),
|
|
501
|
+
totalNotional: totalNotional.toFixed(),
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* Check a scale draft against the venue's rules and, when the venue preview
|
|
506
|
+
* is known, its per-rung minimum.
|
|
507
|
+
*
|
|
508
|
+
* @param params - Draft values, venue rules and the optional venue preview.
|
|
509
|
+
* @param params.rules - Scale rules from `getStrategyRules`.
|
|
510
|
+
* @param params.minPrice - Lowest ladder price.
|
|
511
|
+
* @param params.maxPrice - Highest ladder price.
|
|
512
|
+
* @param params.count - Number of rungs.
|
|
513
|
+
* @param params.skew - Optional rung-size skew.
|
|
514
|
+
* @param params.preview - Ladder prices and sizes from `getScalePriceLadder`,
|
|
515
|
+
* with the venue's per-order minimum value.
|
|
516
|
+
* @returns Validation result with a `PERPS_ERROR_CODES` error.
|
|
517
|
+
*/
|
|
518
|
+
export function validateScaleOrder(params) {
|
|
519
|
+
const { rules, minPrice, maxPrice, count, skew, preview } = params;
|
|
520
|
+
if (!rules) {
|
|
521
|
+
return {
|
|
522
|
+
isValid: false,
|
|
523
|
+
error: PERPS_ERROR_CODES.ORDER_STRATEGY_MARKET_UNSUPPORTED,
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
if (minPrice === undefined || maxPrice === undefined) {
|
|
527
|
+
return {
|
|
528
|
+
isValid: false,
|
|
529
|
+
error: PERPS_ERROR_CODES.ORDER_SCALE_RANGE_REQUIRED,
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
if (!Number.isFinite(minPrice) ||
|
|
533
|
+
!Number.isFinite(maxPrice) ||
|
|
534
|
+
minPrice <= 0 ||
|
|
535
|
+
maxPrice <= minPrice) {
|
|
536
|
+
return {
|
|
537
|
+
isValid: false,
|
|
538
|
+
error: PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID,
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
if (count === undefined ||
|
|
542
|
+
!Number.isInteger(count) ||
|
|
543
|
+
count < rules.minOrders ||
|
|
544
|
+
count > rules.maxOrders) {
|
|
545
|
+
return {
|
|
546
|
+
isValid: false,
|
|
547
|
+
error: PERPS_ERROR_CODES.ORDER_SCALE_COUNT_INVALID,
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
// Omitted is an even ladder, so only a supplied skew is checked.
|
|
551
|
+
if (skew !== undefined && (!Number.isFinite(skew) || skew <= 0)) {
|
|
552
|
+
return {
|
|
553
|
+
isValid: false,
|
|
554
|
+
error: PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID,
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
if (preview) {
|
|
558
|
+
// Each rung is its own order, so the venue minimum applies to every rung,
|
|
559
|
+
// not to the ladder's total. An unreadable preview, or one without exactly
|
|
560
|
+
// `count` rungs, fails.
|
|
561
|
+
const minimum = new BigNumber(preview.minimumQuoteAmount);
|
|
562
|
+
const belowMinimum = preview.prices.length !== count ||
|
|
563
|
+
preview.sizes.length !== count ||
|
|
564
|
+
preview.sizes.some((size, index) => !new BigNumber(size)
|
|
565
|
+
.times(preview.prices[index])
|
|
566
|
+
.isGreaterThanOrEqualTo(minimum));
|
|
567
|
+
if (belowMinimum) {
|
|
568
|
+
return {
|
|
569
|
+
isValid: false,
|
|
570
|
+
error: PERPS_ERROR_CODES.ORDER_SCALE_NOTIONAL_TOO_SMALL,
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
return { isValid: true };
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* Classify scale ladder prices against the book for warnings.
|
|
578
|
+
*
|
|
579
|
+
* - `crosses_market` / `partially_crosses_market`: both or one ladder end is at
|
|
580
|
+
* or through the opposite touch (best ask for a buy, best bid for a sell),
|
|
581
|
+
* so those rungs fill at once as taker.
|
|
582
|
+
* - `far_from_market`: the far ladder end sits more than
|
|
583
|
+
* `ORDER_PRICE_WARNING_CONFIG.FarFromMarketRatio` from the near touch (best
|
|
584
|
+
* bid for a buy, best ask for a sell); `distancePercent` is that distance,
|
|
585
|
+
* rounded up to a whole percent.
|
|
586
|
+
*
|
|
587
|
+
* A reduce-only ladder gets no distance warning, since it only closes. Each
|
|
588
|
+
* check is skipped while its touch is unknown.
|
|
589
|
+
*
|
|
590
|
+
* @param params - Ladder prices, side and top of book.
|
|
591
|
+
* @param params.prices - Rung prices (any order).
|
|
592
|
+
* @param params.isBuy - Whether the ladder buys.
|
|
593
|
+
* @param params.bestBid - Best bid price.
|
|
594
|
+
* @param params.bestAsk - Best ask price.
|
|
595
|
+
* @param params.reduceOnly - Whether the ladder only reduces a position.
|
|
596
|
+
* @returns Warnings, empty when there is nothing to warn about.
|
|
597
|
+
*/
|
|
598
|
+
export function classifyScalePriceWarnings(params) {
|
|
599
|
+
const { isBuy } = params;
|
|
600
|
+
const prices = params.prices.map((price) => new BigNumber(price));
|
|
601
|
+
if (prices.length === 0 ||
|
|
602
|
+
prices.some((price) => !price.isFinite() || !price.isGreaterThan(0))) {
|
|
603
|
+
return [];
|
|
604
|
+
}
|
|
605
|
+
const touch = (price) => {
|
|
606
|
+
const parsed = new BigNumber(price ?? Number.NaN);
|
|
607
|
+
return parsed.isFinite() && parsed.isGreaterThan(0) ? parsed : undefined;
|
|
608
|
+
};
|
|
609
|
+
const oppositeTouch = touch(isBuy ? params.bestAsk : params.bestBid);
|
|
610
|
+
const nearTouch = touch(isBuy ? params.bestBid : params.bestAsk);
|
|
611
|
+
const ends = [BigNumber.min(...prices), BigNumber.max(...prices)];
|
|
612
|
+
const warnings = [];
|
|
613
|
+
if (oppositeTouch) {
|
|
614
|
+
const crossing = ends.filter((price) => isBuy
|
|
615
|
+
? price.isGreaterThanOrEqualTo(oppositeTouch)
|
|
616
|
+
: price.isLessThanOrEqualTo(oppositeTouch)).length;
|
|
617
|
+
if (crossing === ends.length) {
|
|
618
|
+
warnings.push({ code: 'crosses_market' });
|
|
619
|
+
}
|
|
620
|
+
else if (crossing > 0) {
|
|
621
|
+
warnings.push({ code: 'partially_crosses_market' });
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
if (nearTouch && !params.reduceOnly) {
|
|
625
|
+
const far = isBuy ? ends[0] : ends[1];
|
|
626
|
+
const distance = (isBuy ? nearTouch.minus(far) : far.minus(nearTouch)).dividedBy(nearTouch);
|
|
627
|
+
if (distance.isGreaterThan(ORDER_PRICE_WARNING_CONFIG.FarFromMarketRatio)) {
|
|
628
|
+
warnings.push({
|
|
629
|
+
code: 'far_from_market',
|
|
630
|
+
distancePercent: distance
|
|
631
|
+
.times(PERCENT_PER_RATIO)
|
|
632
|
+
.integerValue(BigNumber.ROUND_CEIL)
|
|
633
|
+
.toNumber(),
|
|
634
|
+
});
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
return warnings;
|
|
638
|
+
}
|
|
639
|
+
//# sourceMappingURL=advancedOrders.js.map
|