mango-ui-v3/hooks/useMarkPrice.tsx

43 lines
1.3 KiB
TypeScript
Raw Normal View History

import { useEffect } from 'react'
2021-04-02 11:26:21 -07:00
import useMangoStore from '../stores/useMangoStore'
2021-08-25 07:44:06 -07:00
function formatMarkPriceDecimals(price) {
if (price) {
return +parseFloat(price).toFixed(price < 2 ? 4 : 2)
}
}
2021-04-02 11:26:21 -07:00
export default function useMarkPrice() {
const setMangoStore = useMangoStore((s) => s.set)
2021-04-29 07:38:28 -07:00
const markPrice = useMangoStore((s) => s.selectedMarket.markPrice)
const orderbook = useMangoStore((s) => s.selectedMarket.orderBook)
2021-06-24 09:30:45 -07:00
const fills = useMangoStore((state) => state.selectedMarket.fills)
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 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) => {
2021-08-25 07:44:06 -07:00
state.selectedMarket.markPrice = formatMarkPriceDecimals(newMarkPrice)
2021-04-12 21:40:26 -07:00
})
}
2021-04-02 11:26:21 -07:00
}, [orderbook, trades])
return markPrice
}