Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TRA-890] Return nearest hour PnL as final data point for vaults pnl. #2616

Merged
merged 3 commits into from
Nov 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {
import { RequestMethod, VaultHistoricalPnl } from '../../../../src/types';
import request from 'supertest';
import { getFixedRepresentation, sendRequest } from '../../../helpers/helpers';
import { DateTime } from 'luxon';
import { DateTime, Settings } from 'luxon';
import Big from 'big.js';
import config from '../../../../src/config';

Expand Down Expand Up @@ -124,6 +124,7 @@ describe('vault-controller#V4', () => {
effectiveAtHeight: twoDayBlockHeight,
}),
]);
Settings.now = () => latestTime.valueOf();
});

afterEach(async () => {
Expand All @@ -133,6 +134,7 @@ describe('vault-controller#V4', () => {
config.VAULT_PNL_HISTORY_HOURS = vaultPnlHistoryHoursPrev;
config.VAULT_LATEST_PNL_TICK_WINDOW_HOURS = vaultPnlLastPnlWindowPrev;
config.VAULT_PNL_START_DATE = vaultPnlStartDatePrev;
Settings.now = () => new Date().valueOf();
});

it.each([
Expand Down Expand Up @@ -298,13 +300,14 @@ describe('vault-controller#V4', () => {
});

it.each([
['no resolution', '', [1, 2]],
['daily resolution', '?resolution=day', [1, 2]],
['hourly resolution', '?resolution=hour', [1, 2, 3, 4]],
['no resolution', '', [1, 2], 4],
['daily resolution', '?resolution=day', [1, 2], 4],
['hourly resolution', '?resolution=hour', [1, 2, 3, 4], 4],
])('Get /vaults/historicalPnl with single vault subaccount (%s)', async (
_name: string,
queryParam: string,
expectedTicksIndex: number[],
currentTickIndex: number,
) => {
await VaultTable.create({
...testConstants.defaultVault,
Expand All @@ -313,7 +316,7 @@ describe('vault-controller#V4', () => {
});
const createdPnlTicks: PnlTicksFromDatabase[] = await createPnlTicks();
const finalTick: PnlTicksFromDatabase = {
...createdPnlTicks[expectedTicksIndex[expectedTicksIndex.length - 1]],
...createdPnlTicks[currentTickIndex],
vincentwschau marked this conversation as resolved.
Show resolved Hide resolved
equity: Big(vault1Equity).toFixed(),
blockHeight: latestBlockHeight,
blockTime: latestTime.toISO(),
Expand All @@ -338,14 +341,16 @@ describe('vault-controller#V4', () => {
});

it.each([
['no resolution', '', [1, 2], [6, 7]],
['daily resolution', '?resolution=day', [1, 2], [6, 7]],
['hourly resolution', '?resolution=hour', [1, 2, 3, 4], [6, 7, 8, 9]],
['no resolution', '', [1, 2], [6, 7], 4, 9],
['daily resolution', '?resolution=day', [1, 2], [6, 7], 4, 9],
['hourly resolution', '?resolution=hour', [1, 2, 3, 4], [6, 7, 8, 9], 4, 9],
])('Get /vaults/historicalPnl with 2 vault subaccounts (%s)', async (
_name: string,
queryParam: string,
expectedTicksIndex1: number[],
expectedTicksIndex2: number[],
currentTickIndex1: number,
currentTickIndex2: number,
) => {
await Promise.all([
VaultTable.create({
Expand All @@ -361,14 +366,14 @@ describe('vault-controller#V4', () => {
]);
const createdPnlTicks: PnlTicksFromDatabase[] = await createPnlTicks();
const finalTick1: PnlTicksFromDatabase = {
...createdPnlTicks[expectedTicksIndex1[expectedTicksIndex1.length - 1]],
...createdPnlTicks[currentTickIndex1],
equity: Big(vault1Equity).toFixed(),
blockHeight: latestBlockHeight,
blockTime: latestTime.toISO(),
createdAt: latestTime.toISO(),
};
const finalTick2: PnlTicksFromDatabase = {
...createdPnlTicks[expectedTicksIndex2[expectedTicksIndex2.length - 1]],
...createdPnlTicks[currentTickIndex2],
equity: Big(vault2Equity).toFixed(),
blockHeight: latestBlockHeight,
blockTime: latestTime.toISO(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ import Big from 'big.js';
import bounds from 'binary-searching';
import express from 'express';
import { checkSchema, matchedData } from 'express-validator';
import _ from 'lodash';
import _, { Dictionary } from 'lodash';
import { DateTime } from 'luxon';
import {
Controller, Get, Query, Route,
Expand Down Expand Up @@ -152,15 +152,22 @@ class VaultController extends Controller {
vaultPnlTicks,
vaultPositions,
latestBlock,
latestTicks,
] : [
PnlTicksFromDatabase[],
Map<string, VaultPosition>,
BlockFromDatabase,
PnlTicksFromDatabase[],
] = await Promise.all([
getVaultSubaccountPnlTicks(_.keys(vaultSubaccounts), getResolution(resolution)),
getVaultPositions(vaultSubaccounts),
BlockTable.getLatest(),
getLatestPnlTicks(_.keys(vaultSubaccounts)),
]);
const latestTicksBySubaccountId: Dictionary<PnlTicksFromDatabase> = _.keyBy(
latestTicks,
'subaccountId',
);
Comment on lines +155 to +170
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling for undefined latest ticks

While the Dictionary organization is good, accessing latestTicksBySubaccountId[subaccountId] directly could be unsafe if the subaccountId doesn't exist in the dictionary.

Consider adding a null check or using optional chaining:

-          latestTicksBySubaccountId[subaccountId],
+          latestTicksBySubaccountId[subaccountId] ?? undefined,

Committable suggestion skipped: line range outside the PR's diff.


const groupedVaultPnlTicks: VaultHistoricalPnl[] = _(vaultPnlTicks)
.filter((pnlTickFromDatabsae: PnlTicksFromDatabase): boolean => {
Expand All @@ -185,6 +192,7 @@ class VaultController extends Controller {
currentEquity,
pnlTicks,
latestBlock,
latestTicksBySubaccountId[subaccountId],
);

return {
Expand Down Expand Up @@ -350,13 +358,13 @@ async function getVaultSubaccountPnlTicks(
VaultPnlTicksView.getVaultsPnl(
resolution,
windowSeconds,
getVautlPnlStartDate(),
getVaultPnlStartDate(),
),
PnlTicksTable.getLatestPnlTick(
vaultSubaccountIds,
// Add a buffer of 10 minutes to get the first PnL tick for PnL data as PnL ticks aren't
// created exactly on the hour.
getVautlPnlStartDate().plus({ minutes: 10 }),
getVaultPnlStartDate().plus({ minutes: 10 }),
),
]);

Expand Down Expand Up @@ -551,6 +559,34 @@ function getPnlTicksWithCurrentTick(
return pnlTicks.concat([currentTick]);
}

export async function getLatestPnlTicks(
vaultSubaccountIds: string[],
): Promise<PnlTicksFromDatabase[]> {
vincentwschau marked this conversation as resolved.
Show resolved Hide resolved
const [
latestPnlTicks,
adjustByPnlTicks,
] : [
PnlTicksFromDatabase[],
PnlTicksFromDatabase[],
] = await Promise.all([
PnlTicksTable.getLatestPnlTick(
vaultSubaccountIds,
DateTime.now().toUTC(),
),
PnlTicksTable.getLatestPnlTick(
vaultSubaccountIds,
// Add a buffer of 10 minutes to get the first PnL tick for PnL data as PnL ticks aren't
// created exactly on the hour.
getVaultPnlStartDate().plus({ minutes: 10 }),
),
]);
const adjustedPnlTicks: PnlTicksFromDatabase[] = adjustVaultPnlTicks(
latestPnlTicks,
adjustByPnlTicks,
);
return adjustedPnlTicks;
}

export async function getLatestPnlTick(
vaultSubaccountIds: string[],
vaults: VaultFromDatabase[],
Expand All @@ -565,13 +601,13 @@ export async function getLatestPnlTick(
VaultPnlTicksView.getVaultsPnl(
PnlTickInterval.hour,
config.VAULT_LATEST_PNL_TICK_WINDOW_HOURS * 60 * 60,
getVautlPnlStartDate(),
getVaultPnlStartDate(),
),
PnlTicksTable.getLatestPnlTick(
vaultSubaccountIds,
// Add a buffer of 10 minutes to get the first PnL tick for PnL data as PnL ticks aren't
// created exactly on the hour.
getVautlPnlStartDate().plus({ minutes: 10 }),
getVaultPnlStartDate().plus({ minutes: 10 }),
),
]);
const adjustedPnlTicks: PnlTicksFromDatabase[] = adjustVaultPnlTicks(
Expand Down Expand Up @@ -798,7 +834,7 @@ async function getVaultMapping(): Promise<VaultMapping> {
return validVaultMapping;
}

function getVautlPnlStartDate(): DateTime {
function getVaultPnlStartDate(): DateTime {
const startDate: DateTime = DateTime.fromISO(config.VAULT_PNL_START_DATE).toUTC();
return startDate;
}
Expand Down