chore: move market depth queries to .graphql file (#1814)

This commit is contained in:
Bartłomiej Głownia 2022-10-21 19:34:04 +02:00 committed by GitHub
parent 23b517b4a1
commit c6f8ff68b8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 134 additions and 408 deletions

View File

@ -1,12 +1,12 @@
import merge from 'lodash/merge';
import type { PartialDeep } from 'type-fest';
// eslint-disable-next-line @nrwl/nx/enforce-module-boundaries
import type { MarketDepth } from '../../../../../libs/market-depth/src/lib/__generated__/MarketDepth';
import type { MarketDepthQuery } from '../../../../../libs/market-depth/src/lib/__generated___/MarketDepth';
export const generateMarketDepth = (
override?: PartialDeep<MarketDepth>
): MarketDepth => {
const defaultResult: MarketDepth = {
override?: PartialDeep<MarketDepthQuery>
): MarketDepthQuery => {
const defaultResult: MarketDepthQuery = {
market: {
id: 'a46bd7e5277087723b7ab835844dec3cef8b4445738101269624bf5537d5d423',
depth: {

View File

@ -1,12 +1,12 @@
import merge from 'lodash/merge';
import type { PartialDeep } from 'type-fest';
// eslint-disable-next-line @nrwl/nx/enforce-module-boundaries
import type { MarketDepth } from '../../../../../libs/market-depth/src/lib/__generated__/MarketDepth';
import type { MarketDepthQuery } from '../../../../../libs/market-depth/src/lib/__generated___/MarketDepth';
export const generateMarketDepth = (
override?: PartialDeep<MarketDepth>
): MarketDepth => {
const defaultResult: MarketDepth = {
override?: PartialDeep<MarketDepthQuery>
): MarketDepthQuery => {
const defaultResult: MarketDepthQuery = {
market: {
id: 'market-0',
depth: {

View File

@ -1,14 +1,11 @@
import merge from 'lodash/merge';
import type { PartialDeep } from 'type-fest';
import type {
MarketDepth,
MarketDepth_market,
} from '@vegaprotocol/market-depth';
import type { MarketDepthQuery } from '@vegaprotocol/market-depth';
export const generateOrderBook = (
override?: PartialDeep<MarketDepth>
): MarketDepth => {
const marketDepth: MarketDepth_market = {
override?: PartialDeep<MarketDepthQuery>
): MarketDepthQuery => {
const marketDepth: MarketDepthQuery['market'] = {
id: 'b2426f67b085ba8fb429f1b529d49372b2d096c6fb6f509f76c5863abb6d969e',
depth: {
sell: [

View File

@ -1,50 +1,32 @@
fragment PriceLevelFields on PriceLevel {
price
volume
numberOfOrders
}
query MarketDepth($marketId: ID!) {
market(id: $marketId) {
id
decimalPlaces
positionDecimalPlaces
data {
staticMidPrice
marketTradingMode
indicativeVolume
indicativePrice
bestStaticBidPrice
bestStaticOfferPrice
market {
id
}
}
depth {
lastTrade {
price
}
sell {
price
volume
numberOfOrders
...PriceLevelFields
}
buy {
price
volume
numberOfOrders
...PriceLevelFields
}
sequenceNumber
}
}
}
subscription MarketDepthSubscription($marketIds: [ID!]!) {
marketsDepthUpdate(marketIds: $marketIds) {
subscription MarketDepthUpdate($marketId: ID!) {
marketsDepthUpdate(marketIds: [$marketId]) {
marketId
buy {
price
volume
numberOfOrders
}
sell {
price
volume
numberOfOrders
...PriceLevelFields
}
buy {
...PriceLevelFields
}
sequenceNumber
previousSequenceNumber

View File

@ -1,79 +0,0 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL query operation: MarketDepth
// ====================================================
export interface MarketDepth_market_depth_sell {
__typename: "PriceLevel";
/**
* The price of all the orders at this level (uint64)
*/
price: string;
/**
* The total remaining size of all orders at this level (uint64)
*/
volume: string;
/**
* The number of orders at this price level (uint64)
*/
numberOfOrders: string;
}
export interface MarketDepth_market_depth_buy {
__typename: "PriceLevel";
/**
* The price of all the orders at this level (uint64)
*/
price: string;
/**
* The total remaining size of all orders at this level (uint64)
*/
volume: string;
/**
* The number of orders at this price level (uint64)
*/
numberOfOrders: string;
}
export interface MarketDepth_market_depth {
__typename: "MarketDepth";
/**
* Sell side price levels (if available)
*/
sell: MarketDepth_market_depth_sell[] | null;
/**
* Buy side price levels (if available)
*/
buy: MarketDepth_market_depth_buy[] | null;
/**
* Sequence number for the current snapshot of the market depth
*/
sequenceNumber: string;
}
export interface MarketDepth_market {
__typename: "Market";
/**
* Market ID
*/
id: string;
/**
* Current depth on the order book for this market
*/
depth: MarketDepth_market_depth;
}
export interface MarketDepth {
/**
* An instrument that is trading on the Vega network
*/
market: MarketDepth_market | null;
}
export interface MarketDepthVariables {
marketId: string;
}

View File

@ -1,75 +0,0 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL subscription operation: MarketDepthSubscription
// ====================================================
export interface MarketDepthSubscription_marketsDepthUpdate_sell {
__typename: "PriceLevel";
/**
* The price of all the orders at this level (uint64)
*/
price: string;
/**
* The total remaining size of all orders at this level (uint64)
*/
volume: string;
/**
* The number of orders at this price level (uint64)
*/
numberOfOrders: string;
}
export interface MarketDepthSubscription_marketsDepthUpdate_buy {
__typename: "PriceLevel";
/**
* The price of all the orders at this level (uint64)
*/
price: string;
/**
* The total remaining size of all orders at this level (uint64)
*/
volume: string;
/**
* The number of orders at this price level (uint64)
*/
numberOfOrders: string;
}
export interface MarketDepthSubscription_marketsDepthUpdate {
__typename: "ObservableMarketDepthUpdate";
/**
* Market ID
*/
marketId: string;
/**
* Sell side price levels (if available)
*/
sell: MarketDepthSubscription_marketsDepthUpdate_sell[] | null;
/**
* Buy side price levels (if available)
*/
buy: MarketDepthSubscription_marketsDepthUpdate_buy[] | null;
/**
* Sequence number for the current snapshot of the market depth. It is always increasing but not monotonic.
*/
sequenceNumber: string;
/**
* Sequence number of the last update sent; useful for checking that no updates were missed.
*/
previousSequenceNumber: string;
}
export interface MarketDepthSubscription {
/**
* Subscribe to price level market depth updates
*/
marketsDepthUpdate: MarketDepthSubscription_marketsDepthUpdate[];
}
export interface MarketDepthSubscriptionVariables {
marketId: string;
}

View File

@ -3,57 +3,45 @@ import { Schema as Types } from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type PriceLevelFieldsFragment = { __typename?: 'PriceLevel', price: string, volume: string, numberOfOrders: string };
export type MarketDepthQueryVariables = Types.Exact<{
marketId: Types.Scalars['ID'];
}>;
export type MarketDepthQuery = { __typename?: 'Query', market?: { __typename?: 'Market', id: string, decimalPlaces: number, positionDecimalPlaces: number, data?: { __typename?: 'MarketData', staticMidPrice: string, marketTradingMode: Types.MarketTradingMode, indicativeVolume: string, indicativePrice: string, bestStaticBidPrice: string, bestStaticOfferPrice: string, market: { __typename?: 'Market', id: string } } | null, depth: { __typename?: 'MarketDepth', sequenceNumber: string, lastTrade?: { __typename?: 'Trade', price: string } | null, sell?: Array<{ __typename?: 'PriceLevel', price: string, volume: string, numberOfOrders: string }> | null, buy?: Array<{ __typename?: 'PriceLevel', price: string, volume: string, numberOfOrders: string }> | null } } | null };
export type MarketDepthQuery = { __typename?: 'Query', market?: { __typename?: 'Market', id: string, depth: { __typename?: 'MarketDepth', sequenceNumber: string, sell?: Array<{ __typename?: 'PriceLevel', price: string, volume: string, numberOfOrders: string }> | null, buy?: Array<{ __typename?: 'PriceLevel', price: string, volume: string, numberOfOrders: string }> | null } } | null };
export type MarketDepthSubscriptionSubscriptionVariables = Types.Exact<{
marketIds: Array<Types.Scalars['ID']> | Types.Scalars['ID'];
export type MarketDepthUpdateSubscriptionVariables = Types.Exact<{
marketId: Types.Scalars['ID'];
}>;
export type MarketDepthSubscriptionSubscription = { __typename?: 'Subscription', marketsDepthUpdate: Array<{ __typename?: 'ObservableMarketDepthUpdate', marketId: string, sequenceNumber: string, previousSequenceNumber: string, buy?: Array<{ __typename?: 'PriceLevel', price: string, volume: string, numberOfOrders: string }> | null, sell?: Array<{ __typename?: 'PriceLevel', price: string, volume: string, numberOfOrders: string }> | null }> };
export type MarketDepthUpdateSubscription = { __typename?: 'Subscription', marketsDepthUpdate: Array<{ __typename?: 'ObservableMarketDepthUpdate', marketId: string, sequenceNumber: string, previousSequenceNumber: string, sell?: Array<{ __typename?: 'PriceLevel', price: string, volume: string, numberOfOrders: string }> | null, buy?: Array<{ __typename?: 'PriceLevel', price: string, volume: string, numberOfOrders: string }> | null }> };
export const PriceLevelFieldsFragmentDoc = gql`
fragment PriceLevelFields on PriceLevel {
price
volume
numberOfOrders
}
`;
export const MarketDepthDocument = gql`
query MarketDepth($marketId: ID!) {
market(id: $marketId) {
id
decimalPlaces
positionDecimalPlaces
data {
staticMidPrice
marketTradingMode
indicativeVolume
indicativePrice
bestStaticBidPrice
bestStaticOfferPrice
market {
id
}
}
depth {
lastTrade {
price
}
sell {
price
volume
numberOfOrders
...PriceLevelFields
}
buy {
price
volume
numberOfOrders
...PriceLevelFields
}
sequenceNumber
}
}
}
`;
${PriceLevelFieldsFragmentDoc}`;
/**
* __useMarketDepthQuery__
@ -82,45 +70,41 @@ export function useMarketDepthLazyQuery(baseOptions?: Apollo.LazyQueryHookOption
export type MarketDepthQueryHookResult = ReturnType<typeof useMarketDepthQuery>;
export type MarketDepthLazyQueryHookResult = ReturnType<typeof useMarketDepthLazyQuery>;
export type MarketDepthQueryResult = Apollo.QueryResult<MarketDepthQuery, MarketDepthQueryVariables>;
export const MarketDepthSubscriptionDocument = gql`
subscription MarketDepthSubscription($marketIds: [ID!]!) {
marketsDepthUpdate(marketIds: $marketIds) {
export const MarketDepthUpdateDocument = gql`
subscription MarketDepthUpdate($marketId: ID!) {
marketsDepthUpdate(marketIds: [$marketId]) {
marketId
buy {
price
volume
numberOfOrders
}
sell {
price
volume
numberOfOrders
...PriceLevelFields
}
buy {
...PriceLevelFields
}
sequenceNumber
previousSequenceNumber
}
}
`;
${PriceLevelFieldsFragmentDoc}`;
/**
* __useMarketDepthSubscriptionSubscription__
* __useMarketDepthUpdateSubscription__
*
* To run a query within a React component, call `useMarketDepthSubscriptionSubscription` and pass it any options that fit your needs.
* When your component renders, `useMarketDepthSubscriptionSubscription` returns an object from Apollo Client that contains loading, error, and data properties
* To run a query within a React component, call `useMarketDepthUpdateSubscription` and pass it any options that fit your needs.
* When your component renders, `useMarketDepthUpdateSubscription` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the subscription, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useMarketDepthSubscriptionSubscription({
* const { data, loading, error } = useMarketDepthUpdateSubscription({
* variables: {
* marketIds: // value for 'marketIds'
* marketId: // value for 'marketId'
* },
* });
*/
export function useMarketDepthSubscriptionSubscription(baseOptions: Apollo.SubscriptionHookOptions<MarketDepthSubscriptionSubscription, MarketDepthSubscriptionSubscriptionVariables>) {
export function useMarketDepthUpdateSubscription(baseOptions: Apollo.SubscriptionHookOptions<MarketDepthUpdateSubscription, MarketDepthUpdateSubscriptionVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useSubscription<MarketDepthSubscriptionSubscription, MarketDepthSubscriptionSubscriptionVariables>(MarketDepthSubscriptionDocument, options);
return Apollo.useSubscription<MarketDepthUpdateSubscription, MarketDepthUpdateSubscriptionVariables>(MarketDepthUpdateDocument, options);
}
export type MarketDepthSubscriptionSubscriptionHookResult = ReturnType<typeof useMarketDepthSubscriptionSubscription>;
export type MarketDepthSubscriptionSubscriptionResult = Apollo.SubscriptionResult<MarketDepthSubscriptionSubscription>;
export type MarketDepthUpdateSubscriptionHookResult = ReturnType<typeof useMarketDepthUpdateSubscription>;
export type MarketDepthUpdateSubscriptionResult = Apollo.SubscriptionResult<MarketDepthUpdateSubscription>;

View File

@ -19,10 +19,9 @@ import {
import { marketDataProvider, marketProvider } from '@vegaprotocol/market-list';
import type { MarketData } from '@vegaprotocol/market-list';
import type {
MarketDepthSubscription_marketsDepthUpdate,
MarketDepthSubscription_marketsDepthUpdate_sell,
MarketDepthSubscription_marketsDepthUpdate_buy,
} from './__generated__/MarketDepthSubscription';
MarketDepthUpdateSubscription,
PriceLevelFieldsFragment,
} from './__generated___/MarketDepth';
import type { DepthChartProps } from 'pennant';
import { parseLevel, updateLevels } from './depth-chart-utils';
@ -42,8 +41,8 @@ export const DepthChartContainer = ({ marketId }: DepthChartManagerProps) => {
const dataRef = useRef<DepthData | null>(null);
const marketDataRef = useRef<MarketData | null>(null);
const deltaRef = useRef<{
sell: MarketDepthSubscription_marketsDepthUpdate_sell[];
buy: MarketDepthSubscription_marketsDepthUpdate_buy[];
sell: PriceLevelFieldsFragment[];
buy: PriceLevelFieldsFragment[];
}>({
sell: [],
buy: [],
@ -93,7 +92,7 @@ export const DepthChartContainer = ({ marketId }: DepthChartManagerProps) => {
({
delta: deltas,
}: {
delta?: MarketDepthSubscription_marketsDepthUpdate[];
delta?: MarketDepthUpdateSubscription['marketsDepthUpdate'];
}) => {
if (!dataRef.current) {
return false;

View File

@ -1,5 +1,4 @@
export * from './__generated__/MarketDepth';
export * from './__generated__/MarketDepthSubscription';
export * from './__generated___/MarketDepth';
export * from './depth-chart';
export * from './market-depth-provider';
export * from './orderbook-container';

View File

@ -1,79 +1,40 @@
import { gql } from '@apollo/client';
import { makeDataProvider } from '@vegaprotocol/react-helpers';
import { updateLevels } from './orderbook-data';
import type { Update } from '@vegaprotocol/react-helpers';
import {
MarketDepthDocument,
MarketDepthUpdateDocument,
} from './__generated___/MarketDepth';
import type {
MarketDepth,
MarketDepth_market,
} from './__generated__/MarketDepth';
import type {
MarketDepthSubscription,
MarketDepthSubscription_marketsDepthUpdate,
} from './__generated__/MarketDepthSubscription';
const MARKET_DEPTH_QUERY = gql`
query MarketDepth($marketId: ID!) {
market(id: $marketId) {
id
depth {
sell {
price
volume
numberOfOrders
}
buy {
price
volume
numberOfOrders
}
sequenceNumber
}
}
}
`;
export const MARKET_DEPTH_SUBSCRIPTION_QUERY = gql`
subscription MarketDepthSubscription($marketId: ID!) {
marketsDepthUpdate(marketIds: [$marketId]) {
marketId
sell {
price
volume
numberOfOrders
}
buy {
price
volume
numberOfOrders
}
sequenceNumber
previousSequenceNumber
}
}
`;
MarketDepthQuery,
MarketDepthUpdateSubscription,
} from './__generated___/MarketDepth';
const sequenceNumbers: Record<string, number> = {};
const update: Update<
MarketDepth_market,
MarketDepthSubscription_marketsDepthUpdate[]
ReturnType<typeof getData>,
ReturnType<typeof getDelta>
> = (data, deltas, reload) => {
if (!data) {
return;
}
for (const delta of deltas) {
if (delta.marketId !== data.id) {
continue;
}
/*
const sequenceNumber = Number(delta.sequenceNumber);
if (sequenceNumber <= sequenceNumbers[delta.marketId]) {
return data;
}
/*
if (sequenceNumber - 1 !== sequenceNumbers[delta.market.id]) {
sequenceNumbers[delta.market.id] = 0;
if (sequenceNumber - 1 !== sequenceNumbers[delta.marketId]) {
sequenceNumbers[delta.marketId] = 0;
reload();
return;
}
*/
sequenceNumbers[delta.marketId] = sequenceNumber;
*/
const updatedData = {
...data,
depth: { ...data.depth },
@ -89,7 +50,7 @@ const update: Update<
return data;
};
const getData = (responseData: MarketDepth) => {
const getData = (responseData: MarketDepthQuery) => {
if (responseData.market?.id) {
sequenceNumbers[responseData.market.id] = Number(
responseData.market.depth.sequenceNumber
@ -97,12 +58,12 @@ const getData = (responseData: MarketDepth) => {
}
return responseData.market;
};
const getDelta = (subscriptionData: MarketDepthSubscription) =>
const getDelta = (subscriptionData: MarketDepthUpdateSubscription) =>
subscriptionData.marketsDepthUpdate;
export const marketDepthProvider = makeDataProvider({
query: MARKET_DEPTH_QUERY,
subscriptionQuery: MARKET_DEPTH_SUBSCRIPTION_QUERY,
query: MarketDepthDocument,
subscriptionQuery: MarketDepthUpdateDocument,
update,
getData,
getDelta,

View File

@ -4,16 +4,12 @@ import {
updateCompactedRows,
} from './orderbook-data';
import type { OrderbookRowData } from './orderbook-data';
import type { MarketDepth_market_depth_sell } from './__generated__/MarketDepth';
import type {
MarketDepthSubscription_marketDepthUpdate_sell,
MarketDepthSubscription_marketDepthUpdate_buy,
} from './__generated__/MarketDepthSubscription';
import type { PriceLevelFieldsFragment } from './__generated___/MarketDepth';
describe('compactRows', () => {
const numberOfRows = 100;
const middle = 1000;
const sell: MarketDepth_market_depth_sell[] = new Array(numberOfRows)
const sell: PriceLevelFieldsFragment[] = new Array(numberOfRows)
.fill(null)
.map((n, i) => ({
__typename: 'PriceLevel',
@ -21,7 +17,7 @@ describe('compactRows', () => {
price: (middle + numberOfRows - i).toString(),
numberOfOrders: i.toString(),
}));
const buy: MarketDepth_market_depth_sell[] = new Array(numberOfRows)
const buy: PriceLevelFieldsFragment[] = new Array(numberOfRows)
.fill(null)
.map((n, i) => ({
__typename: 'PriceLevel',
@ -79,7 +75,7 @@ describe('compactRows', () => {
});
describe('updateLevels', () => {
let levels: MarketDepth_market_depth_sell[] = new Array(10)
let levels: PriceLevelFieldsFragment[] = new Array(10)
.fill(null)
.map((n, i) => ({
__typename: 'PriceLevel',
@ -88,7 +84,7 @@ describe('updateLevels', () => {
numberOfOrders: ((i + 1) * 10).toString(),
}));
it('updates, removes and adds new items', () => {
const removeFirstRow: MarketDepthSubscription_marketDepthUpdate_sell = {
const removeFirstRow: PriceLevelFieldsFragment = {
__typename: 'PriceLevel',
price: '10',
volume: '0',
@ -99,7 +95,7 @@ describe('updateLevels', () => {
levels = updateLevels(levels, [removeFirstRow]);
expect(levels[0].price).toEqual('20');
expect(updateLevels([], [removeFirstRow])).toEqual([]);
const addFirstRow: MarketDepthSubscription_marketDepthUpdate_sell = {
const addFirstRow: PriceLevelFieldsFragment = {
__typename: 'PriceLevel',
price: '10',
volume: '10',
@ -107,7 +103,7 @@ describe('updateLevels', () => {
};
levels = updateLevels(levels, [addFirstRow]);
expect(levels[0].price).toEqual('10');
const addBeforeLastRow: MarketDepthSubscription_marketDepthUpdate_sell = {
const addBeforeLastRow: PriceLevelFieldsFragment = {
__typename: 'PriceLevel',
price: '95',
volume: '95',
@ -115,7 +111,7 @@ describe('updateLevels', () => {
};
levels = updateLevels(levels, [addBeforeLastRow]);
expect(levels[levels.length - 2].price).toEqual('95');
const addAtTheEnd: MarketDepthSubscription_marketDepthUpdate_sell = {
const addAtTheEnd: PriceLevelFieldsFragment = {
__typename: 'PriceLevel',
price: '115',
volume: '115',
@ -123,7 +119,7 @@ describe('updateLevels', () => {
};
levels = updateLevels(levels, [addAtTheEnd]);
expect(levels[levels.length - 1].price).toEqual('115');
const updateLastRow: MarketDepthSubscription_marketDepthUpdate_sell = {
const updateLastRow: PriceLevelFieldsFragment = {
__typename: 'PriceLevel',
price: '115',
volume: '116',
@ -196,13 +192,13 @@ describe('updateCompactedRows', () => {
const resolution = 10;
it('update volume', () => {
const sell: MarketDepthSubscription_marketDepthUpdate_sell = {
const sell: PriceLevelFieldsFragment = {
__typename: 'PriceLevel',
price: '120',
volume: '10',
numberOfOrders: '10',
};
const buy: MarketDepthSubscription_marketDepthUpdate_buy = {
const buy: PriceLevelFieldsFragment = {
__typename: 'PriceLevel',
price: '80',
volume: '10',
@ -223,13 +219,13 @@ describe('updateCompactedRows', () => {
});
it('remove row', () => {
const sell: MarketDepthSubscription_marketDepthUpdate_sell = {
const sell: PriceLevelFieldsFragment = {
__typename: 'PriceLevel',
price: '121',
volume: '0',
numberOfOrders: '0',
};
const buy: MarketDepthSubscription_marketDepthUpdate_buy = {
const buy: PriceLevelFieldsFragment = {
__typename: 'PriceLevel',
price: '79',
volume: '0',
@ -245,13 +241,13 @@ describe('updateCompactedRows', () => {
});
it('add new row at the end', () => {
const sell: MarketDepthSubscription_marketDepthUpdate_sell = {
const sell: PriceLevelFieldsFragment = {
__typename: 'PriceLevel',
price: '131',
volume: '5',
numberOfOrders: '5',
};
const buy: MarketDepthSubscription_marketDepthUpdate_buy = {
const buy: PriceLevelFieldsFragment = {
__typename: 'PriceLevel',
price: '59',
volume: '5',
@ -271,13 +267,13 @@ describe('updateCompactedRows', () => {
});
it('add new row in the middle', () => {
const sell: MarketDepthSubscription_marketDepthUpdate_sell = {
const sell: PriceLevelFieldsFragment = {
__typename: 'PriceLevel',
price: '111',
volume: '5',
numberOfOrders: '5',
};
const buy: MarketDepthSubscription_marketDepthUpdate_buy = {
const buy: PriceLevelFieldsFragment = {
__typename: 'PriceLevel',
price: '91',
volume: '5',

View File

@ -3,15 +3,7 @@ import uniqBy from 'lodash/uniqBy';
import { VolumeType } from '@vegaprotocol/react-helpers';
import { MarketTradingMode } from '@vegaprotocol/types';
import type { MarketData } from '@vegaprotocol/market-list';
import type {
MarketDepth_market_depth_sell,
MarketDepth_market_depth_buy,
} from './__generated__/MarketDepth';
import type {
MarketDepthSubscription_marketsDepthUpdate_sell,
MarketDepthSubscription_marketsDepthUpdate_buy,
} from './__generated__/MarketDepthSubscription';
import type { PriceLevelFieldsFragment } from './__generated___/MarketDepth';
export interface CumulativeVol {
bid: number;
relativeBid?: number;
@ -104,35 +96,15 @@ export const createRow = (
const mapRawData =
(dataType: VolumeType.ask | VolumeType.bid) =>
(
data: Omit<
| MarketDepth_market_depth_sell
| MarketDepthSubscription_marketsDepthUpdate_sell
| MarketDepth_market_depth_buy
| MarketDepthSubscription_marketsDepthUpdate_buy,
'__typename'
>
): PartialOrderbookRowData =>
(data: PriceLevelFieldsFragment): PartialOrderbookRowData =>
createPartialRow(data.price, Number(data.volume), dataType);
/**
* @summary merges sell amd buy data, orders by price desc, group by price level, counts cumulative and relative values
*/
export const compactRows = (
sell:
| Omit<
| MarketDepth_market_depth_sell
| MarketDepthSubscription_marketsDepthUpdate_sell,
'__typename'
>[]
| null,
buy:
| Omit<
| MarketDepth_market_depth_buy
| MarketDepthSubscription_marketsDepthUpdate_buy,
'__typename'
>[]
| null,
sell: PriceLevelFieldsFragment[] | null | undefined,
buy: PriceLevelFieldsFragment[] | null | undefined,
resolution: number
) => {
// map raw sell data to OrderbookData
@ -202,9 +174,7 @@ export const compactRows = (
const partiallyUpdateCompactedRows = (
dataType: VolumeType,
data: OrderbookRowData[],
delta:
| MarketDepthSubscription_marketsDepthUpdate_sell
| MarketDepthSubscription_marketsDepthUpdate_buy,
delta: PriceLevelFieldsFragment,
resolution: number,
modifiedIndex: number
): [number, OrderbookRowData[]] => {
@ -259,8 +229,8 @@ const partiallyUpdateCompactedRows = (
*/
export const updateCompactedRows = (
rows: OrderbookRowData[],
sell: MarketDepthSubscription_marketsDepthUpdate_sell[] | null,
buy: MarketDepthSubscription_marketsDepthUpdate_buy[] | null,
sell: PriceLevelFieldsFragment[] | null,
buy: PriceLevelFieldsFragment[] | null,
resolution: number
) => {
let sellModifiedIndex = -1;
@ -352,11 +322,8 @@ export const mapMarketData = (
* @returns
*/
export const updateLevels = (
draft: (MarketDepth_market_depth_buy | MarketDepth_market_depth_sell)[],
updates: (
| MarketDepthSubscription_marketsDepthUpdate_buy
| MarketDepthSubscription_marketsDepthUpdate_sell
)[]
draft: PriceLevelFieldsFragment[],
updates: (PriceLevelFieldsFragment | PriceLevelFieldsFragment)[]
) => {
const levels = [...draft];
updates.forEach((update) => {
@ -406,22 +373,18 @@ export const generateMockData = ({
}: MockDataGeneratorParams) => {
let matrix = new Array(numberOfSellRows).fill(undefined);
let price = midPrice + (numberOfSellRows - Math.ceil(overlap / 2) + 1);
const sell: Omit<MarketDepth_market_depth_sell, '__typename'>[] = matrix.map(
(row, i) => ({
price: (price -= 1).toString(),
volume: (numberOfSellRows - i + 1).toString(),
numberOfOrders: '',
})
);
const sell: PriceLevelFieldsFragment[] = matrix.map((row, i) => ({
price: (price -= 1).toString(),
volume: (numberOfSellRows - i + 1).toString(),
numberOfOrders: '',
}));
price += overlap;
matrix = new Array(numberOfBuyRows).fill(undefined);
const buy: Omit<MarketDepth_market_depth_buy, '__typename'>[] = matrix.map(
(row, i) => ({
price: (price -= 1).toString(),
volume: (i + 2).toString(),
numberOfOrders: '',
})
);
const buy: PriceLevelFieldsFragment[] = matrix.map((row, i) => ({
price: (price -= 1).toString(),
volume: (i + 2).toString(),
numberOfOrders: '',
}));
const rows = compactRows(sell, buy, resolution);
return {
rows,

View File

@ -7,10 +7,9 @@ import { marketDataProvider, marketProvider } from '@vegaprotocol/market-list';
import type { MarketData } from '@vegaprotocol/market-list';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type {
MarketDepthSubscription_marketsDepthUpdate,
MarketDepthSubscription_marketsDepthUpdate_sell,
MarketDepthSubscription_marketsDepthUpdate_buy,
} from './__generated__/MarketDepthSubscription';
MarketDepthUpdateSubscription,
PriceLevelFieldsFragment,
} from './__generated___/MarketDepth';
import {
compactRows,
updateCompactedRows,
@ -32,8 +31,8 @@ export const OrderbookManager = ({ marketId }: OrderbookManagerProps) => {
const dataRef = useRef<OrderbookData>({ rows: null });
const marketDataRef = useRef<MarketData | null>(null);
const deltaRef = useRef<{
sell: MarketDepthSubscription_marketsDepthUpdate_sell[];
buy: MarketDepthSubscription_marketsDepthUpdate_buy[];
sell: PriceLevelFieldsFragment[];
buy: PriceLevelFieldsFragment[];
}>({
sell: [],
buy: [],
@ -63,7 +62,7 @@ export const OrderbookManager = ({ marketId }: OrderbookManagerProps) => {
({
delta: deltas,
}: {
delta?: MarketDepthSubscription_marketsDepthUpdate[];
delta?: MarketDepthUpdateSubscription['marketsDepthUpdate'];
}) => {
if (!dataRef.current.rows) {
return false;

View File

@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import throttle from 'lodash/throttle';
import { useDataProvider } from '@vegaprotocol/react-helpers';
import dataProvider from './market-depth-provider';
import type { MarketDepth_market } from './__generated__/MarketDepth';
import type { MarketDepthQuery } from './__generated___/MarketDepth';
interface Props {
variables: { marketId: string };
@ -13,10 +13,10 @@ export const useOrderBookData = ({
variables,
throttleMilliseconds = 1000,
}: Props) => {
const [orderbookData, setOrderbookData] = useState<MarketDepth_market | null>(
null
);
const dataRef = useRef<MarketDepth_market | null>(null);
const [orderbookData, setOrderbookData] = useState<
MarketDepthQuery['market'] | null
>(null);
const dataRef = useRef<MarketDepthQuery['market'] | null>(null);
const updateOrderbookData = useRef(
throttle(() => {
if (!dataRef.current) {
@ -27,7 +27,7 @@ export const useOrderBookData = ({
);
const update = useCallback(
({ data }: { data: MarketDepth_market | null }) => {
({ data }: { data: MarketDepthQuery['market'] | null }) => {
if (!data) {
return false;
}