-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbid.jsx
327 lines (287 loc) · 12.9 KB
/
bid.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
const {useState, useEffect, useCallback, useMemo} = React;
const extractBet = betString => {
const extract = /^(.*?),? *((?:[0-9]{1,2} *bid *(?:(?=[^0-9])|$)|at *[0-9]{1,2} *|bid *[0-9]{1,2} *){1,2})(?:that *)?(.*)$/;
let bid = null;
let ask = null;
let proposition = null;
const result = betString.match(extract);
if (result !== null) {
const extract_2 = /(?:([0-9]{1,2}) *bid *(?:(?=[^0-9])|$)|at *([0-9]{1,2}) *|bid *([0-9]{1,2}) *)/g;
const bidask = result[2];
while (true) {
const match = extract_2.exec(bidask);
if (!match) {
break;
}
if (match[1] !== undefined) {
bid = parseFloat(match[1])/100.0;
}
if (match[3] !== undefined) {
bid = parseFloat(match[3])/100.0;
}
if (match[2] !== undefined) {
ask = parseFloat(match[2])/100.0;
}
}
if (result[1].trim() && result[3].trim()) {
proposition = `${result[1].trim()} ... ${result[3].trim()}`;
} else {
proposition = `${result[1].trim()}${result[3].trim()}`;
}
}
return {bid, ask, proposition};
}
const OrRow = () => (
<div style={{display: 'flex', flexDirection: 'row', alignItems: 'baseline'}}>
<hr style={{flexGrow: 1}}/>
<span><h3 style={{marginLeft: '20px', marginRight: '20px'}}>OR</h3></span>
<hr style={{flexGrow: 1}}/>
</div>
)
function parseQS(qs) {
const result = {}
Array.from(new URLSearchParams(qs).entries()).forEach(item => {
result[item[0]] = item[1]
})
return result
}
function buildQS(o) {
const queryParams = new URLSearchParams(o).toString()
return queryParams ? `?${queryParams}` : '?'
}
const DECODERS = {
string: s => s,
datetime: s => (s !== '' ? new Date(s) : null),
number: s => Number(s),
stringArray: s => s.split(','),
boolean: s => s === 'true',
json: s => JSON.parse(s),
}
const ENCODERS = {
string: s => s,
datetime: d => (d !== null ? d.toISOString() : ''),
number: n => String(n),
stringArray: a => a.join(','),
boolean: b => String(b),
json: j => JSON.stringify(j),
}
function getQSValue(name) {
return parseQS(window.location.search)[name]
}
function useQueryString({name, type, defaultValue}) {
const decoder = DECODERS[type] || (s => s)
const encoder = ENCODERS[type] || (s => s)
const [value, setValue] = useState(() => {
const existingValue = getQSValue(name)
if (existingValue) {
return decoder(existingValue)
} else {
return typeof defaultValue === 'function' ? defaultValue() : defaultValue
}
})
useEffect(() => {
const qsData = parseQS(window.location.search)
if (value === null) {
delete qsData[name]
} else if (value !== undefined && value !== '') {
qsData[name] = encoder(value)
}
window.history.pushState('', '', buildQS(qsData))
}, [name, value, encoder, type])
useEffect(() => {
function setValueFromQS() {
const qsValue = getQSValue(name)
if (qsValue !== undefined && qsValue !== '') {
setValue(decoder(qsValue))
}
}
window.addEventListener('popstate', setValueFromQS)
return () => {
window.removeEventListener('popstate', setValueFromQS)
}
}, [setValue, decoder, name])
return [value, setValue]
}
const EXAMPLES = [
{value: "The sun will come up tomorrow, 10 bid"},
{value: "This coin toss will come up heads, 50 bid at 50"},
{value: "Karen will work past 10pm today, 70 bid at 90"},
{value: "Your desk is going to collapse, at 10"},
{value: "This sale will go through without and yet we won't hear back from them in the next week, 30 bid at 50"},
]
const Weak = ({children}) => <span style={{color: '#aaaaaa'}} children={children}/>
// this function via https://stackoverflow.com/a/37311182/1102705
function copyTextToClipboard(text) {
const textArea = document.createElement("textarea");
//
// *** This styling is an extra step which is likely not required. ***
//
// Why is it here? To ensure:
// 1. the element is able to have focus and selection.
// 2. if element was to flash render it has minimal visual impact.
// 3. less flakyness with selection and copying which **might** occur if
// the textarea element is not visible.
//
// The likelihood is the element won't even render, not even a flash,
// so some of these are just precautions. However in IE the element
// is visible whilst the popup box asking the user for permission for
// the web page to copy to the clipboard.
//
// Place in top-left corner of screen regardless of scroll position.
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
// Ensure it has a small width and height. Setting to 1px / 1em
// doesn't work as this gives a negative w/h on some browsers.
textArea.style.width = '2em';
textArea.style.height = '2em';
// We don't need padding, reducing the size if it does flash render.
textArea.style.padding = 0;
// Clean up any borders.
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
// Avoid flash of white box if rendered for any reason.
textArea.style.background = 'transparent';
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
let msg;
try {
var successful = document.execCommand('copy');
msg = successful ? 'success' : 'error';
console.log('Copying text command was ' + msg);
} catch (err) {
msg = "error";
console.log('Oops, unable to copy');
}
document.body.removeChild(textArea);
return msg;
}
const App = () => {
const [show_as_jst, setShowAsJST] = useQueryString({name: "show_as_jst", type: "boolean", defaultValue: localStorage.show_as_jst !== "no"})
const [isCounterer, setIsCounterer] = useState(localStorage.isCounterer !== "no")
const [value, setValue] = useQueryString({name: "value", type: "string", defaultValue: ""});
const [currency_prefix, setCurrencyPrefix] = useQueryString({name: "currency_prefix", type: "string", defaultValue: ""});
const [currency_postfix, setCurrencyPostfix] = useQueryString({name: "currency_postfix", type: "string", defaultValue: " points"});
const [amount, setAmount] = useState(10);
const [counterer, proposer] = isCounterer ? ["you", "they"] : ["they", "you"];
const [copyResult, setCopyResult] = useState("");
localStorage.show_as_jst = show_as_jst ? "yes" : "no"
localStorage.isCounterer = isCounterer ? "yes" : "no"
const {bid, ask, proposition} = useMemo(() => {
return extractBet(value)
}, [value])
const update = useCallback(({target: {value}}) => {
setValue(value);
})
const formatCurrency = x => {
if (x === undefined || x === null) {
return null;
}
x = parseFloat(x);
return `${currency_prefix || ""}${x.toFixed(2)}${currency_postfix || ""}`;
}
const percent = x => {
if (x === undefined || x === null) {
return null;
}
x = parseFloat(x);
return (x * 100).toFixed(0);
}
const copyLink = useCallback(() => {
const result = copyTextToClipboard(location.href);
setCopyResult(result);
setTimeout(() => setCopyResult(""), 4000);
})
return <div>
<h1> JST-style betting calculator </h1>
<div>
Enter {proposer === "you" ? "your" : "their"} proposition and bid/ask, in the form "the sky is blue, 98 bid at 99". Examples:
<ul>
{EXAMPLES.map(ex => <li>
<a href={"bid.html" + buildQS(ex)}>{ex.value}</a>
</li>)}
</ul>
</div>
<h3><form><label>
<input
name="countering"
type="checkbox"
checked={isCounterer}
onChange={event => setIsCounterer(event.target.checked)} />
{" "}I'm the person countering the bet (as opposed to the person offering it)
</label></form></h3>
<hr/>
<div className="mui-textfield mui-textfield--float-label">
<textarea value={value} onChange={update} />
<label>{proposer === "you" ? "your" : "their"} message, in JST format, proposing the bet (out of {formatCurrency(amount)})</label>
</div>
<div>
<a href="#" onClick={copyLink}>Copy link to this bet summary</a> {copyResult}
</div>
{proposition && <div>
<ul className="mui-tabs__bar">
<li className={ show_as_jst ? "mui--is-active" : ""}><a onClick={() => setShowAsJST(true)}>Bid style</a></li>
<li className={!show_as_jst ? "mui--is-active" : ""}><a onClick={() => setShowAsJST(false)}>Betting style</a></li>
</ul>
<div className="mui-panel">
<div className={ show_as_jst ? "mui-tabs__pane mui--is-active" : "mui-tabs__pane"}>
<h3> {proposer === "you" ? "You're making" : "You're trading on"} a proposal worth {formatCurrency(amount)} if "{proposition}" resolves true,</h3>
<span>and according to the bet{ask !== null && bid !== null ? "s" : ""} {proposer}'re proposing,</span>
<h4>
{bid !== null && <span>{percent(bid)}% <Weak>({formatCurrency(amount*bid)}) is the lower bound on</Weak></span>} {proposer === "you" ? "your" : "their"} estimate of its probability{ask !== null && <span><Weak>{bid !== null && ", "} which has a higher bound of </Weak> {percent(ask)}% <Weak>({formatCurrency(amount*ask)})</Weak></span>}.
</h4>
{bid !== null && <p>
<hr/>
If {counterer} believe the true probability is less than {percent(bid)}, then {proposer}'re buying this proposition for too much, and {counterer} should take {proposer === "you" ? "your" : "their"} bet.
<h3> {counterer} can accept {proposer === "you" ? "your" : "their"} bid by saying "sold". </h3>
Once the proposition resolves, {proposer}'ll owe {counterer} <strong>{formatCurrency(amount*bid)} regardless</strong> for buying the proposition, but if the proposition was true, {counterer}'ll owe them {formatCurrency(amount)} (which adds up to <strong>{formatCurrency(amount*(1-bid))}</strong>).
</p>}
{ask !== null && <p>
<hr/>
If {counterer} believe the true probability is greater than {percent(ask)}, then {proposer}'re selling this proposition for too little, and {counterer} should take {proposer === "you" ? "your" : "their"} bet.
<h3> {counterer} can accept {proposer === "you" ? "your" : "their"} ask bet by saying "taken". </h3>
Once the proposition resolves, {counterer}'ll owe them <strong>{formatCurrency(amount*ask)} regardless</strong> for buying the proposition, but if the proposition was true, {proposer}'ll owe {counterer} {formatCurrency(amount)} back, (which adds up to <strong>{formatCurrency(amount*(1-ask))}</strong>).
</p>}
</div>
<div className={!show_as_jst ? "mui-tabs__pane mui--is-active" : "mui-tabs__pane"}>
<h3> {proposer === "you" ? "You're offering" : "You're considering"} {ask !== null && bid !== null ? "two bets" : "a bet"} worth {formatCurrency(amount)} if "{proposition}" resolves true,</h3>
<span>and according to the bet{ask !== null && bid !== null ? "s" : ""} {proposer}'re proposing,</span>
<h4>
{bid !== null && <span>{percent(bid)}% <Weak>({formatCurrency(amount*bid)}) is the lower bound on</Weak></span>} {proposer === "you" ? "your" : "their"} estimate of its probability{ask !== null && <span><Weak>{bid !== null && ", "} which has a higher bound of </Weak> {percent(ask)}% <Weak>({formatCurrency(amount*ask)})</Weak></span>}.
</h4>
{bid !== null && <div><p>
<hr/>
<h3> {proposer}'ll take the yes side of the bet at {percent(bid)}% YES to {percent(1-bid)}% NO odds: </h3>
<h4> {proposer === "you" ? "your" : "their"} {formatCurrency(amount*bid)} </h4>
that the claim <strong>"{proposition}"</strong> is true or resolves to being true
<h4> to {counterer === "you" ? "your" : "their"} {formatCurrency(amount*(1-bid))}</h4>
that it's false or resolves to being false.
</p><p>
{counterer} can accept this bet by saying, for example, "my {formatCurrency(amount*(1-bid))} no to
your {formatCurrency(amount*bid)} yes, we're on". It's probably faster to say "sold" - see the other tab.
</p>
</div>}
{(ask !== null && bid !== null && <OrRow/>)}
{ask !== null && <div><p>
<h3> {proposer}'ll take the no side of the bet at {percent(ask)}% YES to {percent(1-ask)}% NO odds: </h3>
<h4> Your {formatCurrency(amount*ask)} </h4>
that the claim <strong>"{proposition}"</strong> is true or resolves to being true
<h4> to their {formatCurrency(amount*(1-ask))}</h4>
that it's false or resolves to being false.
</p>
<p>
{counterer} can accept {proposer === "you" ? "your" : "their"} bet by saying, for example, "my {formatCurrency(amount*ask)} yes to
your {formatCurrency(amount*(1-ask))} no, we're on". It's probably faster to say "taken" - see the other tab.
</p></div>}
</div>
</div>
</div>
}
</div>;
}
ReactDOM.render(
<App/>,
document.getElementById('container')
);