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

314 lines
9.4 KiB
TypeScript
Raw Normal View History

import isEqual from 'lodash/isEqual';
import produce from 'immer';
import BigNumber from 'bignumber.js';
import sortBy from 'lodash/sortBy';
import type { Account } from '@vegaprotocol/accounts';
import { accountsDataProvider } from '@vegaprotocol/accounts';
import { toBigNum } from '@vegaprotocol/react-helpers';
import {
makeDataProvider,
makeDerivedDataProvider,
} from '@vegaprotocol/react-helpers';
import { AccountType } from '@vegaprotocol/types';
import type { MarketTradingMode } from '@vegaprotocol/types';
import type { MarketWithData } from '@vegaprotocol/market-list';
import { marketsWithDataProvider } from '@vegaprotocol/market-list';
import type {
PositionsQuery,
PositionsSubscriptionSubscription,
MarginsQuery,
MarginFieldsFragment,
} from './__generated___/Positions';
import {
PositionsDocument,
PositionsSubscriptionDocument,
} from './__generated___/Positions';
import { marginsDataProvider } from './margin-data-provider';
type PositionMarginLevel = Pick<
MarginFieldsFragment,
'maintenanceLevel' | 'searchLevel' | 'initialLevel'
>;
interface PositionRejoined {
realisedPNL: string;
openVolume: string;
unrealisedPNL: string;
averageEntryPrice: string;
updatedAt?: string | null;
market: MarketWithData | null;
margins: PositionMarginLevel | null;
}
export interface Position {
marketName: string;
averageEntryPrice: string;
marginAccountBalance: 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: PositionsQuery['party'] | null;
positions: Position[] | null;
}
export const getMetrics = (
data: PositionRejoined[] | null,
accounts: Account[] | null
): Position[] => {
if (!data || !data?.length) {
return [];
}
const metrics: Position[] = [];
data.forEach((position) => {
const market = position.market;
const marketData = market?.data;
const marginLevel = position.margins;
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 ||
!market ||
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
!marketData ||
position.openVolume === '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
) {
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.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.averageEntryPrice,
marginAccountBalance: marginAccount.balance,
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:
market.tradableInstrument.instrument.product.settlementAsset.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: market.id,
marketTradingMode: market.tradingMode,
markPrice: marketData.markPrice,
notional: notional.multipliedBy(10 ** marketDecimalPlaces).toFixed(0),
openVolume: position.openVolume,
realisedPNL: position.realisedPNL,
unrealisedPNL: position.unrealisedPNL,
searchPrice: searchPrice
.multipliedBy(10 ** marketDecimalPlaces)
.toFixed(0),
updatedAt: position.updatedAt || null,
});
});
return metrics;
};
export const update = (
data: PositionsQuery['party'],
deltas: PositionsSubscriptionSubscription['positions']
) => {
return produce(data, (draft) => {
chore: stagnet3 api updates (#1321) * chore: update account, fills and orders subscriptions in data providers * chore: update account, fills and orders subscriptions in data providers * fixing console-lite * fixing types in general - regen * chore: update account, fills and orders subscriptions in data providers * fixed console-lite unit tests, uncommented quote name * chore: update account, fills and orders subscriptions in data providers * type aligning of assets and proposals * fixes liquidity data provider * fixed accounts build errors and unit tests * regen types, removed market name * regen types * fixed positions * chore: handle updates in derived market provider, update orders * removed taker fee mapping (renamed to maker fee) * chore: update account, fills and orders subscriptions in data providers * chore: update account, fills and orders subscriptions in data providers * chore: fix Order type * chore: fix possible null types * chore: revert order-list.stories.tsx * chore: derivedDataProvider fixes * fills unit tests fixes * orders unit tests fixes * added eslint ingore for generated files in liquidity * added unique key to the list element of simple market toolbar * changed main-branch-name to develop for pr workflows * removed redundant waitFor * increased test timeout to 10s * removed mocked response * chore: disable simple market list tests * chore: fix e2e projects mock types * feat: [subscription-update] - uncomment some console-lite tests * cypress: trading-accounts * chore: replace market candles with candlesConnection * chore: ignore gql errors, to be reverted after candlesConnectio n will be fixed * feat: [subscription-update] - improve wrongly renamed hook * feat: [subscription-update] - improve wrongly renamed hook * feat: [subscription-update] - improve wrongly renamed hook 3 * chore: add pagination hangdling to derived data provier * cypress: trading-fills * feat: [stagnet3 api update] - remove redundant command in tests * feat: [stagnet3 api update] - remove redundant command in tests * chore: fix trading orders e2e tests * chore: fix console lite e2e mocks * chore: fix market-trade tests * chore: use markets only in market selector, change Instrument cache policy * chore: fix market-selector tests * feat: [subscription-update] - improve ag grid conf for unit tests * feat: [subscription-update] - improve ag grid conf for unit tests * chore: fix candle types in console lite market mocks * chore: revert error policy ignore * chore: revert jest timeout * chore: remove unused AccountFields * chore: revert remove unused AccountFields * chore: simplify node subscription probe * chore: remove unused generated types in candles-chart * chore: improve useMarketsList mock * feat: [subscription-update] - increase jest timeout * feat: [subscription-update] - fix jest timeout * feat: [subscription-update] - fix jest timeout * feat: [subscription-update] - try to fix failing test again * chore: fix candles-chart types * feat: [subscription-update] - temporary skip failing test * feat: [subscription-update] - temporary skip failing test * feat: [subscription-update] - temporary skip failing test * feat: [subscription-update] - fix failling int test * feat: [subscription-update] - try to restore commented unit tests * feat: [subscription-update] - try to restore commented unit tests * feat: [subscription-update] - improve fixed unit tests Co-authored-by: asiaznik <artur@vegaprotocol.io> Co-authored-by: maciek <maciek@vegaprotocol.io>
2022-09-20 15:24:28 +00:00
deltas.forEach((delta) => {
if (!draft?.positionsConnection?.edges || !delta) {
chore: stagnet3 api updates (#1321) * chore: update account, fills and orders subscriptions in data providers * chore: update account, fills and orders subscriptions in data providers * fixing console-lite * fixing types in general - regen * chore: update account, fills and orders subscriptions in data providers * fixed console-lite unit tests, uncommented quote name * chore: update account, fills and orders subscriptions in data providers * type aligning of assets and proposals * fixes liquidity data provider * fixed accounts build errors and unit tests * regen types, removed market name * regen types * fixed positions * chore: handle updates in derived market provider, update orders * removed taker fee mapping (renamed to maker fee) * chore: update account, fills and orders subscriptions in data providers * chore: update account, fills and orders subscriptions in data providers * chore: fix Order type * chore: fix possible null types * chore: revert order-list.stories.tsx * chore: derivedDataProvider fixes * fills unit tests fixes * orders unit tests fixes * added eslint ingore for generated files in liquidity * added unique key to the list element of simple market toolbar * changed main-branch-name to develop for pr workflows * removed redundant waitFor * increased test timeout to 10s * removed mocked response * chore: disable simple market list tests * chore: fix e2e projects mock types * feat: [subscription-update] - uncomment some console-lite tests * cypress: trading-accounts * chore: replace market candles with candlesConnection * chore: ignore gql errors, to be reverted after candlesConnectio n will be fixed * feat: [subscription-update] - improve wrongly renamed hook * feat: [subscription-update] - improve wrongly renamed hook * feat: [subscription-update] - improve wrongly renamed hook 3 * chore: add pagination hangdling to derived data provier * cypress: trading-fills * feat: [stagnet3 api update] - remove redundant command in tests * feat: [stagnet3 api update] - remove redundant command in tests * chore: fix trading orders e2e tests * chore: fix console lite e2e mocks * chore: fix market-trade tests * chore: use markets only in market selector, change Instrument cache policy * chore: fix market-selector tests * feat: [subscription-update] - improve ag grid conf for unit tests * feat: [subscription-update] - improve ag grid conf for unit tests * chore: fix candle types in console lite market mocks * chore: revert error policy ignore * chore: revert jest timeout * chore: remove unused AccountFields * chore: revert remove unused AccountFields * chore: simplify node subscription probe * chore: remove unused generated types in candles-chart * chore: improve useMarketsList mock * feat: [subscription-update] - increase jest timeout * feat: [subscription-update] - fix jest timeout * feat: [subscription-update] - fix jest timeout * feat: [subscription-update] - try to fix failing test again * chore: fix candles-chart types * feat: [subscription-update] - temporary skip failing test * feat: [subscription-update] - temporary skip failing test * feat: [subscription-update] - temporary skip failing test * feat: [subscription-update] - fix failling int test * feat: [subscription-update] - try to restore commented unit tests * feat: [subscription-update] - try to restore commented unit tests * feat: [subscription-update] - improve fixed unit tests Co-authored-by: asiaznik <artur@vegaprotocol.io> Co-authored-by: maciek <maciek@vegaprotocol.io>
2022-09-20 15:24:28 +00:00
return;
}
const index = draft.positionsConnection.edges.findIndex(
(edge) => edge.node.market.id === delta.marketId
chore: stagnet3 api updates (#1321) * chore: update account, fills and orders subscriptions in data providers * chore: update account, fills and orders subscriptions in data providers * fixing console-lite * fixing types in general - regen * chore: update account, fills and orders subscriptions in data providers * fixed console-lite unit tests, uncommented quote name * chore: update account, fills and orders subscriptions in data providers * type aligning of assets and proposals * fixes liquidity data provider * fixed accounts build errors and unit tests * regen types, removed market name * regen types * fixed positions * chore: handle updates in derived market provider, update orders * removed taker fee mapping (renamed to maker fee) * chore: update account, fills and orders subscriptions in data providers * chore: update account, fills and orders subscriptions in data providers * chore: fix Order type * chore: fix possible null types * chore: revert order-list.stories.tsx * chore: derivedDataProvider fixes * fills unit tests fixes * orders unit tests fixes * added eslint ingore for generated files in liquidity * added unique key to the list element of simple market toolbar * changed main-branch-name to develop for pr workflows * removed redundant waitFor * increased test timeout to 10s * removed mocked response * chore: disable simple market list tests * chore: fix e2e projects mock types * feat: [subscription-update] - uncomment some console-lite tests * cypress: trading-accounts * chore: replace market candles with candlesConnection * chore: ignore gql errors, to be reverted after candlesConnectio n will be fixed * feat: [subscription-update] - improve wrongly renamed hook * feat: [subscription-update] - improve wrongly renamed hook * feat: [subscription-update] - improve wrongly renamed hook 3 * chore: add pagination hangdling to derived data provier * cypress: trading-fills * feat: [stagnet3 api update] - remove redundant command in tests * feat: [stagnet3 api update] - remove redundant command in tests * chore: fix trading orders e2e tests * chore: fix console lite e2e mocks * chore: fix market-trade tests * chore: use markets only in market selector, change Instrument cache policy * chore: fix market-selector tests * feat: [subscription-update] - improve ag grid conf for unit tests * feat: [subscription-update] - improve ag grid conf for unit tests * chore: fix candle types in console lite market mocks * chore: revert error policy ignore * chore: revert jest timeout * chore: remove unused AccountFields * chore: revert remove unused AccountFields * chore: simplify node subscription probe * chore: remove unused generated types in candles-chart * chore: improve useMarketsList mock * feat: [subscription-update] - increase jest timeout * feat: [subscription-update] - fix jest timeout * feat: [subscription-update] - fix jest timeout * feat: [subscription-update] - try to fix failing test again * chore: fix candles-chart types * feat: [subscription-update] - temporary skip failing test * feat: [subscription-update] - temporary skip failing test * feat: [subscription-update] - temporary skip failing test * feat: [subscription-update] - fix failling int test * feat: [subscription-update] - try to restore commented unit tests * feat: [subscription-update] - try to restore commented unit tests * feat: [subscription-update] - improve fixed unit tests Co-authored-by: asiaznik <artur@vegaprotocol.io> Co-authored-by: maciek <maciek@vegaprotocol.io>
2022-09-20 15:24:28 +00:00
);
if (index !== -1) {
const currNode = draft.positionsConnection.edges[index].node;
draft.positionsConnection.edges[index].node = {
...currNode,
realisedPNL: delta.realisedPNL,
unrealisedPNL: delta.unrealisedPNL,
openVolume: delta.openVolume,
averageEntryPrice: delta.averageEntryPrice,
updatedAt: delta.updatedAt,
};
chore: stagnet3 api updates (#1321) * chore: update account, fills and orders subscriptions in data providers * chore: update account, fills and orders subscriptions in data providers * fixing console-lite * fixing types in general - regen * chore: update account, fills and orders subscriptions in data providers * fixed console-lite unit tests, uncommented quote name * chore: update account, fills and orders subscriptions in data providers * type aligning of assets and proposals * fixes liquidity data provider * fixed accounts build errors and unit tests * regen types, removed market name * regen types * fixed positions * chore: handle updates in derived market provider, update orders * removed taker fee mapping (renamed to maker fee) * chore: update account, fills and orders subscriptions in data providers * chore: update account, fills and orders subscriptions in data providers * chore: fix Order type * chore: fix possible null types * chore: revert order-list.stories.tsx * chore: derivedDataProvider fixes * fills unit tests fixes * orders unit tests fixes * added eslint ingore for generated files in liquidity * added unique key to the list element of simple market toolbar * changed main-branch-name to develop for pr workflows * removed redundant waitFor * increased test timeout to 10s * removed mocked response * chore: disable simple market list tests * chore: fix e2e projects mock types * feat: [subscription-update] - uncomment some console-lite tests * cypress: trading-accounts * chore: replace market candles with candlesConnection * chore: ignore gql errors, to be reverted after candlesConnectio n will be fixed * feat: [subscription-update] - improve wrongly renamed hook * feat: [subscription-update] - improve wrongly renamed hook * feat: [subscription-update] - improve wrongly renamed hook 3 * chore: add pagination hangdling to derived data provier * cypress: trading-fills * feat: [stagnet3 api update] - remove redundant command in tests * feat: [stagnet3 api update] - remove redundant command in tests * chore: fix trading orders e2e tests * chore: fix console lite e2e mocks * chore: fix market-trade tests * chore: use markets only in market selector, change Instrument cache policy * chore: fix market-selector tests * feat: [subscription-update] - improve ag grid conf for unit tests * feat: [subscription-update] - improve ag grid conf for unit tests * chore: fix candle types in console lite market mocks * chore: revert error policy ignore * chore: revert jest timeout * chore: remove unused AccountFields * chore: revert remove unused AccountFields * chore: simplify node subscription probe * chore: remove unused generated types in candles-chart * chore: improve useMarketsList mock * feat: [subscription-update] - increase jest timeout * feat: [subscription-update] - fix jest timeout * feat: [subscription-update] - fix jest timeout * feat: [subscription-update] - try to fix failing test again * chore: fix candles-chart types * feat: [subscription-update] - temporary skip failing test * feat: [subscription-update] - temporary skip failing test * feat: [subscription-update] - temporary skip failing test * feat: [subscription-update] - fix failling int test * feat: [subscription-update] - try to restore commented unit tests * feat: [subscription-update] - try to restore commented unit tests * feat: [subscription-update] - improve fixed unit tests Co-authored-by: asiaznik <artur@vegaprotocol.io> Co-authored-by: maciek <maciek@vegaprotocol.io>
2022-09-20 15:24:28 +00:00
} else {
draft.positionsConnection.edges.unshift({
__typename: 'PositionEdge',
node: {
...delta,
__typename: 'Position',
market: {
__typename: 'Market',
id: delta.marketId,
},
},
});
chore: stagnet3 api updates (#1321) * chore: update account, fills and orders subscriptions in data providers * chore: update account, fills and orders subscriptions in data providers * fixing console-lite * fixing types in general - regen * chore: update account, fills and orders subscriptions in data providers * fixed console-lite unit tests, uncommented quote name * chore: update account, fills and orders subscriptions in data providers * type aligning of assets and proposals * fixes liquidity data provider * fixed accounts build errors and unit tests * regen types, removed market name * regen types * fixed positions * chore: handle updates in derived market provider, update orders * removed taker fee mapping (renamed to maker fee) * chore: update account, fills and orders subscriptions in data providers * chore: update account, fills and orders subscriptions in data providers * chore: fix Order type * chore: fix possible null types * chore: revert order-list.stories.tsx * chore: derivedDataProvider fixes * fills unit tests fixes * orders unit tests fixes * added eslint ingore for generated files in liquidity * added unique key to the list element of simple market toolbar * changed main-branch-name to develop for pr workflows * removed redundant waitFor * increased test timeout to 10s * removed mocked response * chore: disable simple market list tests * chore: fix e2e projects mock types * feat: [subscription-update] - uncomment some console-lite tests * cypress: trading-accounts * chore: replace market candles with candlesConnection * chore: ignore gql errors, to be reverted after candlesConnectio n will be fixed * feat: [subscription-update] - improve wrongly renamed hook * feat: [subscription-update] - improve wrongly renamed hook * feat: [subscription-update] - improve wrongly renamed hook 3 * chore: add pagination hangdling to derived data provier * cypress: trading-fills * feat: [stagnet3 api update] - remove redundant command in tests * feat: [stagnet3 api update] - remove redundant command in tests * chore: fix trading orders e2e tests * chore: fix console lite e2e mocks * chore: fix market-trade tests * chore: use markets only in market selector, change Instrument cache policy * chore: fix market-selector tests * feat: [subscription-update] - improve ag grid conf for unit tests * feat: [subscription-update] - improve ag grid conf for unit tests * chore: fix candle types in console lite market mocks * chore: revert error policy ignore * chore: revert jest timeout * chore: remove unused AccountFields * chore: revert remove unused AccountFields * chore: simplify node subscription probe * chore: remove unused generated types in candles-chart * chore: improve useMarketsList mock * feat: [subscription-update] - increase jest timeout * feat: [subscription-update] - fix jest timeout * feat: [subscription-update] - fix jest timeout * feat: [subscription-update] - try to fix failing test again * chore: fix candles-chart types * feat: [subscription-update] - temporary skip failing test * feat: [subscription-update] - temporary skip failing test * feat: [subscription-update] - temporary skip failing test * feat: [subscription-update] - fix failling int test * feat: [subscription-update] - try to restore commented unit tests * feat: [subscription-update] - try to restore commented unit tests * feat: [subscription-update] - improve fixed unit tests Co-authored-by: asiaznik <artur@vegaprotocol.io> Co-authored-by: maciek <maciek@vegaprotocol.io>
2022-09-20 15:24:28 +00:00
}
});
});
};
export const positionsDataProvider = makeDataProvider<
PositionsQuery,
PositionsQuery['party'],
PositionsSubscriptionSubscription,
PositionsSubscriptionSubscription['positions']
>({
query: PositionsDocument,
subscriptionQuery: PositionsSubscriptionDocument,
update,
getData: (responseData: PositionsQuery) => responseData.party,
getDelta: (subscriptionData: PositionsSubscriptionSubscription) =>
subscriptionData.positions,
});
const upgradeMarginsConnection = (
marketId: string,
margins: MarginsQuery['party'] | null
) => {
if (marketId && margins?.marginsConnection?.edges) {
const index =
margins.marginsConnection.edges.findIndex(
(edge) => edge.node.market.id === marketId
) ?? -1;
if (index >= 0) {
const marginLevel = margins.marginsConnection.edges[index].node;
return {
maintenanceLevel: marginLevel.maintenanceLevel,
searchLevel: marginLevel.searchLevel,
initialLevel: marginLevel.initialLevel,
};
}
}
return null;
};
export const rejoinPositionData = (
positions: PositionsQuery['party'] | null,
marketsData: MarketWithData[] | null,
margins: MarginsQuery['party'] | null
): PositionRejoined[] | null => {
if (positions?.positionsConnection?.edges && marketsData && margins) {
return positions.positionsConnection.edges.map(({ node }) => {
return {
realisedPNL: node.realisedPNL,
openVolume: node.openVolume,
unrealisedPNL: node.unrealisedPNL,
averageEntryPrice: node.averageEntryPrice,
updatedAt: node.updatedAt,
market:
marketsData?.find((market) => market.id === node.market.id) || null,
margins: upgradeMarginsConnection(node.market.id, margins),
};
});
}
return null;
};
export interface PositionsMetricsProviderVariables {
partyId: string;
}
export const positionsMetricsProvider = makeDerivedDataProvider<
Position[],
chore: stagnet3 api updates (#1321) * chore: update account, fills and orders subscriptions in data providers * chore: update account, fills and orders subscriptions in data providers * fixing console-lite * fixing types in general - regen * chore: update account, fills and orders subscriptions in data providers * fixed console-lite unit tests, uncommented quote name * chore: update account, fills and orders subscriptions in data providers * type aligning of assets and proposals * fixes liquidity data provider * fixed accounts build errors and unit tests * regen types, removed market name * regen types * fixed positions * chore: handle updates in derived market provider, update orders * removed taker fee mapping (renamed to maker fee) * chore: update account, fills and orders subscriptions in data providers * chore: update account, fills and orders subscriptions in data providers * chore: fix Order type * chore: fix possible null types * chore: revert order-list.stories.tsx * chore: derivedDataProvider fixes * fills unit tests fixes * orders unit tests fixes * added eslint ingore for generated files in liquidity * added unique key to the list element of simple market toolbar * changed main-branch-name to develop for pr workflows * removed redundant waitFor * increased test timeout to 10s * removed mocked response * chore: disable simple market list tests * chore: fix e2e projects mock types * feat: [subscription-update] - uncomment some console-lite tests * cypress: trading-accounts * chore: replace market candles with candlesConnection * chore: ignore gql errors, to be reverted after candlesConnectio n will be fixed * feat: [subscription-update] - improve wrongly renamed hook * feat: [subscription-update] - improve wrongly renamed hook * feat: [subscription-update] - improve wrongly renamed hook 3 * chore: add pagination hangdling to derived data provier * cypress: trading-fills * feat: [stagnet3 api update] - remove redundant command in tests * feat: [stagnet3 api update] - remove redundant command in tests * chore: fix trading orders e2e tests * chore: fix console lite e2e mocks * chore: fix market-trade tests * chore: use markets only in market selector, change Instrument cache policy * chore: fix market-selector tests * feat: [subscription-update] - improve ag grid conf for unit tests * feat: [subscription-update] - improve ag grid conf for unit tests * chore: fix candle types in console lite market mocks * chore: revert error policy ignore * chore: revert jest timeout * chore: remove unused AccountFields * chore: revert remove unused AccountFields * chore: simplify node subscription probe * chore: remove unused generated types in candles-chart * chore: improve useMarketsList mock * feat: [subscription-update] - increase jest timeout * feat: [subscription-update] - fix jest timeout * feat: [subscription-update] - fix jest timeout * feat: [subscription-update] - try to fix failing test again * chore: fix candles-chart types * feat: [subscription-update] - temporary skip failing test * feat: [subscription-update] - temporary skip failing test * feat: [subscription-update] - temporary skip failing test * feat: [subscription-update] - fix failling int test * feat: [subscription-update] - try to restore commented unit tests * feat: [subscription-update] - try to restore commented unit tests * feat: [subscription-update] - improve fixed unit tests Co-authored-by: asiaznik <artur@vegaprotocol.io> Co-authored-by: maciek <maciek@vegaprotocol.io>
2022-09-20 15:24:28 +00:00
Position[],
PositionsMetricsProviderVariables
>(
[
positionsDataProvider,
accountsDataProvider,
marketsWithDataProvider,
marginsDataProvider,
],
([positions, accounts, marketsData, margins], variables) => {
const positionsData = rejoinPositionData(positions, marketsData, margins);
if (!variables) {
return [];
}
return sortBy(
getMetrics(positionsData, accounts as Account[] | null),
'marketName'
);
},
(data, delta, previousData) =>
data.filter((row) => {
const previousRow = previousData?.find(
(previousRow) => previousRow.marketId === row.marketId
);
return !(previousRow && isEqual(previousRow, row));
})
);