import { useState, useEffect, useRef, useMemo } from 'react' import useIpAddress from '../../hooks/useIpAddress' import { getTokenBySymbol, getMarketIndexBySymbol, I80F48, PerpMarket, } from '@blockworks-foundation/mango-client' import { notify } from '../../utils/notifications' import { calculateTradePrice, getDecimalCount, sleep } from '../../utils' import { floorToDecimal, capitalize } from '../../utils/index' import useMangoStore from '../../stores/useMangoStore' import Button from '../Button' import Input from '../Input' import { Market } from '@project-serum/serum' import Big from 'big.js' import MarketFee from '../MarketFee' import Loading from '../Loading' import { ElementTitle } from '../styles' import ButtonGroup from '../ButtonGroup' import Checkbox from '../Checkbox' import OrderSideTabs from './OrderSideTabs' import Tooltip from '../Tooltip' import EstPriceImpact from './EstPriceImpact' import { useTranslation } from 'next-i18next' export default function SimpleTradeForm({ initLeverage }) { const { t } = useTranslation('common') const set = useMangoStore((s) => s.set) const { ipAllowed, spotAllowed } = useIpAddress() const connected = useMangoStore((s) => s.wallet.connected) const actions = useMangoStore((s) => s.actions) const groupConfig = useMangoStore((s) => s.selectedMangoGroup.config) const marketConfig = useMangoStore((s) => s.selectedMarket.config) const mangoAccount = useMangoStore((s) => s.selectedMangoAccount.current) const mangoGroup = useMangoStore((s) => s.selectedMangoGroup.current) const mangoClient = useMangoStore((s) => s.connection.client) const mangoCache = useMangoStore((s) => s.selectedMangoGroup.cache) const marketIndex = getMarketIndexBySymbol( groupConfig, marketConfig.baseSymbol ) const market = useMangoStore((s) => s.selectedMarket.current) const { side, baseSize, quoteSize, price, triggerPrice, tradeType } = useMangoStore((s) => s.tradeForm) const [postOnly, setPostOnly] = useState(false) const [ioc, setIoc] = useState(false) const [submitting, setSubmitting] = useState(false) const [positionSizePercent, setPositionSizePercent] = useState('') const [showStopForm, setShowStopForm] = useState(false) const [showTakeProfitForm, setShowTakeProfitForm] = useState(false) const [stopSizePercent, setStopSizePercent] = useState('5%') const [reduceOnly, setReduceOnly] = useState(false) const [spotMargin, setSpotMargin] = useState(false) const orderBookRef = useRef(useMangoStore.getState().selectedMarket.orderBook) const orderbook = orderBookRef.current useEffect( () => useMangoStore.subscribe( // @ts-ignore (orderBook) => (orderBookRef.current = orderBook), (state) => state.selectedMarket.orderBook ), [] ) useEffect(() => { if (tradeType !== 'Market' && tradeType !== 'Limit') { setTradeType('Limit') } }, []) useEffect(() => { if (tradeType === 'Market') { set((s) => { s.tradeForm.price = '' }) } }, [tradeType, set]) const setSide = (side) => set((s) => { s.tradeForm.side = side }) const setBaseSize = (baseSize) => set((s) => { if (!Number.isNaN(parseFloat(baseSize))) { s.tradeForm.baseSize = parseFloat(baseSize) } else { s.tradeForm.baseSize = baseSize } }) const setQuoteSize = (quoteSize) => set((s) => { if (!Number.isNaN(parseFloat(quoteSize))) { s.tradeForm.quoteSize = parseFloat(quoteSize) } else { s.tradeForm.quoteSize = quoteSize } }) const setPrice = (price) => set((s) => { if (!Number.isNaN(parseFloat(price))) { s.tradeForm.price = parseFloat(price) } else { s.tradeForm.price = price } }) const setTriggerPrice = (price) => set((s) => { if (!Number.isNaN(parseFloat(price))) { s.tradeForm.tripperPrice = parseFloat(price) } else { s.tradeForm.tripperPrice = price } }) const setTradeType = (type) => set((s) => { s.tradeForm.tradeType = type }) const markPriceRef = useRef(useMangoStore.getState().selectedMarket.markPrice) const markPrice = markPriceRef.current useEffect( () => useMangoStore.subscribe( (markPrice) => (markPriceRef.current = markPrice as number), (state) => state.selectedMarket.markPrice ), [] ) let minOrderSize = '0' if (market instanceof Market && market.minOrderSize) { minOrderSize = market.minOrderSize.toString() } else if (market instanceof PerpMarket) { const baseDecimals = getTokenBySymbol( groupConfig, marketConfig.baseSymbol ).decimals minOrderSize = new Big(market.baseLotSize) .div(new Big(10).pow(baseDecimals)) .toString() } const sizeDecimalCount = getDecimalCount(minOrderSize) let tickSize = 1 if (market instanceof Market) { tickSize = market.tickSize } else if (market instanceof PerpMarket) { const baseDecimals = getTokenBySymbol( groupConfig, marketConfig.baseSymbol ).decimals const quoteDecimals = getTokenBySymbol( groupConfig, groupConfig.quoteSymbol ).decimals const nativeToUi = new Big(10).pow(baseDecimals - quoteDecimals) const lotsToNative = new Big(market.quoteLotSize).div( new Big(market.baseLotSize) ) tickSize = lotsToNative.mul(nativeToUi).toNumber() } const onSetPrice = (price: number | '') => { setPrice(price) if (!price) return if (baseSize) { onSetBaseSize(baseSize) } } const onSetBaseSize = (baseSize: number | '') => { const { price } = useMangoStore.getState().tradeForm setPositionSizePercent('') setBaseSize(baseSize) if (!baseSize) { setQuoteSize('') return } const usePrice = Number(price) || markPrice if (!usePrice) { setQuoteSize('') return } const rawQuoteSize = baseSize * usePrice setQuoteSize(rawQuoteSize.toFixed(6)) } const onSetQuoteSize = (quoteSize: number | '') => { setPositionSizePercent('') setQuoteSize(quoteSize) if (!quoteSize) { setBaseSize('') return } if (!Number(price) && tradeType === 'Limit') { setBaseSize('') return } const usePrice = Number(price) || markPrice const rawBaseSize = quoteSize / usePrice const baseSize = quoteSize && floorToDecimal(rawBaseSize, sizeDecimalCount) setBaseSize(baseSize) } const onTradeTypeChange = (tradeType) => { setTradeType(tradeType) setPositionSizePercent('') if (tradeType === 'Market') { setIoc(true) setPrice('') } else { const priceOnBook = side === 'buy' ? orderbook?.asks : orderbook?.bids if (priceOnBook && priceOnBook.length > 0 && priceOnBook[0].length > 0) { setPrice(priceOnBook[0][0]) } setIoc(false) } } const postOnChange = (checked) => { if (checked) { setIoc(false) } setPostOnly(checked) } const iocOnChange = (checked) => { if (checked) { setPostOnly(false) } setIoc(checked) } const reduceOnChange = (checked) => { if (checked) { setReduceOnly(false) } setReduceOnly(checked) } async function onSubmit() { if (!price && tradeType === 'Limit') { notify({ title: t('missing-price'), type: 'error', }) return } else if (!baseSize) { notify({ title: t('missing-size'), type: 'error', }) return } const mangoAccount = useMangoStore.getState().selectedMangoAccount.current const mangoGroup = useMangoStore.getState().selectedMangoGroup.current const { askInfo, bidInfo } = useMangoStore.getState().selectedMarket const wallet = useMangoStore.getState().wallet.current if (!wallet || !mangoGroup || !mangoAccount || !market) return setSubmitting(true) try { const orderPrice = calculateTradePrice( tradeType, orderbook, baseSize, side, price ) if (!orderPrice) { notify({ title: t('price-unavailable'), description: t('try-again'), type: 'error', }) } const orderType = ioc ? 'ioc' : postOnly ? 'postOnly' : 'limit' let txid if (market instanceof Market) { txid = await mangoClient.placeSpotOrder( mangoGroup, mangoAccount, mangoGroup.mangoCache, market, wallet, side, orderPrice, baseSize, orderType ) } else { txid = await mangoClient.placePerpOrder( mangoGroup, mangoAccount, mangoGroup.mangoCache, market, wallet, side, orderPrice, baseSize, orderType, 0, side === 'buy' ? askInfo : bidInfo ) } notify({ title: t('successfully-placed'), txid }) setPrice('') onSetBaseSize('') } catch (e) { notify({ title: t('order-error'), description: e.message, txid: e.txid, type: 'error', }) } finally { await sleep(600) actions.reloadMangoAccount() actions.loadMarketFills() setSubmitting(false) } } const { max, deposits, borrows } = useMemo(() => { if (!mangoAccount) return { max: 0 } const priceOrDefault = price ? I80F48.fromNumber(price) : mangoGroup.getPrice(marketIndex, mangoCache) const { max: maxQuote, deposits, borrows, } = mangoAccount.getMaxLeverageForMarket( mangoGroup, mangoCache, marketIndex, market, side, priceOrDefault ) if (maxQuote.toNumber() <= 0) return { max: 0 } // multiply the maxQuote by a scaler value to account for // srm fees or rounding issues in getMaxLeverageForMarket const maxScaler = market instanceof PerpMarket ? 0.99 : 0.95 const scaledMax = price ? (maxQuote.toNumber() * maxScaler) / price : (maxQuote.toNumber() * maxScaler) / mangoGroup.getPrice(marketIndex, mangoCache).toNumber() return { max: scaledMax, deposits, borrows } }, [mangoAccount, mangoGroup, mangoCache, marketIndex, market, side, price]) const handleSetPositionSize = (percent) => { setPositionSizePercent(percent) const baseSize = max * (parseInt(percent) / 100) const step = parseFloat(minOrderSize) const roundedSize = (Math.round(baseSize / step) * step).toFixed( sizeDecimalCount ) setBaseSize(parseFloat(roundedSize)) const usePrice = Number(price) || markPrice if (!usePrice) { setQuoteSize('') } const rawQuoteSize = parseFloat(roundedSize) * usePrice setQuoteSize(rawQuoteSize.toFixed(6)) } const percentToClose = (size, total) => { return (size / total) * 100 } const roundedDeposits = parseFloat(deposits?.toFixed(sizeDecimalCount)) const roundedBorrows = parseFloat(borrows?.toFixed(sizeDecimalCount)) const closeDepositString = percentToClose(baseSize, roundedDeposits) > 100 ? t('close-open-short', { size: (+baseSize - roundedDeposits).toFixed(sizeDecimalCount), symbol: marketConfig.baseSymbol, }) : `${percentToClose(baseSize, roundedDeposits).toFixed(0)}% ${t( 'close-position' ).toLowerCase()}` const closeBorrowString = percentToClose(baseSize, roundedBorrows) > 100 ? t('close-open-long', { size: (+baseSize - roundedDeposits).toFixed(sizeDecimalCount), symbol: marketConfig.baseSymbol, }) : `${percentToClose(baseSize, roundedBorrows).toFixed(0)}% ${t( 'close-position' ).toLowerCase()}` const disabledTradeButton = (!price && tradeType === 'Limit') || !baseSize || !connected || submitting || !mangoAccount const hideProfitStop = (side === 'sell' && baseSize === roundedDeposits) || (side === 'buy' && baseSize === roundedBorrows) const canTrade = ipAllowed || (market instanceof Market && spotAllowed) return (
{marketConfig.name} {initLeverage}x
onTradeTypeChange(p)} values={['Limit', 'Market']} />
onSetPrice(e.target.value)} value={price} disabled={tradeType === 'Market'} placeholder={tradeType === 'Market' ? markPrice : null} prefix={ } />
onSetBaseSize(e.target.value)} value={baseSize} prefix={ } />
onSetQuoteSize(e.target.value)} value={quoteSize} prefix={ } />
handleSetPositionSize(p)} unit="%" values={['10', '25', '50', '75', '100']} />
{side === 'sell' ? (
{roundedDeposits > 0 ? closeDepositString : null}
) : (
{roundedBorrows > 0 ? closeBorrowString : null}
)}
{!hideProfitStop ? (
setShowStopForm(e.target.checked)} > {t('set-stop-loss')}
) : null} {!hideProfitStop ? (
setShowTakeProfitForm(e.target.checked)} > {t('set-take-profit')}
) : null}
{showStopForm && !hideProfitStop ? ( <>
setTriggerPrice(e.target.value)} value={triggerPrice} prefix={ } />
setStopSizePercent(p)} values={['5%', '10%', '15%', '20%', '25%']} />
) : null} {showTakeProfitForm && !hideProfitStop ? ( <>
setTriggerPrice(e.target.value)} value={triggerPrice} prefix={ } />
setStopSizePercent(p)} values={['5%', '10%', '15%', '20%', '25%']} />
) : null}
{tradeType === 'Limit' ? ( <>
postOnChange(e.target.checked)} > POST
iocOnChange(e.target.checked)} > IOC
) : null} {marketConfig.kind === 'perp' ? ( reduceOnChange(e.target.checked)} > Reduce Only ) : null} {marketConfig.kind === 'spot' ? ( setSpotMargin(e.target.checked)} > Margin ) : null}
{tradeType === 'Market' ? (
) : null}
{canTrade ? ( ) : (
)}
) }