mango-ui-v3/hooks/useMarkPrice.tsx

52 lines
1.6 KiB
TypeScript
Raw Normal View History

import { useEffect } from 'react'
2021-12-05 17:13:23 -08:00
import {
fillsSelector,
marketSelector,
markPriceSelector,
orderbookSelector,
setStoreSelector,
} from '../stores/selectors'
2021-04-02 11:26:21 -07:00
import useMangoStore from '../stores/useMangoStore'
import { getDecimalCount } from '../utils'
2021-08-25 07:44:06 -07:00
2021-04-02 11:26:21 -07:00
export default function useMarkPrice() {
2021-12-05 17:13:23 -08:00
const setMangoStore = useMangoStore(setStoreSelector)
const markPrice = useMangoStore(markPriceSelector)
const orderbook = useMangoStore(orderbookSelector)
const fills = useMangoStore(fillsSelector)
const market = useMangoStore(marketSelector)
2021-04-02 11:26:21 -07:00
2021-06-24 09:30:45 -07:00
const trades = fills
.filter((trade) => trade?.eventFlags?.maker || trade?.maker)
.map((trade) => ({
...trade,
side: trade.side === 'buy' ? 'sell' : 'buy',
}))
2021-04-02 11:26:21 -07:00
useEffect(() => {
const bb = orderbook?.bids?.length > 0 && Number(orderbook.bids[0][0])
const ba = orderbook?.asks?.length > 0 && Number(orderbook.asks[0][0])
const last = trades && trades.length > 0 && trades[0].price
const priceElements = [bb, ba, last].filter((e) => e).sort((a, b) => a - b)
const newMarkPrice = priceElements
? priceElements[Math.floor(priceElements.length / 2)]
: null
// const newMarkPrice =
// bb && ba
// ? last
// ? [bb, ba, last].sort((a, b) => a - b)[1]
// : (bb + ba) / 2
// : null
2021-04-12 21:40:26 -07:00
if (newMarkPrice !== markPrice) {
setMangoStore((state) => {
state.selectedMarket.markPrice = newMarkPrice?.toFixed(
getDecimalCount(market?.tickSize)
)
2021-04-12 21:40:26 -07:00
})
}
2021-04-02 11:26:21 -07:00
}, [orderbook, trades])
return markPrice
}