Skip to content

Commit

Permalink
WIP cache oracle prices
Browse files Browse the repository at this point in the history
  • Loading branch information
adamfraser committed Feb 3, 2025
1 parent afa37ec commit 5c9405f
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 9 deletions.
51 changes: 51 additions & 0 deletions indexer/packages/redis/src/caches/orderbook-mid-prices-cache.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { logger } from '@dydxprotocol-indexer/base';
import { PerpetualMarketFromDatabase, PriceMap } from '@dydxprotocol-indexer/postgres';
import Big from 'big.js';
import { Callback, RedisClient } from 'redis';

Expand All @@ -21,6 +22,56 @@ function getOrderbookMidPriceCacheKey(ticker: string): string {
return `${ORDERBOOK_MID_PRICES_CACHE_KEY_PREFIX}${ticker}`;
}

export async function cacheOraclePrices(
client: RedisClient,
markets: PerpetualMarketFromDatabase[],
prices: PriceMap,
): Promise<void> {
const cacheKeyPricePairs:
({cacheKey: string, price: string})[] = markets.flatMap((market) => {
const cacheKey: string = getOrderbookMidPriceCacheKey(market.ticker);
const price = prices[market.marketId];

return price !== undefined ? { cacheKey, price } : [];
});

// Extract cache keys and prices
const { priceCacheKeys, priceValues } = cacheKeyPricePairs.reduce(
(acc, pair) => {
acc.priceCacheKeys.push(pair.cacheKey);
acc.priceValues.push(pair.price);
return acc;
},
{ priceCacheKeys: [] as string[], priceValues: [] as string[] },
);

const nowSeconds: number = Math.floor(Date.now() / 1000); // Current time in seconds

logger.info({
at: 'orderbook-mid-prices-cache#cacheOraclePrices',
message: 'Caching orderbook mid price',
cacheKey: priceCacheKeys[0],
midPrice: priceValues[0],
});

return new Promise<void>((resolve, reject) => {
client.evalsha(
addOrderbookMidPricesScript.hash,
priceCacheKeys.length,
...priceCacheKeys,
...priceValues,
nowSeconds,
(err: Error | null) => {
if (err) {
reject(err);
} else {
resolve();
}
},
);
});
}

/**
* Fetches and caches mid prices for multiple tickers.
* @param client The Redis client
Expand Down
15 changes: 7 additions & 8 deletions indexer/services/roundtable/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
connect as connectToRedis,
} from './helpers/redis';
import aggregateTradingRewardsTasks from './tasks/aggregate-trading-rewards';
import cacheOrderbookMidPrices from './tasks/cache-orderbook-mid-prices';
import cancelStaleOrdersTask from './tasks/cancel-stale-orders';
import createLeaderboardTask from './tasks/create-leaderboard';
import createPnlTicksTask from './tasks/create-pnl-ticks';
Expand Down Expand Up @@ -281,13 +280,13 @@ async function start(): Promise<void> {
config.LOOPS_INTERVAL_MS_REFRESH_VAULT_PNL,
);
}
if (config.LOOPS_ENABLED_CACHE_ORDERBOOK_MID_PRICES) {
startLoop(
cacheOrderbookMidPrices,
'cache-orderbook-mid-prices',
config.LOOPS_INTERVAL_MS_CACHE_ORDERBOOK_MID_PRICES,
);
}
// if (config.LOOPS_ENABLED_CACHE_ORDERBOOK_MID_PRICES) {
// startLoop(
// cacheOrderbookMidPrices,
// 'cache-orderbook-mid-prices',
// config.LOOPS_INTERVAL_MS_CACHE_ORDERBOOK_MID_PRICES,
// );
// }

logger.info({
at: 'index',
Expand Down
9 changes: 8 additions & 1 deletion indexer/services/roundtable/src/tasks/market-updater.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
LiquidityTiersFromDatabase,
LiquidityTiersTable, LiquidityTiersMap, LiquidityTiersColumns,
} from '@dydxprotocol-indexer/postgres';
import { NextFundingCache } from '@dydxprotocol-indexer/redis';
import { NextFundingCache, OrderbookMidPricesCache } from '@dydxprotocol-indexer/redis';
import Big from 'big.js';
import _ from 'lodash';

Expand Down Expand Up @@ -79,6 +79,13 @@ export default async function runTask(): Promise<void> {
Date.now() - start,
);

OrderbookMidPricesCache.cacheOraclePrices(redisClient, perpetualMarkets, latestPrices);
const count = perpetualMarkets.length;
logger.info({
at: 'market_updater#cache_oracle_prices',
message: `Caching prices for ${count} markets`,
});

const clobPairIdToPerpetualMarketId: _.Dictionary<string> = _.chain(perpetualMarkets)
.keyBy(PerpetualMarketColumns.clobPairId)
.mapValues(PerpetualMarketColumns.id)
Expand Down

0 comments on commit 5c9405f

Please sign in to comment.