From 6522990333754e1ff8e72cb3b137c502dca6f541 Mon Sep 17 00:00:00 2001 From: Jack Waller Date: Tue, 10 Jun 2025 17:08:27 +1000 Subject: [PATCH 1/3] chore: reduce number of levels sent to UI --- src/dlob-subscriber/DLOBSubscriberIO.ts | 32 + src/publishers/dlobPublisher.ts | 8 +- src/templates/full.html | 787 ++++++++++++++++++++++++ src/utils/utils.ts | 50 ++ src/wsConnectionManager.ts | 7 +- 5 files changed, 879 insertions(+), 5 deletions(-) create mode 100644 src/templates/full.html diff --git a/src/dlob-subscriber/DLOBSubscriberIO.ts b/src/dlob-subscriber/DLOBSubscriberIO.ts index 5acbc7a..0287d78 100644 --- a/src/dlob-subscriber/DLOBSubscriberIO.ts +++ b/src/dlob-subscriber/DLOBSubscriberIO.ts @@ -1,14 +1,17 @@ import { BN, + BigNum, DLOBSubscriber, DLOBSubscriptionConfig, DriftEnv, L2OrderBookGenerator, MarketType, + ONE, Order, OrderStatus, OrderTriggerCondition, OrderType, + PRICE_PRECISION, PerpOperation, PositionDirection, ZERO, @@ -21,6 +24,7 @@ import { SubscriberLookup, addMarketSlotToResponse, addOracletoResponse, + aggregatePrices, l2WithBNToStrings, parsePositiveIntArray, } from '../utils/utils'; @@ -35,10 +39,12 @@ type wsMarketArgs = { numVammOrders?: number; fallbackL2Generators?: L2OrderBookGenerator[]; updateOnChange?: boolean; + tickSize?: BN }; require('dotenv').config(); +export const GROUPING_OPTIONS = [1, 10, 100, 500, 1000]; const PERP_MAKRET_STALENESS_THRESHOLD = 30 * 60 * 1000; const SPOT_MAKRET_STALENESS_THRESHOLD = 60 * 60 * 1000; const STALE_ORACLE_REMOVE_VAMM_THRESHOLD = 160; @@ -114,6 +120,7 @@ export class DLOBSubscriberIO extends DLOBSubscriber { includeVamm, updateOnChange: false, fallbackL2Generators: [], + tickSize: perpMarket?.amm?.orderTickSize ?? ONE }); } for (const market of config.spotMarketInfos) { @@ -128,6 +135,7 @@ export class DLOBSubscriberIO extends DLOBSubscriber { config.spotMarketSubscribers[market.marketIndex].phoenix, config.spotMarketSubscribers[market.marketIndex].openbook, ].filter((a) => !!a), + tickSize: config.spotMarketSubscribers[market.marketIndex].tickSize ?? ONE }); } } @@ -391,6 +399,30 @@ export class DLOBSubscriberIO extends DLOBSubscriber { }`, l2Formatted_depth100 ); + + GROUPING_OPTIONS.forEach(group => { + const pricePrecision = BigNum.from(group).mul(marketArgs.tickSize).toNum() + const aggregatedBids = aggregatePrices(l2Formatted.bids, 'bid', pricePrecision) + .sort((a, b) => b[0] - a[0]) + .slice(0, 20) + + const aggregatedAsks = aggregatePrices(l2Formatted.asks, 'ask', pricePrecision) + .sort((a, b) => a[0] - b[0]) + .slice(0, 20) + + const l2Formatted_grouped20 = Object.assign({}, l2Formatted, { + bids: aggregatedBids, + asks: aggregatedAsks, + }); + + this.redisClient.publish( + `${clientPrefix}orderbook_${marketType}_${marketArgs.marketIndex}_grouped_${group}${ + this.indicativeQuotesRedisClient ? '_indicative' : '' + }`, + l2Formatted_grouped20 + ); + }) + if (!this.indicativeQuotesRedisClient) { const bids = this.dlob diff --git a/src/publishers/dlobPublisher.ts b/src/publishers/dlobPublisher.ts index 2432be0..694b457 100644 --- a/src/publishers/dlobPublisher.ts +++ b/src/publishers/dlobPublisher.ts @@ -20,6 +20,7 @@ import { PhoenixSubscriber, MarketType, OraclePriceData, + ONE, } from '@drift-labs/sdk'; import { RedisClient, RedisClientPrefix } from '@drift/common/clients'; @@ -114,10 +115,7 @@ const KILLSWITCH_SLOT_DIFF_THRESHOLD = parseInt(process.env.KILLSWITCH_SLOT_DIFF_THRESHOLD) || 200; // comma separated list of perp market indexes to load: i.e. 0,1,2,3 -const PERP_MARKETS_TO_LOAD = - process.env.PERP_MARKETS_TO_LOAD !== undefined - ? parsePositiveIntArray(process.env.PERP_MARKETS_TO_LOAD) - : undefined; +const PERP_MARKETS_TO_LOAD = [0] // comma separated list of spot market indexes to load: i.e. 0,1,2,3 const SPOT_MARKETS_TO_LOAD = @@ -299,6 +297,8 @@ const initializeAllMarketSubscribers = async (driftClient: DriftClient) => { } } } + + markets[market.marketIndex].tickSize = market?.orderTickSize ?? ONE } return markets; diff --git a/src/templates/full.html b/src/templates/full.html new file mode 100644 index 0000000..ae8c50c --- /dev/null +++ b/src/templates/full.html @@ -0,0 +1,787 @@ + + + + + + Drift Orderbook (full) + + + + + +
Disconnected
+ +
+
+
Bids
+
+ Price + Size + Total +
+
+
+
+
Asks
+
+ Price + Size + Total +
+
+
+
+ +
+
+ Connection Log + Show Log +
+
+
+ + + + diff --git a/src/utils/utils.ts b/src/utils/utils.ts index 329a95c..b80257b 100644 --- a/src/utils/utils.ts +++ b/src/utils/utils.ts @@ -1,6 +1,8 @@ import { + BN, DriftClient, DriftEnv, + L2Level, L2OrderBook, L3OrderBook, MarketType, @@ -171,6 +173,53 @@ export const addMarketSlotToResponse = ( response['marketSlot'] = marketSlot; }; +export function aggregatePrices(entries, side, pricePrecision) { + const isAsk = side === 'ask'; + const result = new Map(); + + entries.forEach((entry) => { + const price = parseFloat(entry.price); + const data = { + size: parseFloat(entry.size), + sources: entry.sources || {} + }; + + let bucketPrice, displayPrice; + if (isAsk) { + displayPrice = Math.ceil(price / pricePrecision) * pricePrecision; + bucketPrice = displayPrice; + } else { + displayPrice = Math.floor(price / pricePrecision) * pricePrecision; + bucketPrice = displayPrice; + } + + const bucketKey = Math.round(bucketPrice); + + if (!result.has(bucketKey)) { + result.set(bucketKey, { + size: 0, + price: displayPrice, + sources: {}, + }); + } + + const bucketData = result.get(bucketKey); + bucketData.size += data.size; + + if (data.sources) { + Object.entries(data.sources).forEach(([sourceKey, sourceSize]: [string, string]) => { + if (!bucketData.sources[sourceKey]) { + bucketData.sources[sourceKey] = 0; + } + bucketData.sources[sourceKey] += parseFloat(sourceSize); + }); + } + + }); + + return Array.from(result.values()); +} + /** * Takes in a req.query like: `{ * marketName: 'SOL-PERP,BTC-PERP,ETH-PERP', @@ -484,6 +533,7 @@ export type SubscriberLookup = { phoenix?: PhoenixSubscriber; serum?: SerumSubscriber; openbook?: OpenbookV2Subscriber; + tickSize?: BN; }; }; diff --git a/src/wsConnectionManager.ts b/src/wsConnectionManager.ts index 39bf659..9fcb521 100644 --- a/src/wsConnectionManager.ts +++ b/src/wsConnectionManager.ts @@ -7,6 +7,7 @@ import { sleep, selectMostRecentBySlot } from './utils/utils'; import { register, Gauge, Counter } from 'prom-client'; import { DriftEnv, PerpMarkets, SpotMarkets } from '@drift-labs/sdk'; import { RedisClient, RedisClientPrefix } from '@drift/common/clients'; +import { GROUPING_OPTIONS } from './dlob-subscriber/DLOBSubscriberIO'; // Set up env constants require('dotenv').config(); @@ -95,8 +96,12 @@ const getRedisChannelFromMessage = (message: any): string => { return `trades_${marketType}_${marketIndex}`; case 'orderbook': return `orderbook_${marketType}_${marketIndex}`; - case 'orderbook_indicative': + case 'orderbook_indicative': { + if (message.grouping && GROUPING_OPTIONS.includes(parseInt(message.grouping))) { + return `orderbook_${marketType}_${marketIndex}_grouped_${message.grouping}_indicative`; + } return `orderbook_${marketType}_${marketIndex}_indicative`; + } case 'priorityfees': return `priorityFees_${marketType}_${marketIndex}`; case undefined: From a9bdf07cfa0e5406d6a02cae87c052260652b515 Mon Sep 17 00:00:00 2001 From: Jack Waller Date: Tue, 10 Jun 2025 17:09:08 +1000 Subject: [PATCH 2/3] chore: remove testing --- src/publishers/dlobPublisher.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/publishers/dlobPublisher.ts b/src/publishers/dlobPublisher.ts index 694b457..d444350 100644 --- a/src/publishers/dlobPublisher.ts +++ b/src/publishers/dlobPublisher.ts @@ -115,7 +115,10 @@ const KILLSWITCH_SLOT_DIFF_THRESHOLD = parseInt(process.env.KILLSWITCH_SLOT_DIFF_THRESHOLD) || 200; // comma separated list of perp market indexes to load: i.e. 0,1,2,3 -const PERP_MARKETS_TO_LOAD = [0] +const PERP_MARKETS_TO_LOAD = + process.env.PERP_MARKETS_TO_LOAD !== undefined + ? parsePositiveIntArray(process.env.PERP_MARKETS_TO_LOAD) + : undefined; // comma separated list of spot market indexes to load: i.e. 0,1,2,3 const SPOT_MARKETS_TO_LOAD = From acc695052d78af35136bb07a50e64290ac896703 Mon Sep 17 00:00:00 2001 From: Jack Waller Date: Wed, 11 Jun 2025 10:08:58 +1000 Subject: [PATCH 3/3] chore: use previous groupings for calc --- src/dlob-subscriber/DLOBSubscriberIO.ts | 43 ++++-------- src/utils/utils.ts | 92 ++++++++++++++++++++++--- src/wsConnectionManager.ts | 3 +- 3 files changed, 99 insertions(+), 39 deletions(-) diff --git a/src/dlob-subscriber/DLOBSubscriberIO.ts b/src/dlob-subscriber/DLOBSubscriberIO.ts index 0287d78..455da7c 100644 --- a/src/dlob-subscriber/DLOBSubscriberIO.ts +++ b/src/dlob-subscriber/DLOBSubscriberIO.ts @@ -24,13 +24,13 @@ import { SubscriberLookup, addMarketSlotToResponse, addOracletoResponse, - aggregatePrices, l2WithBNToStrings, parsePositiveIntArray, + publishGroupings, } from '../utils/utils'; import { setHealthStatus, HEALTH_STATUS } from '../core/metrics'; -type wsMarketArgs = { +export type wsMarketArgs = { marketIndex: number; marketType: MarketType; marketName: string; @@ -39,12 +39,11 @@ type wsMarketArgs = { numVammOrders?: number; fallbackL2Generators?: L2OrderBookGenerator[]; updateOnChange?: boolean; - tickSize?: BN + tickSize?: BN; }; require('dotenv').config(); -export const GROUPING_OPTIONS = [1, 10, 100, 500, 1000]; const PERP_MAKRET_STALENESS_THRESHOLD = 30 * 60 * 1000; const SPOT_MAKRET_STALENESS_THRESHOLD = 60 * 60 * 1000; const STALE_ORACLE_REMOVE_VAMM_THRESHOLD = 160; @@ -120,7 +119,7 @@ export class DLOBSubscriberIO extends DLOBSubscriber { includeVamm, updateOnChange: false, fallbackL2Generators: [], - tickSize: perpMarket?.amm?.orderTickSize ?? ONE + tickSize: perpMarket?.amm?.orderTickSize ?? ONE, }); } for (const market of config.spotMarketInfos) { @@ -135,7 +134,8 @@ export class DLOBSubscriberIO extends DLOBSubscriber { config.spotMarketSubscribers[market.marketIndex].phoenix, config.spotMarketSubscribers[market.marketIndex].openbook, ].filter((a) => !!a), - tickSize: config.spotMarketSubscribers[market.marketIndex].tickSize ?? ONE + tickSize: + config.spotMarketSubscribers[market.marketIndex].tickSize ?? ONE, }); } } @@ -399,30 +399,15 @@ export class DLOBSubscriberIO extends DLOBSubscriber { }`, l2Formatted_depth100 ); - - GROUPING_OPTIONS.forEach(group => { - const pricePrecision = BigNum.from(group).mul(marketArgs.tickSize).toNum() - const aggregatedBids = aggregatePrices(l2Formatted.bids, 'bid', pricePrecision) - .sort((a, b) => b[0] - a[0]) - .slice(0, 20) - - const aggregatedAsks = aggregatePrices(l2Formatted.asks, 'ask', pricePrecision) - .sort((a, b) => a[0] - b[0]) - .slice(0, 20) - - const l2Formatted_grouped20 = Object.assign({}, l2Formatted, { - bids: aggregatedBids, - asks: aggregatedAsks, - }); - - this.redisClient.publish( - `${clientPrefix}orderbook_${marketType}_${marketArgs.marketIndex}_grouped_${group}${ - this.indicativeQuotesRedisClient ? '_indicative' : '' - }`, - l2Formatted_grouped20 - ); - }) + publishGroupings( + l2Formatted, + marketArgs, + this.redisClient, + clientPrefix, + marketType, + this.indicativeQuotesRedisClient + ); if (!this.indicativeQuotesRedisClient) { const bids = this.dlob diff --git a/src/utils/utils.ts b/src/utils/utils.ts index b80257b..1257e95 100644 --- a/src/utils/utils.ts +++ b/src/utils/utils.ts @@ -1,8 +1,8 @@ import { BN, + BigNum, DriftClient, DriftEnv, - L2Level, L2OrderBook, L3OrderBook, MarketType, @@ -21,6 +21,16 @@ import { logger } from './logger'; import { NextFunction, Request, Response } from 'express'; import FEATURE_FLAGS from './featureFlags'; import { Connection } from '@solana/web3.js'; +import { wsMarketArgs } from 'src/dlob-subscriber/DLOBSubscriberIO'; + +export const GROUPING_OPTIONS = [1, 10, 100, 500, 1000]; +export const GROUPING_DEPENDENCIES = { + 1: null, + 10: 1, + 100: 10, + 500: 100, + 1000: 100, +}; export const l2WithBNToStrings = (l2: L2OrderBook): any => { for (const key of Object.keys(l2)) { @@ -181,7 +191,7 @@ export function aggregatePrices(entries, side, pricePrecision) { const price = parseFloat(entry.price); const data = { size: parseFloat(entry.size), - sources: entry.sources || {} + sources: entry.sources || {}, }; let bucketPrice, displayPrice; @@ -207,19 +217,85 @@ export function aggregatePrices(entries, side, pricePrecision) { bucketData.size += data.size; if (data.sources) { - Object.entries(data.sources).forEach(([sourceKey, sourceSize]: [string, string]) => { - if (!bucketData.sources[sourceKey]) { - bucketData.sources[sourceKey] = 0; + Object.entries(data.sources).forEach( + ([sourceKey, sourceSize]: [string, string]) => { + if (!bucketData.sources[sourceKey]) { + bucketData.sources[sourceKey] = 0; + } + bucketData.sources[sourceKey] += parseFloat(sourceSize); } - bucketData.sources[sourceKey] += parseFloat(sourceSize); - }); + ); } - }); return Array.from(result.values()); } +export function publishGroupings( + l2Formatted, + marketArgs: wsMarketArgs, + redisClient: RedisClient, + clientPrefix: string, + marketType: string, + indicativeQuotesRedisClient: RedisClient +) { + const groupingResults = new Map(); + + GROUPING_OPTIONS.forEach((group) => { + const pricePrecision = BigNum.from(group).mul(marketArgs.tickSize).toNum(); + const dependency = GROUPING_DEPENDENCIES[group]; + + let fullAggregatedBids, fullAggregatedAsks; + + if (dependency && groupingResults.has(dependency)) { + const previousResults = groupingResults.get(dependency); + + fullAggregatedBids = aggregatePrices( + previousResults.bids, + 'bid', + pricePrecision + ).sort((a, b) => b[0] - a[0]); + + fullAggregatedAsks = aggregatePrices( + previousResults.asks, + 'ask', + pricePrecision + ).sort((a, b) => a[0] - b[0]); + } else { + fullAggregatedBids = aggregatePrices( + l2Formatted.bids, + 'bid', + pricePrecision + ).sort((a, b) => b[0] - a[0]); + + fullAggregatedAsks = aggregatePrices( + l2Formatted.asks, + 'ask', + pricePrecision + ).sort((a, b) => a[0] - b[0]); + } + + groupingResults.set(group, { + bids: fullAggregatedBids, + asks: fullAggregatedAsks, + }); + + const aggregatedBids = fullAggregatedBids.slice(0, 20); + const aggregatedAsks = fullAggregatedAsks.slice(0, 20); + const l2Formatted_grouped20 = Object.assign({}, l2Formatted, { + bids: aggregatedBids, + asks: aggregatedAsks, + }); + + redisClient.publish( + `${clientPrefix}orderbook_${marketType}_${ + marketArgs.marketIndex + }_grouped_${group}${indicativeQuotesRedisClient ? '_indicative' : ''}`, + l2Formatted_grouped20 + ); + }); +} + /** * Takes in a req.query like: `{ * marketName: 'SOL-PERP,BTC-PERP,ETH-PERP', diff --git a/src/wsConnectionManager.ts b/src/wsConnectionManager.ts index 9fcb521..f37b7a9 100644 --- a/src/wsConnectionManager.ts +++ b/src/wsConnectionManager.ts @@ -3,11 +3,10 @@ import express from 'express'; import * as http from 'http'; import compression from 'compression'; import { WebSocket, WebSocketServer } from 'ws'; -import { sleep, selectMostRecentBySlot } from './utils/utils'; +import { sleep, selectMostRecentBySlot, GROUPING_OPTIONS } from './utils/utils'; import { register, Gauge, Counter } from 'prom-client'; import { DriftEnv, PerpMarkets, SpotMarkets } from '@drift-labs/sdk'; import { RedisClient, RedisClientPrefix } from '@drift/common/clients'; -import { GROUPING_OPTIONS } from './dlob-subscriber/DLOBSubscriberIO'; // Set up env constants require('dotenv').config();