@velocity-exchange/sdk 0.4.0 → 0.6.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/README.md +3 -3
- package/lib/browser/adminClient.d.ts +35 -0
- package/lib/browser/adminClient.js +65 -0
- package/lib/browser/config.js +6 -7
- package/lib/browser/constants/numericConstants.d.ts +1 -1
- package/lib/browser/constants/numericConstants.js +1 -1
- package/lib/browser/decode/user.js +5 -1
- package/lib/browser/idl/velocity.d.ts +146 -3
- package/lib/browser/idl/velocity.json +147 -4
- package/lib/browser/orderSubscriber/OrderSubscriber.js +3 -0
- package/lib/browser/pyth/pythLazerSubscriber.js +37 -27
- package/lib/browser/types.d.ts +4 -0
- package/lib/browser/user.d.ts +15 -0
- package/lib/browser/user.js +37 -1
- package/lib/browser/velocityClient.d.ts +46 -10
- package/lib/browser/velocityClient.js +107 -35
- package/lib/node/adminClient.d.ts +35 -0
- package/lib/node/adminClient.d.ts.map +1 -1
- package/lib/node/adminClient.js +65 -0
- package/lib/node/config.d.ts.map +1 -1
- package/lib/node/config.js +6 -7
- package/lib/node/constants/numericConstants.d.ts +1 -1
- package/lib/node/constants/numericConstants.d.ts.map +1 -1
- package/lib/node/constants/numericConstants.js +1 -1
- package/lib/node/decode/user.d.ts.map +1 -1
- package/lib/node/decode/user.js +5 -1
- package/lib/node/idl/velocity.d.ts +146 -3
- package/lib/node/idl/velocity.d.ts.map +1 -1
- package/lib/node/idl/velocity.json +147 -4
- package/lib/node/orderSubscriber/OrderSubscriber.d.ts.map +1 -1
- package/lib/node/orderSubscriber/OrderSubscriber.js +3 -0
- package/lib/node/pyth/pythLazerSubscriber.d.ts.map +1 -1
- package/lib/node/pyth/pythLazerSubscriber.js +37 -27
- package/lib/node/types.d.ts +4 -0
- package/lib/node/types.d.ts.map +1 -1
- package/lib/node/user.d.ts +15 -0
- package/lib/node/user.d.ts.map +1 -1
- package/lib/node/user.js +37 -1
- package/lib/node/velocityClient.d.ts +46 -10
- package/lib/node/velocityClient.d.ts.map +1 -1
- package/lib/node/velocityClient.js +107 -35
- package/package.json +7 -3
- package/.prettierignore +0 -1
- package/CHANGELOG.md +0 -132
- package/build-browser.js +0 -58
- package/bunfig.toml +0 -3
- package/esbuild-shims.js +0 -12
- package/scripts/deposit-isolated-positions.ts +0 -110
- package/scripts/find-flagged-users.ts +0 -213
- package/scripts/grpc-client-test-comparison.ts +0 -372
- package/scripts/grpc-multiuser-client-test-comparison.ts +0 -158
- package/scripts/postbuild.js +0 -95
- package/scripts/single-grpc-client-test.ts +0 -284
- package/scripts/withdraw-isolated-positions.ts +0 -174
- package/src/accounts/README_WebSocketAccountSubscriberV2.md +0 -95
- package/src/accounts/README_WebSocketProgramAccountSubscriberV2.md +0 -135
- package/src/accounts/basicUserAccountSubscriber.ts +0 -79
- package/src/accounts/basicUserStatsAccountSubscriber.ts +0 -87
- package/src/accounts/bulkAccountLoader.ts +0 -358
- package/src/accounts/bulkUserStatsSubscription.ts +0 -40
- package/src/accounts/bulkUserSubscription.ts +0 -39
- package/src/accounts/customizedCadenceBulkAccountLoader.ts +0 -250
- package/src/accounts/fetch.ts +0 -200
- package/src/accounts/grpcAccountSubscriber.ts +0 -225
- package/src/accounts/grpcInsuranceFundStakeAccountSubscriber.ts +0 -73
- package/src/accounts/grpcMultiAccountSubscriber.ts +0 -566
- package/src/accounts/grpcMultiUserAccountSubscriber.ts +0 -328
- package/src/accounts/grpcProgramAccountSubscriber.ts +0 -264
- package/src/accounts/grpcUserAccountSubscriber.ts +0 -63
- package/src/accounts/grpcUserStatsAccountSubscriber.ts +0 -65
- package/src/accounts/grpcVelocityClientAccountSubscriber.ts +0 -257
- package/src/accounts/grpcVelocityClientAccountSubscriberV2.ts +0 -941
- package/src/accounts/laserProgramAccountSubscriber.ts +0 -266
- package/src/accounts/oneShotUserAccountSubscriber.ts +0 -88
- package/src/accounts/oneShotUserStatsAccountSubscriber.ts +0 -94
- package/src/accounts/pollingInsuranceFundStakeAccountSubscriber.ts +0 -223
- package/src/accounts/pollingOracleAccountSubscriber.ts +0 -151
- package/src/accounts/pollingTokenAccountSubscriber.ts +0 -147
- package/src/accounts/pollingUserAccountSubscriber.ts +0 -198
- package/src/accounts/pollingUserStatsAccountSubscriber.ts +0 -180
- package/src/accounts/pollingVelocityClientAccountSubscriber.ts +0 -774
- package/src/accounts/testBulkAccountLoader.ts +0 -59
- package/src/accounts/types.ts +0 -428
- package/src/accounts/utils.ts +0 -90
- package/src/accounts/webSocketAccountSubscriber.ts +0 -304
- package/src/accounts/webSocketAccountSubscriberV2.ts +0 -536
- package/src/accounts/webSocketInsuranceFundStakeAccountSubscriber.ts +0 -171
- package/src/accounts/webSocketProgramAccountSubscriber.ts +0 -244
- package/src/accounts/webSocketProgramAccountSubscriberV2.ts +0 -1048
- package/src/accounts/webSocketProgramAccountsSubscriberV2.ts +0 -1042
- package/src/accounts/webSocketUserAccountSubscriber.ts +0 -139
- package/src/accounts/webSocketUserStatsAccountSubsriber.ts +0 -131
- package/src/accounts/webSocketVelocityClientAccountSubscriber.ts +0 -865
- package/src/accounts/webSocketVelocityClientAccountSubscriberV2.ts +0 -897
- package/src/accounts/websocketProgramUserAccountSubscriber.ts +0 -127
- package/src/addresses/marketAddresses.ts +0 -28
- package/src/addresses/pda.ts +0 -620
- package/src/adminClient.ts +0 -8136
- package/src/assert/assert.ts +0 -5
- package/src/auctionSubscriber/auctionSubscriber.ts +0 -86
- package/src/auctionSubscriber/auctionSubscriberGrpc.ts +0 -99
- package/src/auctionSubscriber/index.ts +0 -9
- package/src/auctionSubscriber/types.ts +0 -30
- package/src/bankrun/bankrunConnection.ts +0 -630
- package/src/blockhashSubscriber/BlockhashSubscriber.ts +0 -160
- package/src/blockhashSubscriber/index.ts +0 -6
- package/src/blockhashSubscriber/types.ts +0 -13
- package/src/clock/clockSubscriber.ts +0 -146
- package/src/config.ts +0 -312
- package/src/constants/index.ts +0 -9
- package/src/constants/numericConstants.ts +0 -194
- package/src/constants/perpMarkets.ts +0 -127
- package/src/constants/spotMarkets.ts +0 -104
- package/src/constants/txConstants.ts +0 -2
- package/src/constituentMap/constituentMap.ts +0 -305
- package/src/constituentMap/pollingConstituentAccountSubscriber.ts +0 -99
- package/src/constituentMap/webSocketConstituentAccountSubscriber.ts +0 -121
- package/src/core/VelocityCore.ts +0 -606
- package/src/core/index.ts +0 -12
- package/src/core/instructions/deposit.ts +0 -64
- package/src/core/instructions/fill.ts +0 -51
- package/src/core/instructions/funding.ts +0 -33
- package/src/core/instructions/liquidation.ts +0 -55
- package/src/core/instructions/orders.ts +0 -84
- package/src/core/instructions/perpOrders.ts +0 -312
- package/src/core/instructions/settlement.ts +0 -40
- package/src/core/instructions/trigger.ts +0 -41
- package/src/core/instructions/withdraw.ts +0 -65
- package/src/core/remainingAccounts.ts +0 -320
- package/src/core/signedMsg.ts +0 -109
- package/src/decode/customCoder.ts +0 -148
- package/src/decode/user.ts +0 -401
- package/src/dlob/DLOB.ts +0 -2793
- package/src/dlob/DLOBNode.ts +0 -305
- package/src/dlob/DLOBSubscriber.ts +0 -269
- package/src/dlob/NodeList.ts +0 -244
- package/src/dlob/orderBookLevels.ts +0 -695
- package/src/dlob/types.ts +0 -37
- package/src/events/eventList.ts +0 -114
- package/src/events/eventSubscriber.ts +0 -521
- package/src/events/eventsServerLogProvider.ts +0 -189
- package/src/events/fetchLogs.ts +0 -219
- package/src/events/parse.ts +0 -271
- package/src/events/pollingLogProvider.ts +0 -113
- package/src/events/sort.ts +0 -51
- package/src/events/txEventCache.ts +0 -92
- package/src/events/types.ts +0 -337
- package/src/events/webSocketLogProvider.ts +0 -152
- package/src/factory/bigNum.ts +0 -709
- package/src/factory/oracleClient.ts +0 -73
- package/src/idl/pyth.json +0 -142
- package/src/idl/pyth.ts +0 -97
- package/src/idl/pyth_solana_receiver.json +0 -628
- package/src/idl/token_faucet.json +0 -229
- package/src/idl/token_faucet.ts +0 -197
- package/src/idl/velocity.json +0 -23974
- package/src/idl/velocity.ts +0 -23980
- package/src/index.ts +0 -150
- package/src/indicative-quotes/indicativeQuotesSender.ts +0 -233
- package/src/isomorphic/README.md +0 -19
- package/src/isomorphic/anchor.browser.ts +0 -44
- package/src/isomorphic/anchor.node.ts +0 -1
- package/src/isomorphic/anchor.ts +0 -1
- package/src/isomorphic/anchor29.browser.ts +0 -24
- package/src/isomorphic/anchor29.node.ts +0 -1
- package/src/isomorphic/anchor29.ts +0 -1
- package/src/isomorphic/grpc.browser.ts +0 -4
- package/src/isomorphic/grpc.node.ts +0 -130
- package/src/isomorphic/grpc.ts +0 -1
- package/src/jupiter/jupiterClient.ts +0 -502
- package/src/keypair.ts +0 -32
- package/src/margin/README.md +0 -138
- package/src/marginCalculation.ts +0 -407
- package/src/marinade/idl/idl.json +0 -1962
- package/src/marinade/index.ts +0 -73
- package/src/marinade/types.ts +0 -3925
- package/src/math/amm.ts +0 -1758
- package/src/math/auction.ts +0 -480
- package/src/math/bankruptcy.ts +0 -138
- package/src/math/builder.ts +0 -130
- package/src/math/conversion.ts +0 -45
- package/src/math/exchangeStatus.ts +0 -261
- package/src/math/funding.ts +0 -498
- package/src/math/insurance.ts +0 -171
- package/src/math/liquidation.ts +0 -433
- package/src/math/margin.ts +0 -327
- package/src/math/market.ts +0 -487
- package/src/math/oracles.ts +0 -477
- package/src/math/orders.ts +0 -500
- package/src/math/position.ts +0 -381
- package/src/math/repeg.ts +0 -223
- package/src/math/spotBalance.ts +0 -996
- package/src/math/spotMarket.ts +0 -115
- package/src/math/spotPosition.ts +0 -263
- package/src/math/state.ts +0 -71
- package/src/math/superStake.ts +0 -602
- package/src/math/tiers.ts +0 -73
- package/src/math/trade.ts +0 -879
- package/src/math/utils.ts +0 -183
- package/src/memcmp.ts +0 -279
- package/src/oracles/oracleClientCache.ts +0 -41
- package/src/oracles/oracleId.ts +0 -99
- package/src/oracles/prelaunchOracleClient.ts +0 -63
- package/src/oracles/pythClient.ts +0 -125
- package/src/oracles/pythLazerClient.ts +0 -141
- package/src/oracles/quoteAssetOracleClient.ts +0 -43
- package/src/oracles/strictOraclePrice.ts +0 -40
- package/src/oracles/types.ts +0 -82
- package/src/oracles/utils.ts +0 -45
- package/src/orderParams.ts +0 -117
- package/src/orderSubscriber/OrderSubscriber.ts +0 -378
- package/src/orderSubscriber/PollingSubscription.ts +0 -50
- package/src/orderSubscriber/WebsocketSubscription.ts +0 -137
- package/src/orderSubscriber/grpcSubscription.ts +0 -155
- package/src/orderSubscriber/index.ts +0 -7
- package/src/orderSubscriber/types.ts +0 -64
- package/src/priorityFee/averageOverSlotsStrategy.ts +0 -17
- package/src/priorityFee/averageStrategy.ts +0 -13
- package/src/priorityFee/ewmaStrategy.ts +0 -51
- package/src/priorityFee/heliusPriorityFeeMethod.ts +0 -68
- package/src/priorityFee/index.ts +0 -16
- package/src/priorityFee/maxOverSlotsStrategy.ts +0 -18
- package/src/priorityFee/maxStrategy.ts +0 -8
- package/src/priorityFee/priorityFeeSubscriber.ts +0 -328
- package/src/priorityFee/priorityFeeSubscriberMap.ts +0 -134
- package/src/priorityFee/solanaPriorityFeeMethod.ts +0 -46
- package/src/priorityFee/types.ts +0 -82
- package/src/priorityFee/velocityPriorityFeeMethod.ts +0 -53
- package/src/pyth/constants.ts +0 -9
- package/src/pyth/index.ts +0 -15
- package/src/pyth/pythLazerSubscriber.ts +0 -365
- package/src/pyth/types.ts +0 -4451
- package/src/pyth/utils.ts +0 -13
- package/src/slot/SlotSubscriber.ts +0 -126
- package/src/slot/SlothashSubscriber.ts +0 -163
- package/src/swap/UnifiedSwapClient.ts +0 -315
- package/src/swift/grpcSignedMsgUserAccountSubscriber.ts +0 -81
- package/src/swift/index.ts +0 -10
- package/src/swift/signedMsgUserAccountSubscriber.ts +0 -251
- package/src/swift/swiftOrderSubscriber.ts +0 -351
- package/src/testClient.ts +0 -42
- package/src/titan/titanClient.ts +0 -438
- package/src/token/index.ts +0 -13
- package/src/tokenFaucet.ts +0 -296
- package/src/tx/baseTxSender.ts +0 -651
- package/src/tx/blockhashFetcher/baseBlockhashFetcher.ts +0 -31
- package/src/tx/blockhashFetcher/cachedBlockhashFetcher.ts +0 -105
- package/src/tx/blockhashFetcher/types.ts +0 -9
- package/src/tx/fastSingleTxSender.ts +0 -200
- package/src/tx/forwardOnlyTxSender.ts +0 -193
- package/src/tx/priorityFeeCalculator.ts +0 -117
- package/src/tx/reportTransactionError.ts +0 -176
- package/src/tx/retryTxSender.ts +0 -177
- package/src/tx/txHandler.ts +0 -1009
- package/src/tx/txParamProcessor.ts +0 -225
- package/src/tx/types.ts +0 -117
- package/src/tx/utils.ts +0 -133
- package/src/tx/whileValidTxSender.ts +0 -377
- package/src/types.ts +0 -2575
- package/src/user.ts +0 -5316
- package/src/userConfig.ts +0 -38
- package/src/userMap/PollingSubscription.ts +0 -61
- package/src/userMap/WebsocketSubscription.ts +0 -93
- package/src/userMap/grpcSubscription.ts +0 -93
- package/src/userMap/referrerMap.ts +0 -360
- package/src/userMap/revenueShareEscrowMap.ts +0 -342
- package/src/userMap/userMap.ts +0 -784
- package/src/userMap/userMapConfig.ts +0 -82
- package/src/userMap/userStatsMap.ts +0 -393
- package/src/userName.ts +0 -37
- package/src/userStats.ts +0 -159
- package/src/userStatsConfig.ts +0 -35
- package/src/util/TransactionConfirmationManager.ts +0 -333
- package/src/util/chainClock.ts +0 -65
- package/src/util/computeUnits.ts +0 -101
- package/src/util/digest.ts +0 -33
- package/src/util/ed25519Utils.ts +0 -95
- package/src/util/promiseTimeout.ts +0 -23
- package/src/velocityClient.ts +0 -14802
- package/src/velocityClientConfig.ts +0 -119
- package/src/wallet.ts +0 -91
- package/tests/VelocityCore/builder_escrow.test.ts +0 -121
- package/tests/VelocityCore/decode.test.ts +0 -16
- package/tests/VelocityCore/fill_trigger.test.ts +0 -73
- package/tests/VelocityCore/instructions.test.ts +0 -46
- package/tests/VelocityCore/pdas.test.ts +0 -30
- package/tests/VelocityCore/perp_orders.test.ts +0 -205
- package/tests/VelocityCore/remainingAccounts.test.ts +0 -72
- package/tests/VelocityCore/settlement_liquidation.test.ts +0 -69
- package/tests/accounts/customizedCadenceBulkAccountLoader.test.ts +0 -211
- package/tests/amm/test.ts +0 -2402
- package/tests/auctions/test.ts +0 -81
- package/tests/bn/test.ts +0 -355
- package/tests/builder/builderFee.test.ts +0 -42
- package/tests/ci/verifyConstants.ts +0 -393
- package/tests/decode/test.ts +0 -262
- package/tests/decode/userAccountBufferStrings.ts +0 -102
- package/tests/dlob/helpers.ts +0 -748
- package/tests/dlob/test.ts +0 -6969
- package/tests/dlob/tickSizeStandardization.ts +0 -545
- package/tests/events/parseLogsForCuUsage.ts +0 -139
- package/tests/exchangeStatus/test.ts +0 -45
- package/tests/insurance/test.ts +0 -40
- package/tests/liquidation/test.ts +0 -125
- package/tests/oracles/mmOracleGate.test.ts +0 -379
- package/tests/oracles/pythPegSnap.test.ts +0 -76
- package/tests/sdkParity/enumParity.test.ts +0 -84
- package/tests/sdkParity/marginCategoryFill.test.ts +0 -143
- package/tests/sdkParity/memcmpOffsets.test.ts +0 -139
- package/tests/spot/test.ts +0 -281
- package/tests/tx/TransactionConfirmationManager.test.ts +0 -312
- package/tests/tx/cachedBlockhashFetcher.test.ts +0 -96
- package/tests/tx/priorityFeeCalculator.ts +0 -77
- package/tests/tx/priorityFeeStrategy.ts +0 -95
- package/tests/user/bankruptcy.ts +0 -165
- package/tests/user/feeAndWithdrawLimits.ts +0 -284
- package/tests/user/getMarginCalculation.ts +0 -586
- package/tests/user/helpers.ts +0 -184
- package/tests/user/liquidations.ts +0 -129
- package/tests/user/marginCalculations.test.ts +0 -321
- package/tests/user/test.ts +0 -833
- package/tsconfig.browser.json +0 -18
- package/tsconfig.json +0 -36
|
@@ -1,695 +0,0 @@
|
|
|
1
|
-
import { BN } from '../isomorphic/anchor';
|
|
2
|
-
import {
|
|
3
|
-
BASE_PRECISION,
|
|
4
|
-
QUOTE_PRECISION,
|
|
5
|
-
ZERO,
|
|
6
|
-
PRICE_PRECISION,
|
|
7
|
-
AMM_TO_QUOTE_PRECISION_RATIO,
|
|
8
|
-
} from '../constants/numericConstants';
|
|
9
|
-
import {
|
|
10
|
-
calculateAmmReservesAfterSwap,
|
|
11
|
-
calculateMarketOpenBidAsk,
|
|
12
|
-
calculateQuoteAssetAmountSwapped,
|
|
13
|
-
calculateSpreadReserves,
|
|
14
|
-
calculateUpdatedAMM,
|
|
15
|
-
} from '../math/amm';
|
|
16
|
-
import { DLOBNode } from './DLOBNode';
|
|
17
|
-
import { isOperationPaused } from '../math/exchangeStatus';
|
|
18
|
-
import {
|
|
19
|
-
isVariant,
|
|
20
|
-
PerpMarketAccount,
|
|
21
|
-
PerpOperation,
|
|
22
|
-
PositionDirection,
|
|
23
|
-
SwapDirection,
|
|
24
|
-
} from '../types';
|
|
25
|
-
import { MMOraclePriceData, OraclePriceData } from '../oracles/types';
|
|
26
|
-
import { PublicKey } from '@solana/web3.js';
|
|
27
|
-
import { standardizeBaseAssetAmount, standardizePrice } from '../math/orders';
|
|
28
|
-
|
|
29
|
-
type liquiditySource = 'vamm' | 'dlob' | 'indicative';
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* A single aggregated price level of an L2 order book: one price with the combined size of all
|
|
33
|
-
* orders resting at (or grouped into) that price, broken down by originating liquidity source.
|
|
34
|
-
*/
|
|
35
|
-
export type L2Level = {
|
|
36
|
-
/** Level price, PRICE_PRECISION (1e6). */
|
|
37
|
-
price: BN;
|
|
38
|
-
/** Total size resting at this price, BASE_PRECISION (1e9). */
|
|
39
|
-
size: BN;
|
|
40
|
-
/** Size contributed by each liquidity source (`'vamm'`, `'dlob'`, `'indicative'`), BASE_PRECISION (1e9). Sources with no contribution are omitted rather than zero. */
|
|
41
|
-
sources: { [key in liquiditySource]?: BN };
|
|
42
|
-
};
|
|
43
|
-
|
|
44
|
-
/** Aggregated (price, size) view of a market's book, as produced by `DLOB.getL2`. */
|
|
45
|
-
export type L2OrderBook = {
|
|
46
|
-
/** Ask levels, ordered from best (lowest price) to worst. */
|
|
47
|
-
asks: L2Level[];
|
|
48
|
-
/** Bid levels, ordered from best (highest price) to worst. */
|
|
49
|
-
bids: L2Level[];
|
|
50
|
-
/** Slot the book was computed at, if the caller supplied one. */
|
|
51
|
-
slot?: number;
|
|
52
|
-
};
|
|
53
|
-
|
|
54
|
-
/** Supplies fallback (non-DLOB) L2 liquidity — e.g. the vAMM — to be merged into `DLOB.getL2`'s output. See `getVammL2Generator`. */
|
|
55
|
-
export interface L2OrderBookGenerator {
|
|
56
|
-
/** Yields ask levels best-first (ascending price). */
|
|
57
|
-
getL2Asks(): Generator<L2Level>;
|
|
58
|
-
/** Yields bid levels best-first (descending price). */
|
|
59
|
-
getL2Bids(): Generator<L2Level>;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
/** A single unaggregated order in an L3 (order-by-order) book view, as produced by `DLOB.getL3`. */
|
|
63
|
-
export type L3Level = {
|
|
64
|
-
/** Order's limit price, PRICE_PRECISION (1e6). */
|
|
65
|
-
price: BN;
|
|
66
|
-
/** Order's remaining (unfilled) size, BASE_PRECISION (1e9). */
|
|
67
|
-
size: BN;
|
|
68
|
-
/** Pubkey of the order's owning `User` account. */
|
|
69
|
-
maker: PublicKey;
|
|
70
|
-
/** The order's `orderId` (unique per maker, not globally). */
|
|
71
|
-
orderId: number;
|
|
72
|
-
};
|
|
73
|
-
|
|
74
|
-
/** Unaggregated, order-by-order view of a market's resting liquidity, as produced by `DLOB.getL3`. Does not include fallback (e.g. vAMM) liquidity. */
|
|
75
|
-
export type L3OrderBook = {
|
|
76
|
-
/** Individual resting ask orders, ordered from best (lowest price) to worst. */
|
|
77
|
-
asks: L3Level[];
|
|
78
|
-
/** Individual resting bid orders, ordered from best (highest price) to worst. */
|
|
79
|
-
bids: L3Level[];
|
|
80
|
-
/** Slot the book was computed at, if the caller supplied one. */
|
|
81
|
-
slot?: number;
|
|
82
|
-
};
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* Default top-of-book quote notional breakpoints ($500/$1000/$2000/$5000, QUOTE_PRECISION 1e6)
|
|
86
|
-
* used by `getVammL2Generator` to produce tighter, more granular vAMM levels near the top of the
|
|
87
|
-
* book for non-major markets before falling back to evenly sized levels for the remaining depth.
|
|
88
|
-
*/
|
|
89
|
-
export const DEFAULT_TOP_OF_BOOK_QUOTE_AMOUNTS = [
|
|
90
|
-
new BN(500).mul(QUOTE_PRECISION),
|
|
91
|
-
new BN(1000).mul(QUOTE_PRECISION),
|
|
92
|
-
new BN(2000).mul(QUOTE_PRECISION),
|
|
93
|
-
new BN(5000).mul(QUOTE_PRECISION),
|
|
94
|
-
];
|
|
95
|
-
|
|
96
|
-
/**
|
|
97
|
-
* Same as `DEFAULT_TOP_OF_BOOK_QUOTE_AMOUNTS` but sized for deeper/more liquid "majors" markets
|
|
98
|
-
* ($5000/$10000/$20000/$50000, QUOTE_PRECISION 1e6). `DLOBSubscriber.getL2` selects this set for
|
|
99
|
-
* `marketIndex < 3`.
|
|
100
|
-
*/
|
|
101
|
-
export const MAJORS_TOP_OF_BOOK_QUOTE_AMOUNTS = [
|
|
102
|
-
new BN(5000).mul(QUOTE_PRECISION),
|
|
103
|
-
new BN(10000).mul(QUOTE_PRECISION),
|
|
104
|
-
new BN(20000).mul(QUOTE_PRECISION),
|
|
105
|
-
new BN(50000).mul(QUOTE_PRECISION),
|
|
106
|
-
];
|
|
107
|
-
|
|
108
|
-
const INDICATIVE_QUOTES_PUBKEY = 'inDNdu3ML4vG5LNExqcwuCQtLcCU8KfK5YM2qYV3JJz';
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* Converts a generator of individual `DLOBNode`s (already sorted best-first, e.g. from
|
|
112
|
-
* `DLOB.getRestingLimitAsks`/`getRestingLimitBids`) into a generator of `L2Level`s — one level
|
|
113
|
-
* per node, not yet merged by price (merging/deduping happens in `createL2Levels`). Nodes with
|
|
114
|
-
* no order or with zero remaining size are skipped. A node owned by the well-known indicative
|
|
115
|
-
* quotes pubkey is tagged as `sources.indicative` instead of `sources.dlob`.
|
|
116
|
-
*
|
|
117
|
-
* @param dlobNodes sorted node generator, e.g. `DLOB.getRestingLimitAsks` or `DLOB.getRestingLimitBids`
|
|
118
|
-
* @param oraclePriceData oracle price data used to resolve each node's limit price
|
|
119
|
-
* @param slot current slot, used to resolve each node's limit price
|
|
120
|
-
* @param tickSize market order tick size, PRICE_PRECISION (1e6); passed through to `DLOBNode.getPriceOrThrow`
|
|
121
|
-
* @returns a generator of `L2Level`s, one per DLOB node with remaining size
|
|
122
|
-
* @throws if any yielded node has no resolvable limit price (via `getPriceOrThrow`)
|
|
123
|
-
*/
|
|
124
|
-
export function* getL2GeneratorFromDLOBNodes(
|
|
125
|
-
dlobNodes: Generator<DLOBNode>,
|
|
126
|
-
oraclePriceData: OraclePriceData,
|
|
127
|
-
slot: number,
|
|
128
|
-
tickSize?: BN
|
|
129
|
-
): Generator<L2Level> {
|
|
130
|
-
for (const dlobNode of dlobNodes) {
|
|
131
|
-
if (!dlobNode.order) {
|
|
132
|
-
continue;
|
|
133
|
-
}
|
|
134
|
-
const size = dlobNode.baseAssetAmount.sub(
|
|
135
|
-
dlobNode.order.baseAssetAmountFilled
|
|
136
|
-
) as BN;
|
|
137
|
-
|
|
138
|
-
if (size.lte(ZERO)) {
|
|
139
|
-
continue;
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
yield {
|
|
143
|
-
size,
|
|
144
|
-
price: dlobNode.getPriceOrThrow(oraclePriceData, slot, tickSize),
|
|
145
|
-
sources:
|
|
146
|
-
dlobNode.userAccount == INDICATIVE_QUOTES_PUBKEY
|
|
147
|
-
? { indicative: size }
|
|
148
|
-
: {
|
|
149
|
-
dlob: size,
|
|
150
|
-
},
|
|
151
|
-
};
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* Merges multiple already-sorted `L2Level` generators (e.g. DLOB liquidity plus one or more
|
|
157
|
-
* fallback sources) into a single sorted generator, using a k-way merge. Does not merge/dedupe
|
|
158
|
-
* levels that land on the same price across generators — see `createL2Levels` for that.
|
|
159
|
-
*
|
|
160
|
-
* @param l2LevelGenerators generators to merge, each already sorted in the desired final order
|
|
161
|
-
* @param compare returns true if `a` should be yielded before `b` (e.g. `a.price.lt(b.price)` for asks)
|
|
162
|
-
* @returns a single generator yielding levels in the order defined by `compare`
|
|
163
|
-
*/
|
|
164
|
-
export function* mergeL2LevelGenerators(
|
|
165
|
-
l2LevelGenerators: Generator<L2Level>[],
|
|
166
|
-
compare: (a: L2Level, b: L2Level) => boolean
|
|
167
|
-
): Generator<L2Level> {
|
|
168
|
-
type GeneratorState = {
|
|
169
|
-
generator: Generator<L2Level>;
|
|
170
|
-
next: IteratorResult<L2Level>;
|
|
171
|
-
};
|
|
172
|
-
|
|
173
|
-
const generators: GeneratorState[] = l2LevelGenerators.map((generator) => {
|
|
174
|
-
return {
|
|
175
|
-
generator,
|
|
176
|
-
next: generator.next(),
|
|
177
|
-
};
|
|
178
|
-
});
|
|
179
|
-
|
|
180
|
-
let next: GeneratorState | undefined;
|
|
181
|
-
do {
|
|
182
|
-
next = generators.reduce<GeneratorState | undefined>((best, next) => {
|
|
183
|
-
if (next.next.done) {
|
|
184
|
-
return best;
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
if (!best) {
|
|
188
|
-
return next;
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
if (compare(next.next.value, best.next.value)) {
|
|
192
|
-
return next;
|
|
193
|
-
} else {
|
|
194
|
-
return best;
|
|
195
|
-
}
|
|
196
|
-
}, undefined);
|
|
197
|
-
|
|
198
|
-
if (next) {
|
|
199
|
-
yield next.next.value;
|
|
200
|
-
next.next = next.generator.next();
|
|
201
|
-
}
|
|
202
|
-
} while (next !== undefined);
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
/**
|
|
206
|
-
* Materializes a sorted `L2Level` generator into an array, merging consecutive levels that share
|
|
207
|
-
* the same price (summing size and per-source sizes) and capping the result at `depth` distinct
|
|
208
|
-
* price levels.
|
|
209
|
-
*
|
|
210
|
-
* @param generator sorted level generator, e.g. output of `mergeL2LevelGenerators`
|
|
211
|
-
* @param depth maximum number of distinct price levels to return
|
|
212
|
-
* @returns up to `depth` merged `L2Level`s
|
|
213
|
-
*/
|
|
214
|
-
export function createL2Levels(
|
|
215
|
-
generator: Generator<L2Level>,
|
|
216
|
-
depth: number
|
|
217
|
-
): L2Level[] {
|
|
218
|
-
const levels = [];
|
|
219
|
-
for (const level of generator) {
|
|
220
|
-
const price = level.price;
|
|
221
|
-
const size = level.size;
|
|
222
|
-
if (levels.length > 0 && levels[levels.length - 1].price.eq(price)) {
|
|
223
|
-
const currentLevel = levels[levels.length - 1];
|
|
224
|
-
currentLevel.size = currentLevel.size.add(size);
|
|
225
|
-
for (const [source, size] of Object.entries(level.sources) as [
|
|
226
|
-
liquiditySource,
|
|
227
|
-
BN,
|
|
228
|
-
][]) {
|
|
229
|
-
const existingSize = currentLevel.sources[source];
|
|
230
|
-
if (existingSize) {
|
|
231
|
-
currentLevel.sources[source] = existingSize.add(size);
|
|
232
|
-
} else {
|
|
233
|
-
currentLevel.sources[source] = size;
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
} else if (levels.length === depth) {
|
|
237
|
-
break;
|
|
238
|
-
} else {
|
|
239
|
-
levels.push(level);
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
return levels;
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
/**
|
|
246
|
-
* Builds an `L2OrderBookGenerator` that synthesizes vAMM (virtual AMM) liquidity levels for a
|
|
247
|
-
* perp market, for use as fallback liquidity in `DLOB.getL2`. Simulates walking the AMM's
|
|
248
|
-
* spread-adjusted reserves outward from the mid price on each side, standardizing prices to the
|
|
249
|
-
* market's `orderTickSize` and sizes to its `orderStepSize`. Returns zero liquidity on a side
|
|
250
|
-
* entirely if AMM fills are paused (`PerpOperation.AMM_FILL`) or if that side's open liquidity is
|
|
251
|
-
* less than 2x the market's `minOrderSize`.
|
|
252
|
-
*
|
|
253
|
-
* @param marketAccount perp market whose AMM reserves/config drive the simulated levels
|
|
254
|
-
* @param mmOraclePriceData market-maker oracle price data used to reprice the AMM before walking it
|
|
255
|
-
* @param numOrders total number of levels to generate per side (including any top-of-book levels)
|
|
256
|
-
* @param now unix timestamp (seconds) used for spread-reserve calculation; defaults to the current time
|
|
257
|
-
* @param topOfBookQuoteAmounts quote-notional breakpoints (QUOTE_PRECISION, 1e6) used to size the
|
|
258
|
-
* first levels more granularly near the top of book — see `DEFAULT_TOP_OF_BOOK_QUOTE_AMOUNTS` /
|
|
259
|
-
* `MAJORS_TOP_OF_BOOK_QUOTE_AMOUNTS`; defaults to `[]` (all levels evenly sized)
|
|
260
|
-
* @param latestSlot most recent known slot, improves spread-reserve accuracy when provided; optional
|
|
261
|
-
* @returns a generator pair (`getL2Bids`/`getL2Asks`) yielding vAMM `L2Level`s, best price first,
|
|
262
|
-
* each tagged with `sources.vamm`
|
|
263
|
-
*/
|
|
264
|
-
export function getVammL2Generator({
|
|
265
|
-
marketAccount,
|
|
266
|
-
mmOraclePriceData,
|
|
267
|
-
numOrders,
|
|
268
|
-
now = new BN(Math.floor(Date.now() / 1000)),
|
|
269
|
-
topOfBookQuoteAmounts = [],
|
|
270
|
-
latestSlot,
|
|
271
|
-
}: {
|
|
272
|
-
marketAccount: PerpMarketAccount;
|
|
273
|
-
mmOraclePriceData: MMOraclePriceData;
|
|
274
|
-
numOrders: number;
|
|
275
|
-
now?: BN;
|
|
276
|
-
topOfBookQuoteAmounts?: BN[];
|
|
277
|
-
latestSlot?: BN;
|
|
278
|
-
}): L2OrderBookGenerator {
|
|
279
|
-
const updatedAmm = calculateUpdatedAMM(marketAccount.amm, mmOraclePriceData);
|
|
280
|
-
const paused = isOperationPaused(
|
|
281
|
-
marketAccount.pausedOperations,
|
|
282
|
-
PerpOperation.AMM_FILL
|
|
283
|
-
);
|
|
284
|
-
let [openBids, openAsks] = paused
|
|
285
|
-
? [ZERO, ZERO]
|
|
286
|
-
: calculateMarketOpenBidAsk(
|
|
287
|
-
updatedAmm.baseAssetReserve,
|
|
288
|
-
updatedAmm.minBaseAssetReserve,
|
|
289
|
-
updatedAmm.maxBaseAssetReserve,
|
|
290
|
-
marketAccount.orderStepSize
|
|
291
|
-
);
|
|
292
|
-
|
|
293
|
-
if (openBids.lt(marketAccount.marketStats.minOrderSize.muln(2)))
|
|
294
|
-
openBids = ZERO;
|
|
295
|
-
if (openAsks.abs().lt(marketAccount.marketStats.minOrderSize.muln(2)))
|
|
296
|
-
openAsks = ZERO;
|
|
297
|
-
|
|
298
|
-
const [bidReserves, askReserves] = calculateSpreadReserves(
|
|
299
|
-
updatedAmm,
|
|
300
|
-
marketAccount.marketStats,
|
|
301
|
-
mmOraclePriceData,
|
|
302
|
-
now,
|
|
303
|
-
latestSlot
|
|
304
|
-
);
|
|
305
|
-
|
|
306
|
-
const numBaseOrders = Math.max(1, numOrders - topOfBookQuoteAmounts.length);
|
|
307
|
-
const commonOpts = {
|
|
308
|
-
numOrders,
|
|
309
|
-
numBaseOrders,
|
|
310
|
-
mmOraclePriceData,
|
|
311
|
-
orderTickSize: marketAccount.orderTickSize,
|
|
312
|
-
orderStepSize: marketAccount.orderStepSize,
|
|
313
|
-
pegMultiplier: updatedAmm.pegMultiplier,
|
|
314
|
-
sqrtK: updatedAmm.sqrtK,
|
|
315
|
-
topOfBookQuoteAmounts,
|
|
316
|
-
};
|
|
317
|
-
|
|
318
|
-
const makeL2Gen = ({
|
|
319
|
-
openLiquidity,
|
|
320
|
-
startReserves,
|
|
321
|
-
swapDir,
|
|
322
|
-
positionDir,
|
|
323
|
-
}: {
|
|
324
|
-
openLiquidity: BN;
|
|
325
|
-
startReserves: { baseAssetReserve: BN; quoteAssetReserve: BN };
|
|
326
|
-
swapDir: SwapDirection;
|
|
327
|
-
positionDir: PositionDirection;
|
|
328
|
-
}) => {
|
|
329
|
-
return function* () {
|
|
330
|
-
let count = 0;
|
|
331
|
-
let topSize = ZERO;
|
|
332
|
-
let size = openLiquidity.abs().divn(commonOpts.numBaseOrders);
|
|
333
|
-
const amm = {
|
|
334
|
-
...startReserves,
|
|
335
|
-
sqrtK: commonOpts.sqrtK,
|
|
336
|
-
pegMultiplier: commonOpts.pegMultiplier,
|
|
337
|
-
};
|
|
338
|
-
|
|
339
|
-
while (count < commonOpts.numOrders && size.gt(ZERO)) {
|
|
340
|
-
let baseSwap = size;
|
|
341
|
-
if (count < commonOpts.topOfBookQuoteAmounts.length) {
|
|
342
|
-
const raw = commonOpts.topOfBookQuoteAmounts[count]
|
|
343
|
-
.mul(AMM_TO_QUOTE_PRECISION_RATIO)
|
|
344
|
-
.mul(PRICE_PRECISION)
|
|
345
|
-
.div(commonOpts.mmOraclePriceData.price);
|
|
346
|
-
baseSwap = standardizeBaseAssetAmount(raw, commonOpts.orderStepSize);
|
|
347
|
-
const remaining = openLiquidity.abs().sub(topSize);
|
|
348
|
-
if (remaining.lt(baseSwap)) baseSwap = remaining;
|
|
349
|
-
}
|
|
350
|
-
if (baseSwap.isZero()) return;
|
|
351
|
-
|
|
352
|
-
const [newQuoteRes, newBaseRes] = calculateAmmReservesAfterSwap(
|
|
353
|
-
amm,
|
|
354
|
-
'base',
|
|
355
|
-
baseSwap,
|
|
356
|
-
swapDir
|
|
357
|
-
);
|
|
358
|
-
const quoteSwapped = calculateQuoteAssetAmountSwapped(
|
|
359
|
-
amm.quoteAssetReserve.sub(newQuoteRes).abs(),
|
|
360
|
-
amm.pegMultiplier,
|
|
361
|
-
swapDir
|
|
362
|
-
);
|
|
363
|
-
const price = standardizePrice(
|
|
364
|
-
quoteSwapped.mul(BASE_PRECISION).div(baseSwap),
|
|
365
|
-
commonOpts.orderTickSize,
|
|
366
|
-
positionDir
|
|
367
|
-
);
|
|
368
|
-
|
|
369
|
-
amm.baseAssetReserve = newBaseRes;
|
|
370
|
-
amm.quoteAssetReserve = newQuoteRes;
|
|
371
|
-
|
|
372
|
-
if (count < commonOpts.topOfBookQuoteAmounts.length) {
|
|
373
|
-
topSize = topSize.add(baseSwap);
|
|
374
|
-
size = openLiquidity
|
|
375
|
-
.abs()
|
|
376
|
-
.sub(topSize)
|
|
377
|
-
.divn(commonOpts.numBaseOrders);
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
yield { price, size: baseSwap, sources: { vamm: baseSwap } };
|
|
381
|
-
count++;
|
|
382
|
-
}
|
|
383
|
-
};
|
|
384
|
-
};
|
|
385
|
-
|
|
386
|
-
return {
|
|
387
|
-
getL2Bids: makeL2Gen({
|
|
388
|
-
openLiquidity: openBids,
|
|
389
|
-
startReserves: bidReserves,
|
|
390
|
-
swapDir: SwapDirection.ADD,
|
|
391
|
-
positionDir: PositionDirection.LONG,
|
|
392
|
-
}),
|
|
393
|
-
getL2Asks: makeL2Gen({
|
|
394
|
-
openLiquidity: openAsks,
|
|
395
|
-
startReserves: askReserves,
|
|
396
|
-
swapDir: SwapDirection.REMOVE,
|
|
397
|
-
positionDir: PositionDirection.SHORT,
|
|
398
|
-
}),
|
|
399
|
-
};
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
/**
|
|
403
|
-
* Re-buckets an `L2OrderBook`'s levels onto a coarser price grid ("grouping"), summing size and
|
|
404
|
-
* per-source sizes of levels that land in the same bucket, and truncating each side to `depth`
|
|
405
|
-
* levels. Bids are standardized down (grouped toward the taker-friendly direction for longs),
|
|
406
|
-
* asks standardized up, matching on-chain price standardization semantics.
|
|
407
|
-
*
|
|
408
|
-
* @param l2 the ungrouped order book, e.g. from `DLOB.getL2`
|
|
409
|
-
* @param grouping price bucket size, PRICE_PRECISION (1e6) — must be a multiple of the market's tick size to produce valid on-chain prices
|
|
410
|
-
* @param depth maximum number of levels to keep per side after grouping
|
|
411
|
-
* @returns a new `L2OrderBook` with grouped bids/asks (does not mutate `l2`)
|
|
412
|
-
*/
|
|
413
|
-
export function groupL2(
|
|
414
|
-
l2: L2OrderBook,
|
|
415
|
-
grouping: BN,
|
|
416
|
-
depth: number
|
|
417
|
-
): L2OrderBook {
|
|
418
|
-
return {
|
|
419
|
-
bids: groupL2Levels(l2.bids, grouping, PositionDirection.LONG, depth),
|
|
420
|
-
asks: groupL2Levels(l2.asks, grouping, PositionDirection.SHORT, depth),
|
|
421
|
-
slot: l2.slot,
|
|
422
|
-
};
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
function cloneL2Level(level: L2Level): L2Level {
|
|
426
|
-
if (!level) return level;
|
|
427
|
-
|
|
428
|
-
return {
|
|
429
|
-
price: level.price,
|
|
430
|
-
size: level.size,
|
|
431
|
-
sources: { ...level.sources },
|
|
432
|
-
};
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
function groupL2Levels(
|
|
436
|
-
levels: L2Level[],
|
|
437
|
-
grouping: BN,
|
|
438
|
-
direction: PositionDirection,
|
|
439
|
-
depth: number
|
|
440
|
-
): L2Level[] {
|
|
441
|
-
const groupedLevels: L2Level[] = [];
|
|
442
|
-
for (const level of levels) {
|
|
443
|
-
const price = standardizePrice(level.price, grouping, direction);
|
|
444
|
-
const size = level.size;
|
|
445
|
-
if (
|
|
446
|
-
groupedLevels.length > 0 &&
|
|
447
|
-
groupedLevels[groupedLevels.length - 1].price.eq(price)
|
|
448
|
-
) {
|
|
449
|
-
// Clones things so we don't mutate the original
|
|
450
|
-
const currentLevel = cloneL2Level(
|
|
451
|
-
groupedLevels[groupedLevels.length - 1]
|
|
452
|
-
);
|
|
453
|
-
|
|
454
|
-
currentLevel.size = currentLevel.size.add(size);
|
|
455
|
-
for (const [source, size] of Object.entries(level.sources) as [
|
|
456
|
-
liquiditySource,
|
|
457
|
-
BN,
|
|
458
|
-
][]) {
|
|
459
|
-
const existingSize = currentLevel.sources[source];
|
|
460
|
-
if (existingSize) {
|
|
461
|
-
currentLevel.sources[source] = existingSize.add(size);
|
|
462
|
-
} else {
|
|
463
|
-
currentLevel.sources[source] = size;
|
|
464
|
-
}
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
groupedLevels[groupedLevels.length - 1] = currentLevel;
|
|
468
|
-
} else {
|
|
469
|
-
const groupedLevel = {
|
|
470
|
-
price: price,
|
|
471
|
-
size,
|
|
472
|
-
sources: level.sources,
|
|
473
|
-
};
|
|
474
|
-
groupedLevels.push(groupedLevel);
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
if (groupedLevels.length === depth) {
|
|
478
|
-
break;
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
|
-
return groupedLevels;
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
/**
|
|
485
|
-
* Method to merge bids or asks by price
|
|
486
|
-
*/
|
|
487
|
-
const mergeByPrice = (bidsOrAsks: L2Level[]) => {
|
|
488
|
-
const merged = new Map<string, L2Level>();
|
|
489
|
-
for (const level of bidsOrAsks) {
|
|
490
|
-
const key = level.price.toString();
|
|
491
|
-
const existing = merged.get(key);
|
|
492
|
-
if (existing) {
|
|
493
|
-
existing.size = existing.size.add(level.size);
|
|
494
|
-
for (const [source, size] of Object.entries(level.sources) as [
|
|
495
|
-
liquiditySource,
|
|
496
|
-
BN,
|
|
497
|
-
][]) {
|
|
498
|
-
const existingSize = existing.sources[source];
|
|
499
|
-
if (existingSize) {
|
|
500
|
-
existing.sources[source] = existingSize.add(size);
|
|
501
|
-
} else {
|
|
502
|
-
existing.sources[source] = size;
|
|
503
|
-
}
|
|
504
|
-
}
|
|
505
|
-
} else {
|
|
506
|
-
merged.set(key, cloneL2Level(level));
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
return Array.from(merged.values());
|
|
510
|
-
};
|
|
511
|
-
|
|
512
|
-
/**
|
|
513
|
-
* The purpose of this function is uncross the L2 orderbook by modifying the bid/ask price at the top of the book
|
|
514
|
-
* This will make the liquidity look worse but more intuitive (users familiar with clob get confused w temporarily
|
|
515
|
-
* crossing book)
|
|
516
|
-
*
|
|
517
|
-
* Things to note about how it works:
|
|
518
|
-
* - it will not uncross the user's liquidity
|
|
519
|
-
* - it does the uncrossing by "shifting" the crossing liquidity to the nearest uncrossed levels. Thus the output liquidity maintains the same total size.
|
|
520
|
-
*
|
|
521
|
-
* No-ops (returns `bids`/`asks` unchanged) if either side is empty, or if the top of book is
|
|
522
|
-
* already uncrossed (`bids[0].price < asks[0].price`).
|
|
523
|
-
*
|
|
524
|
-
* @param bids bid levels, PRICE_PRECISION (1e6) prices, best (highest) first
|
|
525
|
-
* @param asks ask levels, PRICE_PRECISION (1e6) prices, best (lowest) first
|
|
526
|
-
* @param oraclePrice current oracle price, PRICE_PRECISION (1e6)
|
|
527
|
-
* @param oracleTwap5Min 5-minute oracle price TWAP, PRICE_PRECISION (1e6)
|
|
528
|
-
* @param markTwap5Min 5-minute mark price TWAP, PRICE_PRECISION (1e6); `markTwap5Min - oracleTwap5Min` estimates the market's premium/discount to oracle, used as the reference point crossing liquidity is shifted around
|
|
529
|
-
* @param grouping minimum price gap to enforce between the shifted bid/ask, PRICE_PRECISION (1e6)
|
|
530
|
-
* @param userBids set of bid price strings (`BN.toString()`) belonging to the requesting user, which are left untouched rather than shifted
|
|
531
|
-
* @param userAsks set of ask price strings (`BN.toString()`) belonging to the requesting user, which are left untouched rather than shifted
|
|
532
|
-
* @returns new `bids`/`asks` arrays with crossing levels shifted apart by at least `grouping`; total size per side is preserved
|
|
533
|
-
*/
|
|
534
|
-
export function uncrossL2(
|
|
535
|
-
bids: L2Level[],
|
|
536
|
-
asks: L2Level[],
|
|
537
|
-
oraclePrice: BN,
|
|
538
|
-
oracleTwap5Min: BN,
|
|
539
|
-
markTwap5Min: BN,
|
|
540
|
-
grouping: BN,
|
|
541
|
-
userBids: Set<string>,
|
|
542
|
-
userAsks: Set<string>
|
|
543
|
-
): { bids: L2Level[]; asks: L2Level[] } {
|
|
544
|
-
// If there are no bids or asks, there is nothing to center
|
|
545
|
-
if (bids.length === 0 || asks.length === 0) {
|
|
546
|
-
return { bids, asks };
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
// If the top of the book is already centered, there is nothing to do
|
|
550
|
-
if (bids[0].price.lt(asks[0].price)) {
|
|
551
|
-
return { bids, asks };
|
|
552
|
-
}
|
|
553
|
-
|
|
554
|
-
const newBids: L2Level[] = [];
|
|
555
|
-
const newAsks: L2Level[] = [];
|
|
556
|
-
|
|
557
|
-
const updateLevels = (newPrice: BN, oldLevel: L2Level, levels: L2Level[]) => {
|
|
558
|
-
if (levels.length > 0 && levels[levels.length - 1].price.eq(newPrice)) {
|
|
559
|
-
levels[levels.length - 1].size = levels[levels.length - 1].size.add(
|
|
560
|
-
oldLevel.size
|
|
561
|
-
);
|
|
562
|
-
for (const [source, size] of Object.entries(oldLevel.sources) as [
|
|
563
|
-
liquiditySource,
|
|
564
|
-
BN,
|
|
565
|
-
][]) {
|
|
566
|
-
const existingSize = levels[levels.length - 1].sources[source];
|
|
567
|
-
if (existingSize) {
|
|
568
|
-
levels[levels.length - 1].sources = {
|
|
569
|
-
...levels[levels.length - 1].sources,
|
|
570
|
-
[source]: existingSize.add(size),
|
|
571
|
-
};
|
|
572
|
-
} else {
|
|
573
|
-
levels[levels.length - 1].sources[source] = size;
|
|
574
|
-
}
|
|
575
|
-
}
|
|
576
|
-
} else {
|
|
577
|
-
levels.push({
|
|
578
|
-
price: newPrice,
|
|
579
|
-
size: oldLevel.size,
|
|
580
|
-
sources: oldLevel.sources,
|
|
581
|
-
});
|
|
582
|
-
}
|
|
583
|
-
};
|
|
584
|
-
|
|
585
|
-
// This is the best estimate of the premium in the market vs oracle to filter crossing around
|
|
586
|
-
const referencePrice = oraclePrice.add(markTwap5Min.sub(oracleTwap5Min));
|
|
587
|
-
|
|
588
|
-
let bidIndex = 0;
|
|
589
|
-
let askIndex = 0;
|
|
590
|
-
let maxBid: BN | undefined;
|
|
591
|
-
let minAsk: BN | undefined;
|
|
592
|
-
|
|
593
|
-
const getPriceAndSetBound = (newPrice: BN, direction: PositionDirection) => {
|
|
594
|
-
if (isVariant(direction, 'long')) {
|
|
595
|
-
maxBid = maxBid ? BN.min(maxBid, newPrice) : newPrice;
|
|
596
|
-
return maxBid;
|
|
597
|
-
} else {
|
|
598
|
-
minAsk = minAsk ? BN.max(minAsk, newPrice) : newPrice;
|
|
599
|
-
return minAsk;
|
|
600
|
-
}
|
|
601
|
-
};
|
|
602
|
-
|
|
603
|
-
while (bidIndex < bids.length || askIndex < asks.length) {
|
|
604
|
-
const nextBid = cloneL2Level(bids[bidIndex]);
|
|
605
|
-
const nextAsk = cloneL2Level(asks[askIndex]);
|
|
606
|
-
|
|
607
|
-
if (!nextBid) {
|
|
608
|
-
newAsks.push(nextAsk);
|
|
609
|
-
askIndex++;
|
|
610
|
-
continue;
|
|
611
|
-
}
|
|
612
|
-
|
|
613
|
-
if (!nextAsk) {
|
|
614
|
-
newBids.push(nextBid);
|
|
615
|
-
bidIndex++;
|
|
616
|
-
continue;
|
|
617
|
-
}
|
|
618
|
-
|
|
619
|
-
if (userBids.has(nextBid.price.toString())) {
|
|
620
|
-
newBids.push(nextBid);
|
|
621
|
-
bidIndex++;
|
|
622
|
-
continue;
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
if (userAsks.has(nextAsk.price.toString())) {
|
|
626
|
-
newAsks.push(nextAsk);
|
|
627
|
-
askIndex++;
|
|
628
|
-
continue;
|
|
629
|
-
}
|
|
630
|
-
|
|
631
|
-
if (nextBid.price.gte(nextAsk.price)) {
|
|
632
|
-
if (
|
|
633
|
-
nextBid.price.gt(referencePrice) &&
|
|
634
|
-
nextAsk.price.gt(referencePrice)
|
|
635
|
-
) {
|
|
636
|
-
let newBidPrice = nextAsk.price.sub(grouping);
|
|
637
|
-
newBidPrice = getPriceAndSetBound(newBidPrice, PositionDirection.LONG);
|
|
638
|
-
updateLevels(newBidPrice, nextBid, newBids);
|
|
639
|
-
bidIndex++;
|
|
640
|
-
} else if (
|
|
641
|
-
nextAsk.price.lt(referencePrice) &&
|
|
642
|
-
nextBid.price.lt(referencePrice)
|
|
643
|
-
) {
|
|
644
|
-
let newAskPrice = nextBid.price.add(grouping);
|
|
645
|
-
newAskPrice = getPriceAndSetBound(newAskPrice, PositionDirection.SHORT);
|
|
646
|
-
updateLevels(newAskPrice, nextAsk, newAsks);
|
|
647
|
-
askIndex++;
|
|
648
|
-
} else {
|
|
649
|
-
let newBidPrice = referencePrice.sub(grouping);
|
|
650
|
-
let newAskPrice = referencePrice.add(grouping);
|
|
651
|
-
|
|
652
|
-
newBidPrice = getPriceAndSetBound(newBidPrice, PositionDirection.LONG);
|
|
653
|
-
newAskPrice = getPriceAndSetBound(newAskPrice, PositionDirection.SHORT);
|
|
654
|
-
|
|
655
|
-
updateLevels(newBidPrice, nextBid, newBids);
|
|
656
|
-
updateLevels(newAskPrice, nextAsk, newAsks);
|
|
657
|
-
bidIndex++;
|
|
658
|
-
askIndex++;
|
|
659
|
-
}
|
|
660
|
-
} else {
|
|
661
|
-
if (minAsk && nextAsk.price.lte(minAsk)) {
|
|
662
|
-
const newAskPrice = getPriceAndSetBound(
|
|
663
|
-
nextAsk.price,
|
|
664
|
-
PositionDirection.SHORT
|
|
665
|
-
);
|
|
666
|
-
updateLevels(newAskPrice, nextAsk, newAsks);
|
|
667
|
-
} else {
|
|
668
|
-
newAsks.push(nextAsk);
|
|
669
|
-
}
|
|
670
|
-
askIndex++;
|
|
671
|
-
|
|
672
|
-
if (maxBid && nextBid.price.gte(maxBid)) {
|
|
673
|
-
const newBidPrice = getPriceAndSetBound(
|
|
674
|
-
nextBid.price,
|
|
675
|
-
PositionDirection.LONG
|
|
676
|
-
);
|
|
677
|
-
updateLevels(newBidPrice, nextBid, newBids);
|
|
678
|
-
} else {
|
|
679
|
-
newBids.push(nextBid);
|
|
680
|
-
}
|
|
681
|
-
bidIndex++;
|
|
682
|
-
}
|
|
683
|
-
}
|
|
684
|
-
|
|
685
|
-
newBids.sort((a, b) => b.price.cmp(a.price));
|
|
686
|
-
newAsks.sort((a, b) => a.price.cmp(b.price));
|
|
687
|
-
|
|
688
|
-
const finalNewBids = mergeByPrice(newBids);
|
|
689
|
-
const finalNewAsks = mergeByPrice(newAsks);
|
|
690
|
-
|
|
691
|
-
return {
|
|
692
|
-
bids: finalNewBids,
|
|
693
|
-
asks: finalNewAsks,
|
|
694
|
-
};
|
|
695
|
-
}
|