mango-v4-ui/components/trade/Orderbook.tsx

744 lines
23 KiB
TypeScript
Raw Normal View History

2022-09-13 23:24:26 -07:00
import { AccountInfo } from '@solana/web3.js'
import Big from 'big.js'
import mangoStore from '@store/mangoStore'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
2022-09-13 23:24:26 -07:00
import { Market, Orderbook as SpotOrderBook } from '@project-serum/serum'
import useInterval from '@components/shared/useInterval'
2022-09-20 13:05:50 -07:00
import isEqual from 'lodash/isEqual'
2022-09-13 23:24:26 -07:00
import usePrevious from '@components/shared/usePrevious'
import useLocalStorageState from 'hooks/useLocalStorageState'
2022-11-19 11:20:36 -08:00
import { floorToDecimal, getDecimalCount } from 'utils/numbers'
2022-11-22 21:38:31 -08:00
import { ANIMATION_SETTINGS_KEY } from 'utils/constants'
2022-09-13 23:24:26 -07:00
import { useTranslation } from 'next-i18next'
import Decimal from 'decimal.js'
2022-09-18 05:53:28 -07:00
import OrderbookIcon from '@components/icons/OrderbookIcon'
import Tooltip from '@components/shared/Tooltip'
import GroupSize from './GroupSize'
2022-09-26 20:51:31 -07:00
import { breakpoints } from '../../utils/theme'
import { useViewport } from 'hooks/useViewport'
2022-10-10 19:16:13 -07:00
import {
BookSide,
BookSideType,
MangoClient,
PerpMarket,
} from '@blockworks-foundation/mango-v4'
2022-11-20 12:20:27 -08:00
import useSelectedMarket from 'hooks/useSelectedMarket'
2022-11-24 18:39:14 -08:00
import { INITIAL_ANIMATION_SETTINGS } from '@components/settings/AnimationSettings'
2023-01-02 16:30:19 -08:00
import { ArrowPathIcon } from '@heroicons/react/20/solid'
2023-01-02 14:41:16 -08:00
import { sleep } from 'utils'
2022-09-13 23:24:26 -07:00
2022-11-30 07:46:20 -08:00
export const decodeBookL2 = (book: SpotOrderBook | BookSide): number[][] => {
2023-02-03 07:28:39 -08:00
const depth = 300
2022-11-30 07:46:20 -08:00
if (book instanceof SpotOrderBook) {
2022-12-02 15:57:36 -08:00
return book.getL2(depth).map(([price, size]) => [price, size])
2022-11-30 07:46:20 -08:00
} else if (book instanceof BookSide) {
return book.getL2Ui(depth)
}
return []
}
function decodeBook(
2022-10-10 19:16:13 -07:00
client: MangoClient,
market: Market | PerpMarket,
accInfo: AccountInfo<Buffer>,
side: 'bids' | 'asks'
2022-11-30 07:46:20 -08:00
): SpotOrderBook | BookSide {
if (market instanceof Market) {
const book = SpotOrderBook.decode(market, accInfo.data)
return book
} else {
const decodedAcc = client.program.coder.accounts.decode(
'bookSide',
accInfo.data
)
const book = BookSide.from(
client,
market,
side === 'bids' ? BookSideType.bids : BookSideType.asks,
decodedAcc
)
return book
2022-09-13 23:24:26 -07:00
}
}
2022-10-10 19:16:13 -07:00
// export function decodeBook(
// market: Market,
// accInfo: AccountInfo<Buffer>
// ): SpotOrderBook | undefined {
// if (market && accInfo?.data) {
// if (market instanceof Market) {
// return SpotOrderBook.decode(market, accInfo.data)
// }
// else if (market instanceof PerpMarket) {
// // FIXME: Review the null being passed here
// return new BookSide(
// // @ts-ignore
// null,
// market,
// BookSideLayout.decode(accInfo.data),
// undefined,
// 100000
// )
// }
// }
// }
2022-09-13 23:24:26 -07:00
type cumOrderbookSide = {
price: number
size: number
cumulativeSize: number
sizePercent: number
maxSizePercent: number
2022-09-29 13:00:36 -07:00
cumulativeSizePercent: number
2022-09-13 23:24:26 -07:00
}
const getCumulativeOrderbookSide = (
orders: any[],
totalSize: number,
maxSize: number,
2022-10-04 10:15:35 -07:00
depth: number
2022-09-13 23:24:26 -07:00
): cumOrderbookSide[] => {
2022-11-19 11:20:36 -08:00
const cumulative = orders
2022-09-13 23:24:26 -07:00
.slice(0, depth)
.reduce((cumulative, [price, size], i) => {
const cumulativeSize = (cumulative[i - 1]?.cumulativeSize || 0) + size
cumulative.push({
price,
size,
cumulativeSize,
sizePercent: Math.round((cumulativeSize / (totalSize || 1)) * 100),
2022-09-29 13:00:36 -07:00
cumulativeSizePercent: Math.round((size / (cumulativeSize || 1)) * 100),
2022-09-13 23:24:26 -07:00
maxSizePercent: Math.round((size / (maxSize || 1)) * 100),
})
return cumulative
}, [])
2022-09-29 13:00:36 -07:00
2022-09-13 23:24:26 -07:00
return cumulative
}
const groupBy = (
ordersArray: number[][],
2022-10-10 19:16:13 -07:00
market: PerpMarket | Market,
2022-09-13 23:24:26 -07:00
grouping: number,
isBids: boolean
) => {
if (!ordersArray || !market || !grouping || grouping == market?.tickSize) {
return ordersArray || []
}
const groupFloors: Record<number, number> = {}
for (let i = 0; i < ordersArray.length; i++) {
if (typeof ordersArray[i] == 'undefined') {
break
}
const bigGrouping = Big(grouping)
const bigOrder = Big(ordersArray[i][0])
const floor = isBids
? bigOrder
.div(bigGrouping)
.round(0, Big.roundDown)
.times(bigGrouping)
.toNumber()
: bigOrder
.div(bigGrouping)
.round(0, Big.roundUp)
.times(bigGrouping)
.toNumber()
if (typeof groupFloors[floor] == 'undefined') {
groupFloors[floor] = ordersArray[i][1]
} else {
groupFloors[floor] = ordersArray[i][1] + groupFloors[floor]
}
}
const sortedGroups = Object.entries(groupFloors)
.map((entry) => {
return [
+parseFloat(entry[0]).toFixed(getDecimalCount(grouping)),
entry[1],
]
})
.sort((a: number[], b: number[]) => {
if (!a || !b) {
return -1
}
return isBids ? b[0] - a[0] : a[0] - b[0]
})
return sortedGroups
}
2022-09-20 18:18:04 -07:00
2022-11-01 11:13:02 -07:00
const hasOpenOrderForPriceGroup = (
openOrderPrices: number[],
price: string,
grouping: number
) => {
return !!openOrderPrices.find((ooPrice) => {
return (
ooPrice >= parseFloat(price) && ooPrice < parseFloat(price) + grouping
)
})
}
2022-09-25 19:02:26 -07:00
const depth = 40
2022-09-20 18:18:04 -07:00
2022-09-20 13:05:50 -07:00
const Orderbook = () => {
2022-10-03 03:38:05 -07:00
const { t } = useTranslation(['common', 'trade'])
2023-01-14 21:01:30 -08:00
const {
selectedMarket,
serumOrPerpMarket: market,
baseSymbol,
quoteSymbol,
} = useSelectedMarket()
const connection = mangoStore((s) => s.connection)
2022-09-13 23:24:26 -07:00
const [isScrolled, setIsScrolled] = useState(false)
2022-09-13 23:24:26 -07:00
const [orderbookData, setOrderbookData] = useState<any | null>(null)
const [grouping, setGrouping] = useState(0.01)
2022-09-18 05:53:28 -07:00
const [showBuys, setShowBuys] = useState(true)
const [showSells, setShowSells] = useState(true)
2022-11-01 11:13:02 -07:00
const [userOpenOrderPrices, setUserOpenOrderPrices] = useState<number[]>([])
2022-09-13 23:24:26 -07:00
const currentOrderbookData = useRef<any>(null)
const nextOrderbookData = useRef<any>(null)
const orderbookElRef = useRef<HTMLDivElement>(null)
2022-09-13 23:24:26 -07:00
const previousGrouping = usePrevious(grouping)
2022-09-26 20:51:31 -07:00
const { width } = useViewport()
const isMobile = width ? width < breakpoints.md : false
2022-09-13 23:24:26 -07:00
const depthArray = useMemo(() => {
const bookDepth = !isMobile ? depth : 9
2022-09-26 20:51:31 -07:00
return Array(bookDepth).fill(0)
2022-10-10 19:16:13 -07:00
}, [isMobile])
2022-09-13 23:24:26 -07:00
useEffect(() => {
2022-10-10 19:16:13 -07:00
if (!market) return
setGrouping(market.tickSize)
}, [market])
2022-09-13 23:24:26 -07:00
useEffect(
() =>
mangoStore.subscribe(
(state) => [state.selectedMarket.orderbook],
(orderbook) => (nextOrderbookData.current = orderbook)
),
[]
)
const verticallyCenterOrderbook = useCallback(() => {
const element = orderbookElRef.current
if (element) {
2022-09-20 18:18:04 -07:00
if (element.scrollHeight > window.innerHeight) {
element.scrollTop =
(element.scrollHeight - element.scrollHeight) / 2 +
(element.scrollHeight - window.innerHeight) / 2 +
94
} else {
element.scrollTop = (element.scrollHeight - element.offsetHeight) / 2
}
}
}, [])
2022-09-13 23:24:26 -07:00
useInterval(() => {
const orderbook = mangoStore.getState().selectedMarket.orderbook
const group = mangoStore.getState().group
2022-10-10 19:16:13 -07:00
if (!market || !group) return
2022-09-13 23:24:26 -07:00
if (
nextOrderbookData?.current &&
2022-09-20 13:05:50 -07:00
(!isEqual(currentOrderbookData.current, nextOrderbookData.current) ||
2022-09-13 23:24:26 -07:00
previousGrouping !== grouping)
) {
// check if user has open orders so we can highlight them on orderbook
2022-11-01 11:13:02 -07:00
const openOrders = mangoStore.getState().mangoAccount.openOrders
const marketPk =
selectedMarket && selectedMarket instanceof PerpMarket
? selectedMarket.publicKey
: selectedMarket?.serumMarketExternal
const newUserOpenOrderPrices =
marketPk && openOrders[marketPk.toString()]?.length
? openOrders[marketPk.toString()]?.map((order) => order.price)
: []
if (!isEqual(newUserOpenOrderPrices, userOpenOrderPrices)) {
setUserOpenOrderPrices(newUserOpenOrderPrices)
}
2022-09-13 23:24:26 -07:00
// updated orderbook data
2022-11-20 15:35:59 -08:00
const bids = groupBy(orderbook?.bids, market, grouping, true) || []
const asks = groupBy(orderbook?.asks, market, grouping, false) || []
2022-09-13 23:24:26 -07:00
const sum = (total: number, [, size]: number[], index: number) =>
index < depth ? total + size : total
const totalSize = bids.reduce(sum, 0) + asks.reduce(sum, 0)
2022-09-29 13:00:36 -07:00
2022-09-13 23:24:26 -07:00
const maxSize =
Math.max(
2022-09-29 13:00:36 -07:00
...bids.map((b: number[]) => {
return b[1]
2022-09-13 23:24:26 -07:00
})
) +
Math.max(
2022-09-29 13:00:36 -07:00
...asks.map((a: number[]) => {
return a[1]
2022-09-13 23:24:26 -07:00
})
)
2022-09-25 19:02:26 -07:00
const bidsToDisplay = getCumulativeOrderbookSide(
bids,
2022-09-29 13:00:36 -07:00
totalSize,
maxSize,
depth
2022-09-25 19:02:26 -07:00
)
const asksToDisplay = getCumulativeOrderbookSide(
asks,
2022-09-29 13:00:36 -07:00
totalSize,
maxSize,
2022-10-04 10:15:35 -07:00
depth
2022-09-25 19:02:26 -07:00
)
2022-09-13 23:24:26 -07:00
currentOrderbookData.current = {
bids: orderbook?.bids,
asks: orderbook?.asks,
}
if (bidsToDisplay[0] || asksToDisplay[0]) {
const bid = bidsToDisplay[0]?.price
2022-09-25 19:02:26 -07:00
const ask = asksToDisplay[0]?.price
2022-09-13 23:24:26 -07:00
let spread = 0,
spreadPercentage = 0
if (bid && ask) {
spread = ask - bid
spreadPercentage = (spread / ask) * 100
}
setOrderbookData({
bids: bidsToDisplay,
asks: asksToDisplay.reverse(),
spread,
spreadPercentage,
})
if (!isScrolled) {
verticallyCenterOrderbook()
}
2022-09-13 23:24:26 -07:00
} else {
setOrderbookData(null)
}
}
}, 400)
useEffect(() => {
const group = mangoStore.getState().group
const set = mangoStore.getState().set
2022-10-10 19:16:13 -07:00
const client = mangoStore.getState().client
2022-09-13 23:24:26 -07:00
2022-12-05 18:53:59 -08:00
if (!market || !group) return
2022-12-11 22:36:30 -08:00
let previousBidInfo: AccountInfo<Buffer> | undefined = undefined
let previousAskInfo: AccountInfo<Buffer> | undefined = undefined
let bidSubscriptionId: number | undefined = undefined
let askSubscriptionId: number | undefined = undefined
2022-12-05 18:53:59 -08:00
2022-10-10 19:16:13 -07:00
const bidsPk =
market instanceof Market ? market['_decoded'].bids : market.bids
2022-12-05 18:53:59 -08:00
console.log('bidsPk', bidsPk?.toString())
2022-11-15 20:12:51 -08:00
if (bidsPk) {
connection.getAccountInfo(bidsPk).then((info) => {
if (!info) return
2022-11-30 07:46:20 -08:00
const decodedBook = decodeBook(client, market, info, 'bids')
2022-11-15 20:12:51 -08:00
set((state) => {
2022-11-30 07:46:20 -08:00
state.selectedMarket.bidsAccount = decodedBook
state.selectedMarket.orderbook.bids = decodeBookL2(decodedBook)
2022-11-15 20:12:51 -08:00
})
2022-10-10 19:16:13 -07:00
})
2022-11-15 20:12:51 -08:00
bidSubscriptionId = connection.onAccountChange(
bidsPk,
2022-11-19 11:20:36 -08:00
(info, _context) => {
2022-11-15 20:12:51 -08:00
if (
!previousBidInfo ||
!previousBidInfo.data.equals(info.data) ||
previousBidInfo.lamports !== info.lamports
) {
previousBidInfo = info
2022-11-30 07:46:20 -08:00
const decodedBook = decodeBook(client, market, info, 'bids')
2022-11-15 20:12:51 -08:00
set((state) => {
2022-11-30 07:46:20 -08:00
state.selectedMarket.bidsAccount = decodedBook
state.selectedMarket.orderbook.bids = decodeBookL2(decodedBook)
2022-11-15 20:12:51 -08:00
})
}
2022-09-13 23:24:26 -07:00
}
2022-11-15 20:12:51 -08:00
)
}
2022-12-05 18:53:59 -08:00
2022-10-10 19:16:13 -07:00
const asksPk =
market instanceof Market ? market['_decoded'].asks : market.asks
2022-12-05 18:53:59 -08:00
console.log('asksPk', asksPk?.toString())
2022-11-15 20:12:51 -08:00
if (asksPk) {
connection.getAccountInfo(asksPk).then((info) => {
if (!info) return
2022-11-30 07:46:20 -08:00
const decodedBook = decodeBook(client, market, info, 'asks')
2022-11-15 20:12:51 -08:00
set((state) => {
2022-11-30 07:46:20 -08:00
state.selectedMarket.asksAccount = decodedBook
state.selectedMarket.orderbook.asks = decodeBookL2(decodedBook)
2022-11-15 20:12:51 -08:00
})
2022-10-10 19:16:13 -07:00
})
2022-11-15 20:12:51 -08:00
askSubscriptionId = connection.onAccountChange(
asksPk,
2022-11-19 11:20:36 -08:00
(info, _context) => {
2022-11-15 20:12:51 -08:00
if (
!previousAskInfo ||
!previousAskInfo.data.equals(info.data) ||
previousAskInfo.lamports !== info.lamports
) {
previousAskInfo = info
2022-11-30 07:46:20 -08:00
const decodedBook = decodeBook(client, market, info, 'asks')
2022-11-15 20:12:51 -08:00
set((state) => {
2022-11-30 07:46:20 -08:00
state.selectedMarket.asksAccount = decodedBook
state.selectedMarket.orderbook.asks = decodeBookL2(decodedBook)
2022-11-15 20:12:51 -08:00
})
}
2022-09-13 23:24:26 -07:00
}
2022-11-15 20:12:51 -08:00
)
}
2022-09-13 23:24:26 -07:00
return () => {
2022-12-11 22:36:30 -08:00
if (typeof bidSubscriptionId !== 'undefined') {
2022-11-15 20:12:51 -08:00
connection.removeAccountChangeListener(bidSubscriptionId)
}
2022-12-11 22:36:30 -08:00
if (typeof askSubscriptionId !== 'undefined') {
2022-11-15 20:12:51 -08:00
connection.removeAccountChangeListener(askSubscriptionId)
}
2022-09-13 23:24:26 -07:00
}
}, [market, connection])
2022-09-13 23:24:26 -07:00
useEffect(() => {
2022-09-25 22:32:48 -07:00
window.addEventListener('resize', verticallyCenterOrderbook)
// const id = setTimeout(verticallyCenterOrderbook, 400)
// return () => clearTimeout(id)
}, [verticallyCenterOrderbook])
2023-01-02 14:41:16 -08:00
const resetOrderbook = useCallback(async () => {
setShowBuys(true)
setShowSells(true)
await sleep(300)
verticallyCenterOrderbook()
}, [])
const onGroupSizeChange = useCallback((groupSize: number) => {
2022-09-18 05:53:28 -07:00
setGrouping(groupSize)
}, [])
2022-09-18 05:53:28 -07:00
2022-09-20 22:22:50 -07:00
const handleScroll = useCallback(() => {
setIsScrolled(true)
}, [])
2022-09-13 23:24:26 -07:00
return (
2022-09-20 13:05:50 -07:00
<div className="flex h-full flex-col">
<div className="flex items-center justify-between border-b border-th-bkg-3 px-4 py-2">
2023-01-02 16:30:19 -08:00
<div id="trade-step-three" className="flex items-center space-x-1.5">
2022-09-20 13:05:50 -07:00
<Tooltip
2022-10-03 03:38:05 -07:00
content={showBuys ? t('trade:hide-bids') : t('trade:show-bids')}
2023-01-02 14:48:05 -08:00
placement="bottom"
2022-09-20 13:05:50 -07:00
>
<button
className={`rounded ${
showBuys ? 'bg-th-bkg-3' : 'bg-th-bkg-2'
} default-transition flex h-6 w-6 items-center justify-center hover:border-th-fgd-4 focus:outline-none disabled:cursor-not-allowed`}
onClick={() => setShowBuys(!showBuys)}
disabled={!showSells}
2022-09-19 17:26:59 -07:00
>
2022-09-20 13:05:50 -07:00
<OrderbookIcon className="h-4 w-4" side="buy" />
</button>
</Tooltip>
<Tooltip
2022-10-03 03:38:05 -07:00
content={showSells ? t('trade:hide-asks') : t('trade:show-asks')}
2023-01-02 14:48:05 -08:00
placement="bottom"
2022-09-20 13:05:50 -07:00
>
<button
className={`rounded ${
showSells ? 'bg-th-bkg-3' : 'bg-th-bkg-2'
} default-transition flex h-6 w-6 items-center justify-center hover:border-th-fgd-4 focus:outline-none disabled:cursor-not-allowed`}
onClick={() => setShowSells(!showSells)}
disabled={!showBuys}
2022-09-18 05:53:28 -07:00
>
2022-09-20 13:05:50 -07:00
<OrderbookIcon className="h-4 w-4" side="sell" />
</button>
2022-09-18 05:53:28 -07:00
</Tooltip>
2023-01-02 14:48:05 -08:00
<Tooltip content={'Reset and center orderbook'} placement="bottom">
2023-01-02 14:41:16 -08:00
<button
className={`rounded ${
showSells ? 'bg-th-bkg-3' : 'bg-th-bkg-2'
} default-transition flex h-6 w-6 items-center justify-center hover:border-th-fgd-4 focus:outline-none disabled:cursor-not-allowed`}
onClick={resetOrderbook}
>
2023-01-02 16:30:19 -08:00
<ArrowPathIcon className="h-4 w-4" />
2023-01-02 14:41:16 -08:00
</button>
</Tooltip>
2022-09-18 05:53:28 -07:00
</div>
2022-10-10 19:16:13 -07:00
{market ? (
2022-09-30 05:55:28 -07:00
<div id="trade-step-four">
<Tooltip content={t('trade:grouping')} placement="left" delay={250}>
2022-09-30 05:55:28 -07:00
<GroupSize
2022-10-10 19:16:13 -07:00
tickSize={market.tickSize}
2022-09-30 05:55:28 -07:00
onChange={onGroupSizeChange}
value={grouping}
/>
</Tooltip>
</div>
2022-09-25 22:32:48 -07:00
) : null}
2022-09-20 13:05:50 -07:00
</div>
2022-09-21 21:46:30 -07:00
<div className="grid grid-cols-2 px-4 pt-2 pb-1 text-xxs text-th-fgd-4">
2023-01-14 21:01:30 -08:00
<div className="col-span-1 text-right">
{t('trade:size')} ({baseSymbol})
</div>
<div className="col-span-1 text-right">
{t('price')} ({quoteSymbol})
</div>
2022-09-20 13:05:50 -07:00
</div>
<div
className="hide-scroll relative h-full overflow-y-scroll"
ref={orderbookElRef}
2022-09-20 22:22:50 -07:00
onScroll={handleScroll}
2022-09-20 13:05:50 -07:00
>
2022-09-25 22:32:48 -07:00
{showSells
? depthArray.map((_x, idx) => {
let index = idx
if (orderbookData?.asks) {
const lengthDiff = depthArray.length - orderbookData.asks.length
if (lengthDiff > 0) {
index = index < lengthDiff ? -1 : Math.abs(lengthDiff - index)
}
}
2022-09-20 13:05:50 -07:00
return (
<div className="h-[24px]" key={idx}>
2022-10-10 19:16:13 -07:00
{!!orderbookData?.asks[index] && market ? (
<MemoizedOrderbookRow
2022-10-10 19:16:13 -07:00
minOrderSize={market.minOrderSize}
tickSize={market.tickSize}
2022-11-01 11:13:02 -07:00
hasOpenOrder={hasOpenOrderForPriceGroup(
userOpenOrderPrices,
orderbookData?.asks[index].price,
grouping
)}
2022-09-20 13:05:50 -07:00
key={orderbookData?.asks[index].price}
price={orderbookData?.asks[index].price}
2022-09-26 12:56:06 -07:00
size={orderbookData?.asks[index].size}
2022-09-20 13:05:50 -07:00
side="sell"
2022-09-26 12:56:06 -07:00
sizePercent={orderbookData?.asks[index].sizePercent}
2022-09-29 13:00:36 -07:00
cumulativeSizePercent={
orderbookData?.asks[index].cumulativeSizePercent
}
grouping={grouping}
/>
) : null}
</div>
2022-09-20 13:05:50 -07:00
)
})
: null}
{showBuys && showSells ? (
2022-09-21 21:25:24 -07:00
<div
className="my-2 grid grid-cols-2 border-y border-th-bkg-3 py-2 px-4 text-xs text-th-fgd-4"
id="trade-step-nine"
>
2022-09-20 13:05:50 -07:00
<div className="col-span-1 flex justify-between">
2022-10-03 03:38:05 -07:00
<div className="text-xxs">{t('trade:spread')}</div>
2022-09-21 21:46:30 -07:00
<div className="font-mono">
2022-09-20 13:05:50 -07:00
{orderbookData?.spreadPercentage.toFixed(2)}%
</div>
</div>
2022-09-21 21:46:30 -07:00
<div className="col-span-1 text-right font-mono">
2022-09-20 13:05:50 -07:00
{orderbookData?.spread.toFixed(2)}
</div>
</div>
) : null}
2022-09-25 22:32:48 -07:00
{showBuys
2022-09-20 13:05:50 -07:00
? depthArray.map((_x, index) => (
2022-09-25 22:32:48 -07:00
<div className="h-[24px]" key={index}>
2022-10-10 19:16:13 -07:00
{!!orderbookData?.bids[index] && market ? (
2022-09-20 13:05:50 -07:00
<MemoizedOrderbookRow
2022-10-10 19:16:13 -07:00
minOrderSize={market.minOrderSize}
tickSize={market.tickSize}
2022-11-01 11:13:02 -07:00
hasOpenOrder={hasOpenOrderForPriceGroup(
userOpenOrderPrices,
orderbookData?.bids[index].price,
grouping
)}
2022-09-20 13:05:50 -07:00
price={orderbookData?.bids[index].price}
2022-09-26 12:56:06 -07:00
size={orderbookData?.bids[index].size}
2022-09-20 13:05:50 -07:00
side="buy"
2022-09-26 12:56:06 -07:00
sizePercent={orderbookData?.bids[index].sizePercent}
2022-09-29 13:00:36 -07:00
cumulativeSizePercent={
orderbookData?.bids[index].cumulativeSizePercent
2022-09-20 13:05:50 -07:00
}
grouping={grouping}
/>
) : null}
</div>
))
: null}
2022-09-13 23:24:26 -07:00
</div>
</div>
)
}
const OrderbookRow = ({
side,
price,
size,
sizePercent,
// invert,
2022-11-01 11:13:02 -07:00
hasOpenOrder,
2022-09-19 16:26:30 -07:00
minOrderSize,
2022-09-29 13:00:36 -07:00
cumulativeSizePercent,
2022-09-19 16:26:30 -07:00
tickSize,
2022-09-13 23:24:26 -07:00
grouping,
}: {
side: 'buy' | 'sell'
price: number
size: number
sizePercent: number
2022-09-29 13:00:36 -07:00
cumulativeSizePercent: number
2022-11-01 11:13:02 -07:00
hasOpenOrder: boolean
2022-09-13 23:24:26 -07:00
// invert: boolean
grouping: number
2022-09-19 16:26:30 -07:00
minOrderSize: number
tickSize: number
2022-09-13 23:24:26 -07:00
}) => {
const element = useRef<HTMLDivElement>(null)
2022-11-22 21:38:31 -08:00
const [animationSettings] = useLocalStorageState(
ANIMATION_SETTINGS_KEY,
INITIAL_ANIMATION_SETTINGS
)
2022-09-13 23:24:26 -07:00
const flashClassName = side === 'sell' ? 'red-flash' : 'green-flash'
useEffect(() => {
2022-11-22 21:38:31 -08:00
animationSettings['orderbook-flash'].active &&
2022-09-13 23:24:26 -07:00
!element.current?.classList.contains(`${flashClassName}`) &&
element.current?.classList.add(`${flashClassName}`)
const id = setTimeout(
() =>
element.current?.classList.contains(`${flashClassName}`) &&
element.current?.classList.remove(`${flashClassName}`),
2022-09-26 12:56:06 -07:00
500
2022-09-13 23:24:26 -07:00
)
return () => clearTimeout(id)
}, [price, size])
2022-09-26 12:56:06 -07:00
const formattedSize = useMemo(() => {
return minOrderSize && !isNaN(size)
2022-09-19 16:26:30 -07:00
? floorToDecimal(size, getDecimalCount(minOrderSize))
2022-09-13 23:24:26 -07:00
: new Decimal(size)
2022-09-26 12:56:06 -07:00
}, [size, minOrderSize])
2022-09-13 23:24:26 -07:00
2022-09-26 12:56:06 -07:00
const formattedPrice = useMemo(() => {
return tickSize && !isNaN(price)
2022-09-19 16:26:30 -07:00
? floorToDecimal(price, getDecimalCount(tickSize))
2022-09-13 23:24:26 -07:00
: new Decimal(price)
2022-09-26 12:56:06 -07:00
}, [price, tickSize])
2022-09-13 23:24:26 -07:00
2022-09-26 12:56:06 -07:00
const handlePriceClick = useCallback(() => {
const set = mangoStore.getState().set
set((state) => {
state.tradeForm.price = formattedPrice.toFixed()
if (state.tradeForm.baseSize && state.tradeForm.tradeType === 'Limit') {
const quoteSize = floorToDecimal(
formattedPrice.mul(new Decimal(state.tradeForm.baseSize)),
getDecimalCount(tickSize)
)
state.tradeForm.quoteSize = quoteSize.toFixed()
}
2022-09-26 12:56:06 -07:00
})
}, [formattedPrice, tickSize])
2022-09-13 23:24:26 -07:00
2022-12-08 15:56:36 -08:00
const handleSizeClick = useCallback(() => {
const set = mangoStore.getState().set
set((state) => {
state.tradeForm.baseSize = formattedSize.toString()
if (formattedSize && state.tradeForm.price) {
const quoteSize = floorToDecimal(
formattedSize.mul(new Decimal(state.tradeForm.price)),
getDecimalCount(tickSize)
)
state.tradeForm.quoteSize = quoteSize.toString()
}
2022-12-08 15:56:36 -08:00
})
}, [formattedSize, tickSize])
2022-09-13 23:24:26 -07:00
const groupingDecimalCount = useMemo(
() => getDecimalCount(grouping),
[grouping]
)
const minOrderSizeDecimals = useMemo(
2022-09-19 16:26:30 -07:00
() => getDecimalCount(minOrderSize),
[minOrderSize]
2022-09-13 23:24:26 -07:00
)
2022-09-19 16:26:30 -07:00
if (!minOrderSize) return null
2022-09-13 23:24:26 -07:00
return (
<div
className={`relative flex h-[24px] cursor-pointer justify-between border-b border-b-th-bkg-1 text-sm`}
2022-09-13 23:24:26 -07:00
ref={element}
>
<>
2022-12-08 15:56:36 -08:00
<div className="flex h-full w-full items-center justify-between text-th-fgd-3 hover:bg-th-bkg-2">
<div
className="flex h-full w-full items-center justify-start pl-2 hover:underline"
onClick={handleSizeClick}
>
2022-09-18 16:01:57 -07:00
<div
style={{ fontFeatureSettings: 'zero 1' }}
2022-09-29 13:00:36 -07:00
className={`z-10 w-full text-right font-mono text-xs ${
2022-11-30 19:32:32 -08:00
hasOpenOrder ? 'text-th-active' : ''
2022-09-18 16:01:57 -07:00
}`}
// onClick={handleSizeClick}
>
{formattedSize.toFixed(minOrderSizeDecimals)}
</div>
2022-09-13 23:24:26 -07:00
</div>
2022-12-08 15:56:36 -08:00
<div
className={`z-10 flex h-full w-full items-center pr-4 hover:underline`}
onClick={handlePriceClick}
>
<div className="w-full text-right font-mono text-xs">
{formattedPrice.toFixed(groupingDecimalCount)}
</div>
2022-09-13 23:24:26 -07:00
</div>
</div>
<Line
2022-09-29 13:00:36 -07:00
className={`absolute left-0 opacity-40 brightness-125 ${
2022-11-30 19:32:32 -08:00
side === 'buy' ? `bg-th-up-muted` : `bg-th-down-muted`
2022-09-13 23:24:26 -07:00
}`}
2022-09-29 13:00:36 -07:00
data-width={Math.max(sizePercent, 0.5) + '%'}
/>
<Line
className={`absolute left-0 opacity-70 ${
2022-11-30 19:32:32 -08:00
side === 'buy' ? `bg-th-up` : `bg-th-down`
2022-09-29 13:00:36 -07:00
}`}
data-width={
Math.max((cumulativeSizePercent / 100) * sizePercent, 0.1) + '%'
}
2022-09-13 23:24:26 -07:00
/>
</>
</div>
)
}
2022-09-19 16:26:30 -07:00
const MemoizedOrderbookRow = React.memo(OrderbookRow)
2022-11-20 15:35:59 -08:00
const Line = (props: {
className: string
invert?: boolean
'data-width': string
}) => {
2022-09-13 23:24:26 -07:00
return (
<div
className={`${props.className}`}
style={{
textAlign: props.invert ? 'left' : 'right',
height: '100%',
width: `${props['data-width'] ? props['data-width'] : ''}`,
}}
/>
)
}
export default Orderbook