Merge pull request #234 from drift-labs/master
bump common + nick's script changes
This commit is contained in:
Submodule drift-common updated: ec8383719d...82dbbf336b
@@ -20,6 +20,7 @@
|
|||||||
"@types/ws": "^8.5.8",
|
"@types/ws": "^8.5.8",
|
||||||
"async-mutex": "^0.4.0",
|
"async-mutex": "^0.4.0",
|
||||||
"axios": "^1.6.2",
|
"axios": "^1.6.2",
|
||||||
|
"bottleneck": "^2.19.5",
|
||||||
"commander": "^9.4.0",
|
"commander": "^9.4.0",
|
||||||
"compression": "^1.7.4",
|
"compression": "^1.7.4",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
|
|||||||
@@ -657,7 +657,10 @@ const main = async (): Promise<void> => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const redisClient = perpMarketRedisMap.get(marketIndex).client;
|
const redisClient = redisClients.find(
|
||||||
|
(client) =>
|
||||||
|
client.forceGetClient().options.keyPrefix === RedisClientPrefix.DLOB
|
||||||
|
);
|
||||||
|
|
||||||
const redisResponseGainers = await redisClient.getRaw(
|
const redisResponseGainers = await redisClient.getRaw(
|
||||||
`perp_market_${marketIndex}_gainers`
|
`perp_market_${marketIndex}_gainers`
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { RedisClient, RedisClientPrefix } from '@drift/common';
|
import { RedisClient, RedisClientPrefix, sleep } from '@drift/common';
|
||||||
import {
|
import {
|
||||||
BigNum,
|
BigNum,
|
||||||
DriftClient,
|
DriftClient,
|
||||||
@@ -11,11 +11,11 @@ import {
|
|||||||
Wallet,
|
Wallet,
|
||||||
ZERO,
|
ZERO,
|
||||||
calculateClaimablePnl,
|
calculateClaimablePnl,
|
||||||
calculatePositionPNL,
|
|
||||||
decodeUser,
|
decodeUser,
|
||||||
} from '@drift-labs/sdk';
|
} from '@drift-labs/sdk';
|
||||||
import { Connection, Keypair } from '@solana/web3.js';
|
import { Connection, Keypair } from '@solana/web3.js';
|
||||||
import { logger } from '../utils/logger';
|
import { logger } from '../utils/logger';
|
||||||
|
import Bottleneck from 'bottleneck';
|
||||||
|
|
||||||
const dotenv = require('dotenv');
|
const dotenv = require('dotenv');
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
@@ -29,10 +29,19 @@ type UserPnlMap = {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type AllPnlUsers = {
|
||||||
|
[perpMarketIndex: number]: {
|
||||||
|
users: { userPubKey: string; pnl: number }[];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
const startTime = Date.now();
|
const startTime = Date.now();
|
||||||
const endpoint = process.env.ENDPOINT as string;
|
const endpoint = process.env.ENDPOINT as string;
|
||||||
const wsEndpoint = process.env.WS_ENDPOINT as string;
|
const wsEndpoint = process.env.WS_ENDPOINT as string;
|
||||||
const driftEnv = process.env.ENV as string;
|
const driftEnv = process.env.ENV as string;
|
||||||
|
const chunkSize = Number(process.env.CHUNK_SIZE) || 100;
|
||||||
|
const sleepTimeMs = Number(process.env.SLEEP_TIME_MS) || 500;
|
||||||
|
const delayMs = Number(process.env.DEFAULT_DELAY_MS) || 100;
|
||||||
|
|
||||||
const connection = new Connection(endpoint, {
|
const connection = new Connection(endpoint, {
|
||||||
commitment: 'confirmed',
|
commitment: 'confirmed',
|
||||||
@@ -45,6 +54,8 @@ const driftClient = new DriftClient({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const userMapRedisClient = new RedisClient({
|
const userMapRedisClient = new RedisClient({
|
||||||
|
host: process.env.ELASTICACHE_USERMAP_HOST ?? process.env.ELASTICACHE_HOST,
|
||||||
|
port: process.env.ELASTICACHE_USERMAP_PORT ?? process.env.ELASTICACHE_PORT,
|
||||||
prefix: RedisClientPrefix.USER_MAP,
|
prefix: RedisClientPrefix.USER_MAP,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -56,14 +67,41 @@ const main = async () => {
|
|||||||
// get the users from usermap redis client
|
// get the users from usermap redis client
|
||||||
await driftClient.subscribe();
|
await driftClient.subscribe();
|
||||||
|
|
||||||
|
const limiter = new Bottleneck({
|
||||||
|
maxConcurrent: 10,
|
||||||
|
minTime: delayMs,
|
||||||
|
});
|
||||||
|
|
||||||
const userStrings = await userMapRedisClient.lRange('user_pubkeys', 0, -1);
|
const userStrings = await userMapRedisClient.lRange('user_pubkeys', 0, -1);
|
||||||
|
|
||||||
const redisUsers = await Promise.all(
|
const totalCount = userStrings.length;
|
||||||
userStrings.map((userStr) => getUserFromRedis(userStr))
|
let finishedCount = 0;
|
||||||
|
let allNonZeroPnls = {};
|
||||||
|
|
||||||
|
logger.info(`Starting loop for total of ${totalCount} users`);
|
||||||
|
|
||||||
|
while (finishedCount < totalCount) {
|
||||||
|
const userChunk = userStrings.slice(
|
||||||
|
finishedCount,
|
||||||
|
finishedCount + chunkSize
|
||||||
);
|
);
|
||||||
|
|
||||||
// construct an object with the top 20/bottom 20 unsettled in each perp market
|
limiter.schedule(async () => {
|
||||||
const userPnlMap = createMarketSpecificPnlLeaderboards(redisUsers);
|
const redisUsers = await Promise.all(
|
||||||
|
userChunk.map((userStr) => getUserFromRedis(userStr))
|
||||||
|
);
|
||||||
|
// add all the nonzero pnl users from each market in chunks
|
||||||
|
allNonZeroPnls = buildUserMarketLists(redisUsers, allNonZeroPnls);
|
||||||
|
});
|
||||||
|
|
||||||
|
finishedCount += chunkSize;
|
||||||
|
|
||||||
|
logger.info(`Wrote ${finishedCount} users, sleeping for ${sleepTimeMs}ms`);
|
||||||
|
|
||||||
|
await sleep(sleepTimeMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
const userPnlMap = createMarketPnlLeaderboards(allNonZeroPnls);
|
||||||
|
|
||||||
const success = await writeToDlobRedis(userPnlMap);
|
const success = await writeToDlobRedis(userPnlMap);
|
||||||
|
|
||||||
@@ -73,6 +111,12 @@ const main = async () => {
|
|||||||
} in ${Date.now() - startTime} ms`
|
} in ${Date.now() - startTime} ms`
|
||||||
);
|
);
|
||||||
|
|
||||||
|
await sleep(5000);
|
||||||
|
|
||||||
|
logger.info('==== TEST PRINT LOSERS FROM BTC-PERP ====');
|
||||||
|
const losers = await dlobRedisClient.getRaw(`perp_market_1_losers`);
|
||||||
|
logger.info(losers);
|
||||||
|
|
||||||
process.exit();
|
process.exit();
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -84,30 +128,66 @@ const writeToDlobRedis = async (userPnlMap: UserPnlMap): Promise<boolean> => {
|
|||||||
const losersRedisKey = `perp_market_${perpMarketIndex}_losers`;
|
const losersRedisKey = `perp_market_${perpMarketIndex}_losers`;
|
||||||
|
|
||||||
// write the new lists
|
// write the new lists
|
||||||
await dlobRedisClient.setRaw(
|
await Promise.all([
|
||||||
|
dlobRedisClient.setRaw(
|
||||||
gainersRedisKey,
|
gainersRedisKey,
|
||||||
JSON.stringify(userPnlMap[perpMarketIndex].gain)
|
JSON.stringify(userPnlMap[perpMarketIndex].gain ?? [])
|
||||||
);
|
),
|
||||||
await dlobRedisClient.setRaw(
|
dlobRedisClient.setRaw(
|
||||||
losersRedisKey,
|
losersRedisKey,
|
||||||
JSON.stringify(userPnlMap[perpMarketIndex].loss)
|
JSON.stringify(userPnlMap[perpMarketIndex].loss ?? [])
|
||||||
|
),
|
||||||
|
]).then(([_winnersResult, _losersResult]) => {
|
||||||
|
logger.info(
|
||||||
|
`Wrote ${userPnlMap[perpMarketIndex].gain.length} users to redis key: ${gainersRedisKey}`
|
||||||
);
|
);
|
||||||
|
logger.info(
|
||||||
return;
|
`Wrote ${userPnlMap[perpMarketIndex].loss.length} users to redis key: ${losersRedisKey}`
|
||||||
|
);
|
||||||
|
});
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.log('Error writing to dlob redis client: ', e);
|
logger.info(`Error writing to dlob redis client: ${e}`);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const createMarketSpecificPnlLeaderboards = (
|
const createMarketPnlLeaderboards = (allPnlUsers: AllPnlUsers): UserPnlMap => {
|
||||||
redisUsers: { user: User; bufferString: string }[]
|
let pnlMap = {};
|
||||||
): UserPnlMap => {
|
|
||||||
const pnlMap = {};
|
Object.keys(allPnlUsers).forEach((perpMarketIndex) => {
|
||||||
|
try {
|
||||||
|
const sortedPnls = allPnlUsers[perpMarketIndex].users.sort(
|
||||||
|
(a, b) => b.pnl - a.pnl
|
||||||
|
);
|
||||||
|
// store the top 20 winners and losers in each perp market
|
||||||
|
pnlMap[perpMarketIndex] = {
|
||||||
|
gain: sortedPnls.slice(0, 20),
|
||||||
|
loss: sortedPnls.slice(-20).reverse(),
|
||||||
|
};
|
||||||
|
} catch (e) {
|
||||||
|
logger.info(
|
||||||
|
`Error in ${PerpMarkets[driftEnv][perpMarketIndex].symbol}: ${e}`
|
||||||
|
);
|
||||||
|
|
||||||
|
pnlMap[perpMarketIndex] = {
|
||||||
|
gain: [],
|
||||||
|
loss: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return pnlMap;
|
||||||
|
};
|
||||||
|
|
||||||
|
const buildUserMarketLists = (
|
||||||
|
redisUsers: { user: User; bufferString: string }[],
|
||||||
|
allPnlUsers: AllPnlUsers
|
||||||
|
): AllPnlUsers => {
|
||||||
|
let newPnlUsers = allPnlUsers;
|
||||||
|
|
||||||
const usdcSpotMarket = driftClient.getSpotMarketAccount(
|
const usdcSpotMarket = driftClient.getSpotMarketAccount(
|
||||||
QUOTE_SPOT_MARKET_INDEX
|
QUOTE_SPOT_MARKET_INDEX
|
||||||
@@ -123,7 +203,7 @@ const createMarketSpecificPnlLeaderboards = (
|
|||||||
perpMarket.marketIndex
|
perpMarket.marketIndex
|
||||||
);
|
);
|
||||||
|
|
||||||
const allNonZeroPnls = redisUsers.flatMap((redisUser) => {
|
const allNonZeroPnlsInMarket = redisUsers.flatMap((redisUser) => {
|
||||||
try {
|
try {
|
||||||
const perpPosition = redisUser.user.getPerpPosition(
|
const perpPosition = redisUser.user.getPerpPosition(
|
||||||
perpMarket.marketIndex
|
perpMarket.marketIndex
|
||||||
@@ -144,21 +224,12 @@ const createMarketSpecificPnlLeaderboards = (
|
|||||||
false
|
false
|
||||||
)[0];
|
)[0];
|
||||||
|
|
||||||
let marketPnl = calculatePositionPNL(
|
const marketPnl = calculateClaimablePnl(
|
||||||
perpMarketAccount,
|
|
||||||
perpPositionWithLpSettle,
|
|
||||||
true,
|
|
||||||
oraclePriceData
|
|
||||||
);
|
|
||||||
|
|
||||||
if (marketPnl.gt(ZERO)) {
|
|
||||||
marketPnl = calculateClaimablePnl(
|
|
||||||
perpMarketAccount,
|
perpMarketAccount,
|
||||||
usdcSpotMarket,
|
usdcSpotMarket,
|
||||||
perpPositionWithLpSettle,
|
perpPositionWithLpSettle,
|
||||||
oraclePriceData
|
oraclePriceData
|
||||||
);
|
);
|
||||||
}
|
|
||||||
|
|
||||||
return marketPnl.eq(ZERO)
|
return marketPnl.eq(ZERO)
|
||||||
? []
|
? []
|
||||||
@@ -175,19 +246,21 @@ const createMarketSpecificPnlLeaderboards = (
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const sortedPnls = allNonZeroPnls.sort((a, b) => b.pnl - a.pnl);
|
if (!allPnlUsers[perpMarket.marketIndex]) {
|
||||||
|
newPnlUsers[perpMarket.marketIndex] = { users: allNonZeroPnlsInMarket };
|
||||||
// store the top 20 winners and losers in each perp market
|
} else {
|
||||||
pnlMap[perpMarket.marketIndex] = {
|
newPnlUsers[perpMarket.marketIndex] = {
|
||||||
gain: sortedPnls.slice(0, 20),
|
users: allPnlUsers[perpMarket.marketIndex].users.concat(
|
||||||
loss: sortedPnls.slice(-20, -1),
|
allNonZeroPnlsInMarket
|
||||||
|
),
|
||||||
};
|
};
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.error(`Could not fetch PnLs for ${perpMarket.symbol}: `, e);
|
logger.error(`Could not fetch PnLs for ${perpMarket.symbol}: `, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return pnlMap;
|
return newPnlUsers;
|
||||||
};
|
};
|
||||||
|
|
||||||
const getUserFromRedis = async (userAccountStr: string) => {
|
const getUserFromRedis = async (userAccountStr: string) => {
|
||||||
|
|||||||
Reference in New Issue
Block a user