From 1413cc0c05a53778b401f3ee61bf7ffb2d7d514d Mon Sep 17 00:00:00 2001 From: Caitlyn Carver <31781720+MentalTrain@users.noreply.github.com> Date: Thu, 27 Jul 2023 23:34:44 -0700 Subject: [PATCH] adding HistoricalMarketStats --- src/perps.ts | 26 ++++++++++++++++++++++++++ subgraphs/perps.graphql | 16 ++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/src/perps.ts b/src/perps.ts index 68364197..7c46e806 100644 --- a/src/perps.ts +++ b/src/perps.ts @@ -76,6 +76,29 @@ export function handleMarketRemoved(event: MarketRemovedEvent): void { store.remove('PerpsMarket', event.params.market.toHex()); } +// Update historical market stats entity +function updateHistoricalMarketStats(marketKey: string, timestamp: BigInt, tradeSize: BigInt): void { + const dayTimestamp = timestamp.toI32() / DAY_SECONDS * DAY_SECONDS; // Convert to the start of the day + const historicalStatId = marketKey + '-' + dayTimestamp.toString(); + let historicalStat = HistoricalMarketStats.load(historicalStatId); + + if (!historicalStat) { + // If the historical stat does not exist, create a new one + historicalStat = new HistoricalMarketStats(historicalStatId); + historicalStat.timestamp = dayTimestamp; + historicalStat.marketKey = Bytes.fromHexString(marketKey) as Bytes; + historicalStat.marketAsset = Bytes.fromHexString(marketEntity.asset) as Bytes; + historicalStat.period = PeriodEnum.DAILY; + historicalStat.marketSize = ZERO; + } else { + // If the historical stat already exists for the day, add the new trade size to the existing marketSize + historicalStat.marketSize = historicalStat.marketSize.plus(tradeSize); + } + + // save the data + historicalStat.save(); +} + export function handlePositionModified(event: PositionModifiedEvent): void { // handler for the position modified function // the PositionModified event it emitted any time a user interacts with a position @@ -319,6 +342,9 @@ export function handlePositionModified(event: PositionModifiedEvent): void { synthetixFeePaid, ZERO, ); + // update historical market stats ---cici + updateHistoricalMarketStats(marketEntity.marketKey, event.block.timestamp, tradeEntity.size); + } } else { // if the tradeSize is equal to zero, it must be a margin transfer or a liquidation diff --git a/subgraphs/perps.graphql b/subgraphs/perps.graphql index 398af650..cb71eacc 100644 --- a/subgraphs/perps.graphql +++ b/subgraphs/perps.graphql @@ -233,3 +233,19 @@ type CrossMarginAccount @entity { id: ID! owner: Bytes! } + +# Define the enum for the 'period' field +enum PeriodEnum { + DAILY + WEEKLY + MONTHLY + # Add other allowed values as needed +} + +type HistoricalMarketStats @entity { + timestamp: BigInt! + marketKey: Bytes! + marketAsset: Bytes! + period: PeriodEnum + marketSize: BigInt! +} \ No newline at end of file