vega-frontend-monorepo/libs/positions/src/lib/positions-data-providers.ts

281 lines
7.5 KiB
TypeScript
Raw Normal View History

import { gql } from '@apollo/client';
import produce from 'immer';
import BigNumber from 'bignumber.js';
import sortBy from 'lodash/sortBy';
import type { Accounts_party_accounts } from '@vegaprotocol/accounts';
import { accountsDataProvider } from '@vegaprotocol/accounts';
import { toBigNum } from '@vegaprotocol/react-helpers';
import type { Positions, Positions_party } from './__generated__/Positions';
import {
makeDataProvider,
makeDerivedDataProvider,
} from '@vegaprotocol/react-helpers';
import type {
PositionsSubscription,
PositionsSubscription_positions,
} from './__generated__/PositionsSubscription';
import { AccountType } from '@vegaprotocol/types';
import type { MarketTradingMode } from '@vegaprotocol/types';
export interface Position {
marketName: string;
averageEntryPrice: string;
capitalUtilisation: number;
currentLeverage: number;
feat(#840): update positions tab (#1101) * feat(#473): add positions metrics data provider * feat(#473) add positions stats * feat(#473) add positions stats * feat(#473): add positions stats * feat(#473): add positions stats * feat(#473): position metrics, test and refactoring * feat(#473): add unit tests to positions table * feat(#473): fix spelling, order positions by updated at desc * feat(#473): protect from division by 0 * feat(#473): fix trading positions e2e tests * feat(#473): fix e2e data mocks * feat(#473): post code review clean up * feat(#993): dependencies handling in data provider * feat(#993): fix e2e tests data mocks * feat(#993): remove position metrics mocks, add market data market id * feat(#993): add missing mocks, fix combine function * feat(#993): set loading initially to true, add unit tests * feat(#993): cleanup, add comments * feat(#993): remove undefined from client type * feat(#993): cosmetic changes * feat(#840): update positions tab * feat:(#993): pass informaton about update callback cause * feat(#840): update positions tab * feat(#840): update positions tab * feat(#840): update positions tab * chore: skip handles 5000 markets e2e test * feat(#840): update positions tab * feat(#840): rename assetDecimals to decimals * feat(#840): close position * feat(#993): notify about update * feat(#840): add use close position hook * feat(#840): do not show 0 volume positions, make liquidation price minimum 0 * feat(#840): post code review fixes and improvments * feat: fix fill-table spec
2022-09-02 20:53:00 +00:00
decimals: number;
marketDecimalPlaces: number;
positionDecimalPlaces: number;
totalBalance: string;
assetSymbol: string;
liquidationPrice: string;
lowMarginLevel: boolean;
marketId: string;
marketTradingMode: MarketTradingMode;
markPrice: string;
notional: string;
openVolume: string;
realisedPNL: string;
unrealisedPNL: string;
searchPrice: string;
updatedAt: string | null;
}
export interface Data {
party: Positions_party | null;
positions: Position[] | null;
}
const POSITION_FIELDS = gql`
fragment PositionFields on Position {
realisedPNL
openVolume
unrealisedPNL
averageEntryPrice
updatedAt
marginsConnection {
edges {
node {
market {
id
}
maintenanceLevel
searchLevel
initialLevel
collateralReleaseLevel
asset {
symbol
}
}
}
}
market {
id
decimalPlaces
positionDecimalPlaces
tradingMode
tradableInstrument {
instrument {
name
}
}
data {
markPrice
market {
id
}
}
}
}
`;
export const POSITIONS_QUERY = gql`
${POSITION_FIELDS}
query Positions($partyId: ID!) {
party(id: $partyId) {
id
positionsConnection {
edges {
node {
...PositionFields
}
}
}
}
}
`;
export const POSITIONS_SUBSCRIPTION = gql`
${POSITION_FIELDS}
subscription PositionsSubscription($partyId: ID!) {
positions(partyId: $partyId) {
...PositionFields
}
}
`;
export const getMetrics = (
data: Positions_party | null,
accounts: Accounts_party_accounts[] | null
): Position[] => {
if (!data || !data?.positionsConnection.edges) {
return [];
}
const metrics: Position[] = [];
data?.positionsConnection.edges.forEach((position) => {
const market = position.node.market;
const marketData = market.data;
const marginLevel = position.node.marginsConnection.edges?.find(
(margin) => margin.node.market.id === market.id
)?.node;
const marginAccount = accounts?.find((account) => {
return account.market?.id === market.id;
});
feat(#840): update positions tab (#1101) * feat(#473): add positions metrics data provider * feat(#473) add positions stats * feat(#473) add positions stats * feat(#473): add positions stats * feat(#473): add positions stats * feat(#473): position metrics, test and refactoring * feat(#473): add unit tests to positions table * feat(#473): fix spelling, order positions by updated at desc * feat(#473): protect from division by 0 * feat(#473): fix trading positions e2e tests * feat(#473): fix e2e data mocks * feat(#473): post code review clean up * feat(#993): dependencies handling in data provider * feat(#993): fix e2e tests data mocks * feat(#993): remove position metrics mocks, add market data market id * feat(#993): add missing mocks, fix combine function * feat(#993): set loading initially to true, add unit tests * feat(#993): cleanup, add comments * feat(#993): remove undefined from client type * feat(#993): cosmetic changes * feat(#840): update positions tab * feat:(#993): pass informaton about update callback cause * feat(#840): update positions tab * feat(#840): update positions tab * feat(#840): update positions tab * chore: skip handles 5000 markets e2e test * feat(#840): update positions tab * feat(#840): rename assetDecimals to decimals * feat(#840): close position * feat(#993): notify about update * feat(#840): add use close position hook * feat(#840): do not show 0 volume positions, make liquidation price minimum 0 * feat(#840): post code review fixes and improvments * feat: fix fill-table spec
2022-09-02 20:53:00 +00:00
if (
!marginAccount ||
!marginLevel ||
!marketData ||
position.node.openVolume === '0'
) {
return;
}
const generalAccount = accounts?.find(
(account) =>
account.asset.id === marginAccount.asset.id &&
feat: 0.54.0 (#949) * chore: remove stagnet2, add stagnet3 * fix: types for transaction order submission (#932) * test: add night runs again (#917) Co-authored-by: Rado <rado@vegaprotocol.io> * chore: update tranches Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * Feat/893 anchor per network param (#907) * feat: highlight network param targeted by anchor * Feat/893: Highlighted key-value row colours * Feat/893: Removed unneeded important bangs Co-authored-by: sam-keen <samuel.kleinmann@gmail.com> * Fix/687: Jump to block input should not allow negative block numbers or 0 (#918) * Fix/687: Jump to block input should not allow negative block numbers * Fix/687: Jump to block input should have a minimum of 1 * fix: text and theme icon colors (#920) * Fix/eager connection (#923) * fix: eager connect * chore: add comment for eslint disable * chore: update tranches Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * chore: update tranches Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * chore: update tranches Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * chore: update tranches Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * chore: update tranches Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * chore: update tranches Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * chore: update tranches Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * chore: update tranches Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * chore: update tranches Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * chore: update tranches Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * chore: update tranches Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * Task/Remove vegawallet service api client (#916) * chore: remove generated vegawallet client code and implement in rest connector * feat: add zod validation * feat: handle specific auth/token delete case * feat: make withdraw dialog match vega tx dialog * fix: response stub to be right shape, add content type to requests * chore: revert unrelated classname change * feat: [console-lite] - fixes in order margin calcs (#891) * feat: [console-lite] - fixes in order margin calcs * feat: [console-lite] - fixes in order margin calcs - fix decimals * feat: [console-lite] - fixes in order margin calcs - add unit tests * feat: [console-lite] - fixes in order margin calcs - improve cals * feat: [console-lite] - fixes in order margin calcs - improve cals * feat: [console-lite] - fixes in order margin calcs - more improvements Co-authored-by: maciek <maciek@vegaprotocol.io> * fix: make check link unclickable while loading (#928) * fix: make check link unclickable while loading * fix: format * chore: update tranches Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * fix/904: Validators sorting (#913) * fix(790): gap between orderbook headers and tabs (#929) * feat: show correct reward type (#930) * chore: update tranches Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * chore: update tranches Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * chore: update tranches Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * Task/remove vegawallet service (#926) * feat: improve error handling * chore: lint * fix: cypress test incorrect assertion * chore: update tranches Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * chore: update tranches Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * chore: update tranches Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * chore: update tranches Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * fix: order transaction types Co-authored-by: Radosław Szpiech <szpiechrados@gmail.com> Co-authored-by: Rado <rado@vegaprotocol.io> Co-authored-by: mattrussell36 <mattrussell36@users.noreply.github.com> Co-authored-by: Edd <edd@vega.xyz> Co-authored-by: sam-keen <samuel.kleinmann@gmail.com> Co-authored-by: Sam Keen <samuel@vegaprotocol.io> Co-authored-by: Matthew Russell <mattrussell36@gmail.com> Co-authored-by: macqbat <kubat.maciek@gmail.com> Co-authored-by: maciek <maciek@vegaprotocol.io> Co-authored-by: asiaznik <artur.siaznik@gmail.com> Co-authored-by: Dexter Edwards <dexter.edwards93@gmail.com> * test: fix test import * chore: resolve bad merge files * chore: begin enum changes * test: fix the majority of the tests * test: fix tests * style: lint * fix: update enums * fix: adjusted tests to updated enums * ci: bump capsule * fix: temporarily skip failing staking tests * ci: revert capsule changes * test: fix tests for stats * chore: merge few changes and api updates to stagnet3 updates branch (#1100) * chore: merge few changes and api updates to stagnet3 updates branch * chore: [console-lite] - fast fix in unit test Co-authored-by: maciek <maciek@vegaprotocol.io> * test: fix broken test * chore: change to use the new nodes rather than load balancer * style: formatting * style: formatting * chore: fix env file * fix: don't assume GQL URL path * fix: skip positions query if there is no part * fix: simple trading app test Co-authored-by: botond <105208209+notbot00@users.noreply.github.com> Co-authored-by: Radosław Szpiech <szpiechrados@gmail.com> Co-authored-by: Rado <rado@vegaprotocol.io> Co-authored-by: mattrussell36 <mattrussell36@users.noreply.github.com> Co-authored-by: Edd <edd@vega.xyz> Co-authored-by: sam-keen <samuel.kleinmann@gmail.com> Co-authored-by: Sam Keen <samuel@vegaprotocol.io> Co-authored-by: Matthew Russell <mattrussell36@gmail.com> Co-authored-by: macqbat <kubat.maciek@gmail.com> Co-authored-by: maciek <maciek@vegaprotocol.io> Co-authored-by: asiaznik <artur.siaznik@gmail.com> Co-authored-by: Joe <joe@vega.xyz> Co-authored-by: m.ray <16125548+MadalinaRaicu@users.noreply.github.com>
2022-08-22 22:50:13 +00:00
account.type === AccountType.ACCOUNT_TYPE_GENERAL
);
feat(#840): update positions tab (#1101) * feat(#473): add positions metrics data provider * feat(#473) add positions stats * feat(#473) add positions stats * feat(#473): add positions stats * feat(#473): add positions stats * feat(#473): position metrics, test and refactoring * feat(#473): add unit tests to positions table * feat(#473): fix spelling, order positions by updated at desc * feat(#473): protect from division by 0 * feat(#473): fix trading positions e2e tests * feat(#473): fix e2e data mocks * feat(#473): post code review clean up * feat(#993): dependencies handling in data provider * feat(#993): fix e2e tests data mocks * feat(#993): remove position metrics mocks, add market data market id * feat(#993): add missing mocks, fix combine function * feat(#993): set loading initially to true, add unit tests * feat(#993): cleanup, add comments * feat(#993): remove undefined from client type * feat(#993): cosmetic changes * feat(#840): update positions tab * feat:(#993): pass informaton about update callback cause * feat(#840): update positions tab * feat(#840): update positions tab * feat(#840): update positions tab * chore: skip handles 5000 markets e2e test * feat(#840): update positions tab * feat(#840): rename assetDecimals to decimals * feat(#840): close position * feat(#993): notify about update * feat(#840): add use close position hook * feat(#840): do not show 0 volume positions, make liquidation price minimum 0 * feat(#840): post code review fixes and improvments * feat: fix fill-table spec
2022-09-02 20:53:00 +00:00
const decimals = marginAccount.asset.decimals;
const { positionDecimalPlaces, decimalPlaces: marketDecimalPlaces } =
market;
const openVolume = toBigNum(
position.node.openVolume,
positionDecimalPlaces
);
feat(#840): update positions tab (#1101) * feat(#473): add positions metrics data provider * feat(#473) add positions stats * feat(#473) add positions stats * feat(#473): add positions stats * feat(#473): add positions stats * feat(#473): position metrics, test and refactoring * feat(#473): add unit tests to positions table * feat(#473): fix spelling, order positions by updated at desc * feat(#473): protect from division by 0 * feat(#473): fix trading positions e2e tests * feat(#473): fix e2e data mocks * feat(#473): post code review clean up * feat(#993): dependencies handling in data provider * feat(#993): fix e2e tests data mocks * feat(#993): remove position metrics mocks, add market data market id * feat(#993): add missing mocks, fix combine function * feat(#993): set loading initially to true, add unit tests * feat(#993): cleanup, add comments * feat(#993): remove undefined from client type * feat(#993): cosmetic changes * feat(#840): update positions tab * feat:(#993): pass informaton about update callback cause * feat(#840): update positions tab * feat(#840): update positions tab * feat(#840): update positions tab * chore: skip handles 5000 markets e2e test * feat(#840): update positions tab * feat(#840): rename assetDecimals to decimals * feat(#840): close position * feat(#993): notify about update * feat(#840): add use close position hook * feat(#840): do not show 0 volume positions, make liquidation price minimum 0 * feat(#840): post code review fixes and improvments * feat: fix fill-table spec
2022-09-02 20:53:00 +00:00
const marginAccountBalance = toBigNum(marginAccount.balance ?? 0, decimals);
const generalAccountBalance = toBigNum(
generalAccount?.balance ?? 0,
feat(#840): update positions tab (#1101) * feat(#473): add positions metrics data provider * feat(#473) add positions stats * feat(#473) add positions stats * feat(#473): add positions stats * feat(#473): add positions stats * feat(#473): position metrics, test and refactoring * feat(#473): add unit tests to positions table * feat(#473): fix spelling, order positions by updated at desc * feat(#473): protect from division by 0 * feat(#473): fix trading positions e2e tests * feat(#473): fix e2e data mocks * feat(#473): post code review clean up * feat(#993): dependencies handling in data provider * feat(#993): fix e2e tests data mocks * feat(#993): remove position metrics mocks, add market data market id * feat(#993): add missing mocks, fix combine function * feat(#993): set loading initially to true, add unit tests * feat(#993): cleanup, add comments * feat(#993): remove undefined from client type * feat(#993): cosmetic changes * feat(#840): update positions tab * feat:(#993): pass informaton about update callback cause * feat(#840): update positions tab * feat(#840): update positions tab * feat(#840): update positions tab * chore: skip handles 5000 markets e2e test * feat(#840): update positions tab * feat(#840): rename assetDecimals to decimals * feat(#840): close position * feat(#993): notify about update * feat(#840): add use close position hook * feat(#840): do not show 0 volume positions, make liquidation price minimum 0 * feat(#840): post code review fixes and improvments * feat: fix fill-table spec
2022-09-02 20:53:00 +00:00
decimals
);
const markPrice = toBigNum(marketData.markPrice, marketDecimalPlaces);
const notional = (
openVolume.isGreaterThan(0) ? openVolume : openVolume.multipliedBy(-1)
).multipliedBy(markPrice);
const totalBalance = marginAccountBalance.plus(generalAccountBalance);
const currentLeverage = totalBalance.isEqualTo(0)
? new BigNumber(0)
: notional.dividedBy(totalBalance);
const capitalUtilisation = totalBalance.isEqualTo(0)
? new BigNumber(0)
: marginAccountBalance.dividedBy(totalBalance).multipliedBy(100);
const marginMaintenance = toBigNum(
marginLevel.maintenanceLevel,
marketDecimalPlaces
);
const marginSearch = toBigNum(marginLevel.searchLevel, marketDecimalPlaces);
const marginInitial = toBigNum(
marginLevel.initialLevel,
marketDecimalPlaces
);
feat(#840): update positions tab (#1101) * feat(#473): add positions metrics data provider * feat(#473) add positions stats * feat(#473) add positions stats * feat(#473): add positions stats * feat(#473): add positions stats * feat(#473): position metrics, test and refactoring * feat(#473): add unit tests to positions table * feat(#473): fix spelling, order positions by updated at desc * feat(#473): protect from division by 0 * feat(#473): fix trading positions e2e tests * feat(#473): fix e2e data mocks * feat(#473): post code review clean up * feat(#993): dependencies handling in data provider * feat(#993): fix e2e tests data mocks * feat(#993): remove position metrics mocks, add market data market id * feat(#993): add missing mocks, fix combine function * feat(#993): set loading initially to true, add unit tests * feat(#993): cleanup, add comments * feat(#993): remove undefined from client type * feat(#993): cosmetic changes * feat(#840): update positions tab * feat:(#993): pass informaton about update callback cause * feat(#840): update positions tab * feat(#840): update positions tab * feat(#840): update positions tab * chore: skip handles 5000 markets e2e test * feat(#840): update positions tab * feat(#840): rename assetDecimals to decimals * feat(#840): close position * feat(#993): notify about update * feat(#840): add use close position hook * feat(#840): do not show 0 volume positions, make liquidation price minimum 0 * feat(#840): post code review fixes and improvments * feat: fix fill-table spec
2022-09-02 20:53:00 +00:00
const searchPrice = marginSearch
.minus(marginAccountBalance)
.dividedBy(openVolume)
.plus(markPrice);
const liquidationPrice = BigNumber.maximum(
0,
marginMaintenance
.minus(marginAccountBalance)
.minus(generalAccountBalance)
.dividedBy(openVolume)
.plus(markPrice)
);
const lowMarginLevel =
marginAccountBalance.isLessThan(
marginSearch.plus(marginInitial.minus(marginSearch).dividedBy(2))
) && generalAccountBalance.isLessThan(marginInitial.minus(marginSearch));
metrics.push({
marketName: market.tradableInstrument.instrument.name,
averageEntryPrice: position.node.averageEntryPrice,
capitalUtilisation: Math.round(capitalUtilisation.toNumber()),
currentLeverage: currentLeverage.toNumber(),
marketDecimalPlaces,
positionDecimalPlaces,
feat(#840): update positions tab (#1101) * feat(#473): add positions metrics data provider * feat(#473) add positions stats * feat(#473) add positions stats * feat(#473): add positions stats * feat(#473): add positions stats * feat(#473): position metrics, test and refactoring * feat(#473): add unit tests to positions table * feat(#473): fix spelling, order positions by updated at desc * feat(#473): protect from division by 0 * feat(#473): fix trading positions e2e tests * feat(#473): fix e2e data mocks * feat(#473): post code review clean up * feat(#993): dependencies handling in data provider * feat(#993): fix e2e tests data mocks * feat(#993): remove position metrics mocks, add market data market id * feat(#993): add missing mocks, fix combine function * feat(#993): set loading initially to true, add unit tests * feat(#993): cleanup, add comments * feat(#993): remove undefined from client type * feat(#993): cosmetic changes * feat(#840): update positions tab * feat:(#993): pass informaton about update callback cause * feat(#840): update positions tab * feat(#840): update positions tab * feat(#840): update positions tab * chore: skip handles 5000 markets e2e test * feat(#840): update positions tab * feat(#840): rename assetDecimals to decimals * feat(#840): close position * feat(#993): notify about update * feat(#840): add use close position hook * feat(#840): do not show 0 volume positions, make liquidation price minimum 0 * feat(#840): post code review fixes and improvments * feat: fix fill-table spec
2022-09-02 20:53:00 +00:00
decimals,
assetSymbol: marginLevel.asset.symbol,
feat(#840): update positions tab (#1101) * feat(#473): add positions metrics data provider * feat(#473) add positions stats * feat(#473) add positions stats * feat(#473): add positions stats * feat(#473): add positions stats * feat(#473): position metrics, test and refactoring * feat(#473): add unit tests to positions table * feat(#473): fix spelling, order positions by updated at desc * feat(#473): protect from division by 0 * feat(#473): fix trading positions e2e tests * feat(#473): fix e2e data mocks * feat(#473): post code review clean up * feat(#993): dependencies handling in data provider * feat(#993): fix e2e tests data mocks * feat(#993): remove position metrics mocks, add market data market id * feat(#993): add missing mocks, fix combine function * feat(#993): set loading initially to true, add unit tests * feat(#993): cleanup, add comments * feat(#993): remove undefined from client type * feat(#993): cosmetic changes * feat(#840): update positions tab * feat:(#993): pass informaton about update callback cause * feat(#840): update positions tab * feat(#840): update positions tab * feat(#840): update positions tab * chore: skip handles 5000 markets e2e test * feat(#840): update positions tab * feat(#840): rename assetDecimals to decimals * feat(#840): close position * feat(#993): notify about update * feat(#840): add use close position hook * feat(#840): do not show 0 volume positions, make liquidation price minimum 0 * feat(#840): post code review fixes and improvments * feat: fix fill-table spec
2022-09-02 20:53:00 +00:00
totalBalance: totalBalance.multipliedBy(10 ** decimals).toFixed(),
lowMarginLevel,
liquidationPrice: liquidationPrice
.multipliedBy(10 ** marketDecimalPlaces)
.toFixed(0),
marketId: position.node.market.id,
marketTradingMode: position.node.market.tradingMode,
markPrice: marketData.markPrice,
notional: notional.multipliedBy(10 ** marketDecimalPlaces).toFixed(0),
openVolume: position.node.openVolume,
realisedPNL: position.node.realisedPNL,
unrealisedPNL: position.node.unrealisedPNL,
searchPrice: searchPrice
.multipliedBy(10 ** marketDecimalPlaces)
.toFixed(0),
updatedAt: position.node.updatedAt,
});
});
return metrics;
};
export const update = (
data: Positions_party,
delta: PositionsSubscription_positions | null
) => {
return produce(data, (draft) => {
if (!draft.positionsConnection.edges || !delta) {
return;
}
const index = draft.positionsConnection.edges.findIndex(
(edge) => edge.node.market.id === delta.market.id
);
if (index !== -1) {
draft.positionsConnection.edges[index].node = delta;
} else {
draft.positionsConnection.edges.push({
__typename: 'PositionEdge',
node: delta,
});
}
});
};
export const positionDataProvider = makeDataProvider<
Positions,
Positions_party,
PositionsSubscription,
PositionsSubscription_positions
>({
query: POSITIONS_QUERY,
subscriptionQuery: POSITIONS_SUBSCRIPTION,
update,
getData: (responseData: Positions) => responseData.party,
getDelta: (subscriptionData: PositionsSubscription) =>
subscriptionData.positions,
});
export const positionsMetricsDataProvider = makeDerivedDataProvider<Position[]>(
[positionDataProvider, accountsDataProvider],
([positions, accounts]) => {
return sortBy(
getMetrics(
positions as Positions_party | null,
accounts as Accounts_party_accounts[] | null
),
'updatedAt'
).reverse();
}
);