Answer bet panel

This commit is contained in:
James Grugett 2022-02-14 14:14:02 -06:00
parent 467effa5ca
commit b9248499c9
4 changed files with 231 additions and 74 deletions

View File

@ -1,27 +0,0 @@
import * as _ from 'lodash'
export function getMultiProbability(
totalShares: {
[answerId: string]: number
},
answerId: string
) {
const squareSum = _.sumBy(Object.values(totalShares), (shares) => shares ** 2)
const shares = totalShares[answerId] ?? 0
return shares ** 2 / squareSum
}
export function calculateMultiShares(
totalShares: {
[answerId: string]: number
},
bet: number,
betChoice: string
) {
const squareSum = _.sumBy(Object.values(totalShares), (shares) => shares ** 2)
const shares = totalShares[betChoice] ?? 0
const c = 2 * bet * Math.sqrt(squareSum)
return Math.sqrt(bet ** 2 + shares ** 2 + c) - shares
}

View File

@ -1,39 +1,51 @@
import _ from 'lodash'
import { Bet } from './bet' import { Bet } from './bet'
import { Contract } from './contract' import { Contract } from './contract'
import { FEES } from './fees' import { FEES } from './fees'
export function getProbability(totalShares: { YES: number; NO: number }) { export function getProbability(totalShares: { YES: number; NO: number }) {
const { YES: y, NO: n } = totalShares return getOutcomeProbability(totalShares, 'YES')
return y ** 2 / (y ** 2 + n ** 2) }
export function getOutcomeProbability(
totalShares: {
[outcome: string]: number
},
outcome: string
) {
const squareSum = _.sumBy(Object.values(totalShares), (shares) => shares ** 2)
const shares = totalShares[outcome] ?? 0
return shares ** 2 / squareSum
} }
export function getProbabilityAfterBet( export function getProbabilityAfterBet(
totalShares: { YES: number; NO: number }, totalShares: {
outcome: 'YES' | 'NO', [outcome: string]: number
},
outcome: string,
bet: number bet: number
) { ) {
const shares = calculateShares(totalShares, bet, outcome) const shares = calculateShares(totalShares, bet, outcome)
const [YES, NO] = const prevShares = totalShares[outcome] ?? 0
outcome === 'YES' const newTotalShares = { ...totalShares, outcome: prevShares + shares }
? [totalShares.YES + shares, totalShares.NO]
: [totalShares.YES, totalShares.NO + shares]
return getProbability({ YES, NO }) return getOutcomeProbability(newTotalShares, outcome)
} }
export function calculateShares( export function calculateShares(
totalShares: { YES: number; NO: number }, totalShares: {
[outcome: string]: number
},
bet: number, bet: number,
betChoice: 'YES' | 'NO' betChoice: string
) { ) {
const [yesShares, noShares] = [totalShares.YES, totalShares.NO] const squareSum = _.sumBy(Object.values(totalShares), (shares) => shares ** 2)
const shares = totalShares[betChoice] ?? 0
const c = 2 * bet * Math.sqrt(yesShares ** 2 + noShares ** 2) const c = 2 * bet * Math.sqrt(squareSum)
return betChoice === 'YES' return Math.sqrt(bet ** 2 + shares ** 2 + c) - shares
? Math.sqrt(bet ** 2 + yesShares ** 2 + c) - yesShares
: Math.sqrt(bet ** 2 + noShares ** 2 + c) - noShares
} }
export function calculateEstimatedWinnings( export function calculateEstimatedWinnings(
@ -128,15 +140,15 @@ export function calculateCancelPayout(contract: Contract, bet: Bet) {
export function calculateStandardPayout( export function calculateStandardPayout(
contract: Contract, contract: Contract,
bet: Bet, bet: Bet,
outcome: 'YES' | 'NO' outcome: string
) { ) {
const { amount, outcome: betOutcome, shares } = bet const { amount, outcome: betOutcome, shares } = bet
if (betOutcome !== outcome) return 0 if (betOutcome !== outcome) return 0
const { totalShares, totalBets, phantomShares } = contract const { totalShares, totalBets, phantomShares } = contract
if (totalShares[outcome] === 0) return 0 if (!totalShares[outcome]) return 0
const truePool = contract.pool.YES + contract.pool.NO const truePool = _.sum(Object.values(totalShares))
if (totalBets[outcome] >= truePool) if (totalBets[outcome] >= truePool)
return (amount / totalBets[outcome]) * truePool return (amount / totalBets[outcome]) * truePool

View File

@ -1,6 +1,9 @@
import { Bet } from './bet' import { Bet } from './bet'
import { calculateShares, getProbability } from './calculate' import {
import { calculateMultiShares, getMultiProbability } from './calculate-multi' calculateShares,
getProbability,
getOutcomeProbability,
} from './calculate'
import { Contract } from './contract' import { Contract } from './contract'
import { User } from './user' import { User } from './user'
@ -66,7 +69,7 @@ export const getNewMultiBetInfo = (
const prevOutcomePool = pool[outcome] ?? 0 const prevOutcomePool = pool[outcome] ?? 0
const newPool = { ...pool, outcome: prevOutcomePool + amount } const newPool = { ...pool, outcome: prevOutcomePool + amount }
const shares = calculateMultiShares(contract.totalShares, amount, outcome) const shares = calculateShares(contract.totalShares, amount, outcome)
const prevShares = totalShares[outcome] ?? 0 const prevShares = totalShares[outcome] ?? 0
const newTotalShares = { ...totalShares, outcome: prevShares + shares } const newTotalShares = { ...totalShares, outcome: prevShares + shares }
@ -74,8 +77,8 @@ export const getNewMultiBetInfo = (
const prevTotalBets = totalBets[outcome] ?? 0 const prevTotalBets = totalBets[outcome] ?? 0
const newTotalBets = { ...totalBets, outcome: prevTotalBets + amount } const newTotalBets = { ...totalBets, outcome: prevTotalBets + amount }
const probBefore = getMultiProbability(totalShares, outcome) const probBefore = getOutcomeProbability(totalShares, outcome)
const probAfter = getMultiProbability(newTotalShares, outcome) const probAfter = getOutcomeProbability(newTotalShares, outcome)
const newBet: Bet<'MULTI'> = { const newBet: Bet<'MULTI'> = {
id: newBetId, id: newBetId,

View File

@ -1,18 +1,32 @@
import clsx from 'clsx' import clsx from 'clsx'
import { useState } from 'react' import { useEffect, useRef, useState } from 'react'
import Textarea from 'react-expanding-textarea' import Textarea from 'react-expanding-textarea'
import { Answer } from '../../common/answer' import { Answer } from '../../common/answer'
import { Contract } from '../../common/contract' import { Contract } from '../../common/contract'
import { AmountInput } from './amount-input' import { AmountInput } from './amount-input'
import { Col } from './layout/col' import { Col } from './layout/col'
import { createAnswer } from '../lib/firebase/api-call' import { createAnswer, placeBet } from '../lib/firebase/api-call'
import { Row } from './layout/row' import { Row } from './layout/row'
import { Avatar } from './avatar' import { Avatar } from './avatar'
import { SiteLink } from './site-link' import { SiteLink } from './site-link'
import { DateTimeTooltip } from './datetime-tooltip' import { DateTimeTooltip } from './datetime-tooltip'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import { BuyButton } from './yes-no-selector' import { BuyButton } from './yes-no-selector'
import { Spacer } from './layout/spacer'
import {
formatMoney,
formatPercent,
formatWithCommas,
} from '../../common/util/format'
import { InfoTooltip } from './info-tooltip'
import { useUser } from '../hooks/use-user'
import {
getProbabilityAfterBet,
getOutcomeProbability,
calculateShares,
} from '../../common/calculate'
import { firebaseLogin } from '../lib/firebase/users'
export function AnswersPanel(props: { export function AnswersPanel(props: {
contract: Contract<'MULTI'> contract: Contract<'MULTI'>
@ -36,33 +50,188 @@ function AnswerItem(props: { answer: Answer; contract: Contract<'MULTI'> }) {
const createdDate = dayjs(createdTime).format('MMM D') const createdDate = dayjs(createdTime).format('MMM D')
const [isBetting, setIsBetting] = useState(false)
return ( return (
<Col className="p-2 sm:flex-row"> <Col>
<Col className="gap-2 flex-1"> <Col className="p-2 sm:flex-row">
<div>{answer.text}</div> <Col className="gap-2 flex-1">
<div>{answer.text}</div>
<Row className="text-gray-500 text-sm gap-2 items-center"> <Row className="text-gray-500 text-sm gap-2 items-center">
<SiteLink className="relative" href={`/${username}`}> <SiteLink className="relative" href={`/${username}`}>
<Row className="items-center gap-2"> <Row className="items-center gap-2">
<Avatar avatarUrl={avatarUrl} size={6} /> <Avatar avatarUrl={avatarUrl} size={6} />
<div className="truncate">{name}</div> <div className="truncate">{name}</div>
</Row> </Row>
</SiteLink> </SiteLink>
<div className=""></div> <div className=""></div>
<div className="whitespace-nowrap"> <div className="whitespace-nowrap">
<DateTimeTooltip text="" time={contract.createdTime}> <DateTimeTooltip text="" time={contract.createdTime}>
{createdDate} {createdDate}
</DateTimeTooltip> </DateTimeTooltip>
</div> </div>
</Row> </Row>
</Col>
<BuyButton
className="justify-end self-end flex-initial"
onClick={() => {
setIsBetting(true)
}}
/>
</Col> </Col>
<BuyButton {isBetting && <AnswerBetPanel answer={answer} contract={contract} />}
className="justify-end self-end flex-initial" </Col>
onClick={() => {}} )
/> }
function AnswerBetPanel(props: {
answer: Answer
contract: Contract<'MULTI'>
}) {
const { answer, contract } = props
const { id: answerId } = answer
const user = useUser()
const [betAmount, setBetAmount] = useState<number | undefined>(undefined)
const [error, setError] = useState<string | undefined>()
const [isSubmitting, setIsSubmitting] = useState(false)
const [wasSubmitted, setWasSubmitted] = useState(false)
const inputRef = useRef<HTMLElement>(null)
useEffect(() => {
inputRef.current && inputRef.current.focus()
}, [])
function onBetChange(newAmount: number | undefined) {
setWasSubmitted(false)
setBetAmount(newAmount)
}
async function submitBet() {
if (!user || !betAmount) return
if (user.balance < betAmount) {
setError('Insufficient balance')
return
}
setError(undefined)
setIsSubmitting(true)
const result = await placeBet({
amount: betAmount,
outcome: answerId,
contractId: contract.id,
}).then((r) => r.data as any)
console.log('placed bet. Result:', result)
if (result?.status === 'success') {
setIsSubmitting(false)
setWasSubmitted(true)
setBetAmount(undefined)
} else {
setError(result?.error || 'Error placing bet')
setIsSubmitting(false)
}
}
const betDisabled = isSubmitting || !betAmount || error
const initialProb = getOutcomeProbability(contract.totalShares, answer.id)
const resultProb = getProbabilityAfterBet(
contract.totalShares,
answerId,
betAmount ?? 0
)
const shares = calculateShares(contract.totalShares, betAmount ?? 0, answerId)
const currentPayout = betAmount
? 0
: // calculatePayoutAfterCorrectBet(contract, {
// outcome: answerId,
// amount: betAmount,
// shares,
// } as Bet)
0
const currentReturn = betAmount ? (currentPayout - betAmount) / betAmount : 0
const currentReturnPercent = (currentReturn * 100).toFixed() + '%'
return (
<Col className="items-center">
<Col className="p-2 items-start">
<div className="my-3 text-left text-sm text-gray-500">Amount </div>
<AmountInput
inputClassName="w-full"
amount={betAmount}
onChange={onBetChange}
error={error}
setError={setError}
disabled={isSubmitting}
inputRef={inputRef}
/>
<Spacer h={4} />
<div className="mt-2 mb-1 text-sm text-gray-500">
Implied probability
</div>
<Row>
<div>{formatPercent(initialProb)}</div>
<div className="mx-2"></div>
<div>{formatPercent(resultProb)}</div>
</Row>
<Spacer h={4} />
<Row className="mt-2 mb-1 items-center gap-2 text-sm text-gray-500">
Potential payout
<InfoTooltip
text={`Current payout for ${formatWithCommas(
shares
)} / ${formatWithCommas(
shares + contract.totalShares[answerId]
)} shares`}
/>
</Row>
<div>
{formatMoney(currentPayout)}
&nbsp; <span>(+{currentReturnPercent})</span>
</div>
<Spacer h={6} />
{user ? (
<button
className={clsx(
'btn',
betDisabled ? 'btn-disabled' : 'btn-primary',
isSubmitting ? 'loading' : ''
)}
onClick={betDisabled ? undefined : submitBet}
>
{isSubmitting ? 'Submitting...' : 'Submit trade'}
</button>
) : (
<button
className="btn mt-4 whitespace-nowrap border-none bg-gradient-to-r from-teal-500 to-green-500 px-10 text-lg font-medium normal-case hover:from-teal-600 hover:to-green-600"
onClick={firebaseLogin}
>
Sign in to trade!
</button>
)}
{wasSubmitted && <div className="mt-4">Trade submitted!</div>}
</Col>
</Col> </Col>
) )
} }