mango-ui-v3/hooks/useTradeHistory.tsx

77 lines
2.4 KiB
TypeScript
Raw Normal View History

2021-04-14 15:46:36 -07:00
import { useState, useEffect } from 'react'
import useMangoStore from '../stores/useMangoStore'
import useSerumStore from '../stores/useSerumStore'
2021-04-12 21:40:26 -07:00
import useMarket from './useMarket'
import useInterval from './useInterval'
const byTimestamp = (a, b) => {
return (
new Date(b.loadTimestamp).getTime() - new Date(a.loadTimestamp).getTime()
)
}
const formatTradeHistory = (newTradeHistory) => {
return newTradeHistory
.flat()
.map((trade) => {
return {
...trade,
marketName: trade.marketName
? trade.marketName
: `${trade.baseCurrency}/${trade.quoteCurrency}`,
key: `${trade.orderId}${trade.side}${trade.uuid}`,
liquidity: trade.maker || trade?.eventFlags?.maker ? 'Maker' : 'Taker',
}
})
.sort(byTimestamp)
}
2021-04-12 21:40:26 -07:00
const useFills = () => {
const fills = useSerumStore((s) => s.fills)
const { market, marketName } = useMarket()
const marginAccount = useMangoStore((s) => s.selectedMarginAccount.current)
const selectedMangoGroup = useMangoStore((s) => s.selectedMangoGroup.current)
if (!marginAccount || !selectedMangoGroup) return null
const marketIndex = selectedMangoGroup.getMarketIndex(market)
const openOrdersAccount = marginAccount.openOrdersAccounts[marketIndex]
2021-04-13 17:14:38 -07:00
if (!openOrdersAccount) return []
2021-04-12 21:40:26 -07:00
return fills
.filter((fill) => fill.openOrders.equals(openOrdersAccount.publicKey))
.map((fill) => ({ ...fill, marketName }))
}
export const useTradeHistory = () => {
2021-04-12 21:40:26 -07:00
const eventQueueFills = useFills()
const [allTrades, setAllTrades] = useState<any[]>([])
2021-04-14 15:46:36 -07:00
const tradeHistory = useMangoStore((s) => s.tradeHistory)
const marginAccount = useMangoStore((s) => s.selectedMarginAccount.current)
2021-04-14 15:46:36 -07:00
const actions = useMangoStore((s) => s.actions)
2021-04-12 21:40:26 -07:00
useInterval(() => {
2021-04-14 15:46:36 -07:00
if (marginAccount) {
actions.fetchTradeHistory()
}
2021-04-14 15:46:36 -07:00
}, 12000)
useEffect(() => {
2021-04-13 17:14:38 -07:00
if (eventQueueFills && eventQueueFills.length > 0) {
const newFills = eventQueueFills.filter(
(fill) =>
!tradeHistory.find((t) => t.orderId === fill.orderId.toString())
)
const newTradeHistory = [...newFills, ...tradeHistory]
if (newFills.length > 0 && newTradeHistory.length !== allTrades.length) {
const formattedTradeHistory = formatTradeHistory(newTradeHistory)
setAllTrades(formattedTradeHistory)
}
}
}, [tradeHistory, eventQueueFills])
return { tradeHistory: allTrades }
}
export default useTradeHistory