@continuumdao/quantlib 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +242 -0
- package/baroneAdesiWhaley.js +136 -0
- package/binomial.js +158 -0
- package/black.js +174 -0
- package/decide.js +379 -0
- package/derive.js +243 -0
- package/heston.js +330 -0
- package/index.js +31 -0
- package/jsonlStore.js +42 -0
- package/normal.js +19 -0
- package/optionsDb.js +69 -0
- package/package.json +26 -4
- package/replay.js +91 -0
- package/rysk.js +61 -0
- package/smile.js +169 -0
- package/spreads.js +90 -0
- package/store.js +94 -0
- package/svi.js +344 -0
- package/README.md +0 -3
package/optionsDb.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Read-only view of the options snapshots written by options-data-storage.
|
|
3
|
+
* The file is user_folder/data/databases/options.sqlite. This module does not create it.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { existsSync } from 'node:fs'
|
|
7
|
+
import { DatabaseSync } from 'node:sqlite'
|
|
8
|
+
import { isAbsolute, join, sep } from 'node:path'
|
|
9
|
+
|
|
10
|
+
const FILE_NAME = 'options.sqlite'
|
|
11
|
+
|
|
12
|
+
/** Absolute path of the options database. The file is not created. */
|
|
13
|
+
export function optionsDatabaseFile(userFolder) {
|
|
14
|
+
const root = String(userFolder || '').trim()
|
|
15
|
+
if (!isAbsolute(root)) throw new Error('user folder must be an absolute path')
|
|
16
|
+
const file = join(root, 'data', 'databases', FILE_NAME)
|
|
17
|
+
const prefix = root.endsWith(sep) ? root : root + sep
|
|
18
|
+
if (!file.startsWith(prefix)) throw new Error('database path leaves the user folder')
|
|
19
|
+
return file
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Open the options database for reading.
|
|
24
|
+
* latest returns one snapshot document. list returns venue, underlying, count, and latest time.
|
|
25
|
+
*/
|
|
26
|
+
export function openOptionsDatabase(userFolder) {
|
|
27
|
+
const file = optionsDatabaseFile(userFolder)
|
|
28
|
+
if (!existsSync(file)) throw new Error(`options database is missing at ${file}`)
|
|
29
|
+
const db = new DatabaseSync(file, { readOnly: true })
|
|
30
|
+
const newest = db.prepare(
|
|
31
|
+
`SELECT document FROM option_snapshots
|
|
32
|
+
WHERE venue = ? AND underlying = ?
|
|
33
|
+
ORDER BY ts DESC, id DESC
|
|
34
|
+
LIMIT 1`,
|
|
35
|
+
)
|
|
36
|
+
const asOf = db.prepare(
|
|
37
|
+
`SELECT document FROM option_snapshots
|
|
38
|
+
WHERE venue = ? AND underlying = ? AND ts <= ?
|
|
39
|
+
ORDER BY ts DESC, id DESC
|
|
40
|
+
LIMIT 1`,
|
|
41
|
+
)
|
|
42
|
+
const summary = db.prepare(
|
|
43
|
+
`SELECT venue, underlying, COUNT(*) AS snapshots, MAX(ts) AS latest
|
|
44
|
+
FROM option_snapshots
|
|
45
|
+
GROUP BY venue, underlying
|
|
46
|
+
ORDER BY venue, underlying`,
|
|
47
|
+
)
|
|
48
|
+
return {
|
|
49
|
+
file,
|
|
50
|
+
list() {
|
|
51
|
+
return summary.all().map((row) => ({
|
|
52
|
+
venue: row.venue,
|
|
53
|
+
underlying: row.underlying,
|
|
54
|
+
snapshots: Number(row.snapshots),
|
|
55
|
+
latest: Number(row.latest),
|
|
56
|
+
}))
|
|
57
|
+
},
|
|
58
|
+
latest(venue, underlying, at) {
|
|
59
|
+
const book = String(venue ?? '').trim().toLowerCase()
|
|
60
|
+
const name = String(underlying ?? '').trim().toUpperCase()
|
|
61
|
+
const row = at == null ? newest.get(book, name) : asOf.get(book, name, Number(at))
|
|
62
|
+
if (!row) return null
|
|
63
|
+
return JSON.parse(row.document)
|
|
64
|
+
},
|
|
65
|
+
close() {
|
|
66
|
+
db.close()
|
|
67
|
+
},
|
|
68
|
+
}
|
|
69
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@continuumdao/quantlib",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Option pricing and snapshot replay for Derive and Rysk. Black-76, binomial trees, smile-gated Heston, and raw SVI.",
|
|
5
|
+
"license": "BSD-3-Clause",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=22"
|
|
9
|
+
},
|
|
10
|
+
"exports": {
|
|
11
|
+
".": "./index.js"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"*.js",
|
|
15
|
+
"LICENSE"
|
|
16
|
+
],
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/Selqui/continuumdao-plugins.git",
|
|
20
|
+
"directory": "lib/quantlib"
|
|
21
|
+
},
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public"
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"test": "node --test test/*.test.js"
|
|
27
|
+
}
|
|
28
|
+
}
|
package/replay.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Replay stored snapshot documents.
|
|
3
|
+
* Buys fill at the stored ask. Sells fill at the stored bid.
|
|
4
|
+
* A step whose smile is too thin is priced with Black-76 and counted.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { blackScholesMerton, dividendForForward } from './black.js'
|
|
8
|
+
import { fitHeston, hestonPrice } from './heston.js'
|
|
9
|
+
|
|
10
|
+
function findTicker(document, order) {
|
|
11
|
+
const tickers = document.tickers ?? []
|
|
12
|
+
if (order.instrumentName) {
|
|
13
|
+
const named = tickers.find((row) => row.instrumentName === order.instrumentName)
|
|
14
|
+
if (named) return named
|
|
15
|
+
}
|
|
16
|
+
return tickers.find((row) => (
|
|
17
|
+
Number(row.strike) === Number(order.strike)
|
|
18
|
+
&& String(row.type) === String(order.type)
|
|
19
|
+
&& Number(row.expiry) === Number(order.expiry)
|
|
20
|
+
)) ?? null
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function modelFor(ticker, fit, rate, points) {
|
|
24
|
+
if (!(ticker.time > 0) || !(ticker.strike > 0) || !ticker.type) return null
|
|
25
|
+
const spot = Number(ticker.index)
|
|
26
|
+
if (!(spot > 0)) return null
|
|
27
|
+
const forward = ticker.forward ?? spot
|
|
28
|
+
const dividend = dividendForForward(spot, forward, ticker.time, rate)
|
|
29
|
+
const base = { type: ticker.type, spot, strike: ticker.strike, time: ticker.time, rate, dividend }
|
|
30
|
+
if (fit.heston) {
|
|
31
|
+
return hestonPrice({ ...base, ...fit.heston }, points)
|
|
32
|
+
}
|
|
33
|
+
if (!(ticker.iv > 0)) return null
|
|
34
|
+
return blackScholesMerton({ ...base, vol: ticker.iv })
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* strategy receives { document, fit } and returns { orders }.
|
|
39
|
+
* Each order is a signed size. Positive buys, negative sells.
|
|
40
|
+
*/
|
|
41
|
+
export function replaySnapshots(documents, strategy, options = {}) {
|
|
42
|
+
const rate = options.rate ?? 0
|
|
43
|
+
const points = options.points ?? 80
|
|
44
|
+
const ordered = [...(documents ?? [])].sort((a, b) => Number(a.ts) - Number(b.ts))
|
|
45
|
+
const trades = []
|
|
46
|
+
const steps = []
|
|
47
|
+
let skippedHeston = 0
|
|
48
|
+
for (const document of ordered) {
|
|
49
|
+
const fit = fitHeston(document.tickers ?? [], {
|
|
50
|
+
now: document.ts,
|
|
51
|
+
rate,
|
|
52
|
+
points: options.fitPoints ?? points,
|
|
53
|
+
maxIter: options.maxIter ?? 12,
|
|
54
|
+
})
|
|
55
|
+
if (!fit.heston) skippedHeston += 1
|
|
56
|
+
const orders = strategy({ document, fit })?.orders ?? []
|
|
57
|
+
const fills = []
|
|
58
|
+
for (const order of orders) {
|
|
59
|
+
const ticker = findTicker(document, order)
|
|
60
|
+
const size = Number(order.size)
|
|
61
|
+
if (!ticker || !Number.isFinite(size) || size === 0) continue
|
|
62
|
+
const price = size > 0 ? Number(ticker.ask) : Number(ticker.bid)
|
|
63
|
+
if (!Number.isFinite(price)) continue
|
|
64
|
+
const model = modelFor(ticker, fit, rate, points)
|
|
65
|
+
fills.push({
|
|
66
|
+
ts: document.ts,
|
|
67
|
+
instrumentName: ticker.instrumentName ?? null,
|
|
68
|
+
size,
|
|
69
|
+
price,
|
|
70
|
+
premium: -size * price,
|
|
71
|
+
model,
|
|
72
|
+
venueGreeks: {
|
|
73
|
+
delta: ticker.delta ?? null,
|
|
74
|
+
gamma: ticker.gamma ?? null,
|
|
75
|
+
theta: ticker.theta ?? null,
|
|
76
|
+
vega: ticker.vega ?? null,
|
|
77
|
+
rho: ticker.rho ?? null,
|
|
78
|
+
},
|
|
79
|
+
})
|
|
80
|
+
}
|
|
81
|
+
trades.push(...fills)
|
|
82
|
+
steps.push({
|
|
83
|
+
ts: document.ts,
|
|
84
|
+
engine: fit.engine,
|
|
85
|
+
singleExpiry: fit.singleExpiry,
|
|
86
|
+
reason: fit.reason,
|
|
87
|
+
fills,
|
|
88
|
+
})
|
|
89
|
+
}
|
|
90
|
+
return { trades, steps, skippedHeston, stepCount: steps.length }
|
|
91
|
+
}
|
package/rysk.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Fair value of one Rysk listed strike against an RFQ premium.
|
|
3
|
+
* Rysk inventory has no implied vol. Pass a Heston fit, an SVI fit, or a vol.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { black76, blackScholesMerton, dividendForForward } from './black.js'
|
|
7
|
+
import { hestonPrice } from './heston.js'
|
|
8
|
+
import { sviVolatility } from './svi.js'
|
|
9
|
+
|
|
10
|
+
function contractType(input) {
|
|
11
|
+
if (input.isPut === true || input.type === 'put' || input.type === 'P') return 'put'
|
|
12
|
+
return 'call'
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* side sell is the node taker default (isTakerBuy false): take when the quote pays at least the model.
|
|
17
|
+
* side buy takes when the quote costs at most the model.
|
|
18
|
+
*/
|
|
19
|
+
export function ryskFairValue(input) {
|
|
20
|
+
const strike = Number(input.strike)
|
|
21
|
+
const spot = Number(input.spot ?? input.index)
|
|
22
|
+
const time = Number(input.time)
|
|
23
|
+
const rate = input.rate == null ? 0 : Number(input.rate)
|
|
24
|
+
const forward = input.forward == null ? spot : Number(input.forward)
|
|
25
|
+
const type = contractType(input)
|
|
26
|
+
const trade = input.side === 'buy' ? 'buy' : 'sell'
|
|
27
|
+
if (!(strike > 0) || !(spot > 0) || !(time > 0) || !(forward > 0)) {
|
|
28
|
+
return { decision: 'skip', reason: 'missing contract', model: null, quote: null, side: trade }
|
|
29
|
+
}
|
|
30
|
+
const dividend = input.dividend == null ? dividendForForward(spot, forward, time, rate) : Number(input.dividend)
|
|
31
|
+
let model = null
|
|
32
|
+
if (input.heston) {
|
|
33
|
+
model = hestonPrice({
|
|
34
|
+
type,
|
|
35
|
+
spot,
|
|
36
|
+
strike,
|
|
37
|
+
time,
|
|
38
|
+
rate,
|
|
39
|
+
dividend,
|
|
40
|
+
...input.heston,
|
|
41
|
+
}, input.points ?? 400).price
|
|
42
|
+
} else if (input.svi) {
|
|
43
|
+
const vol = sviVolatility({
|
|
44
|
+
strike,
|
|
45
|
+
forward: input.svi.forward ?? forward,
|
|
46
|
+
time: input.svi.time ?? time,
|
|
47
|
+
...input.svi,
|
|
48
|
+
})
|
|
49
|
+
model = black76({ type, strike, forward, vol, time, rate }).price
|
|
50
|
+
} else if (Number(input.vol) > 0) {
|
|
51
|
+
model = blackScholesMerton({ type, spot, strike, vol: Number(input.vol), time, rate, dividend }).price
|
|
52
|
+
} else {
|
|
53
|
+
return { decision: 'skip', reason: 'no vol', model: null, quote: null, side: trade }
|
|
54
|
+
}
|
|
55
|
+
const quote = input.quotePrice == null ? null : Number(input.quotePrice)
|
|
56
|
+
if (quote == null || !Number.isFinite(quote)) {
|
|
57
|
+
return { decision: 'skip', reason: 'no quote', model, quote: null, side: trade }
|
|
58
|
+
}
|
|
59
|
+
const favorable = trade === 'buy' ? quote <= model : quote >= model
|
|
60
|
+
return { decision: favorable ? 'take' : 'pass', reason: null, model, quote, side: trade }
|
|
61
|
+
}
|
package/smile.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Smile and smirk from a chain of implied vols.
|
|
3
|
+
* A weight of open interest or volume needs those fields on the rows.
|
|
4
|
+
* SVI is fit on an expiry with at least six strikes. A thinner slice keeps the slope.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { fitSvi, sviVolatility } from './svi.js'
|
|
8
|
+
|
|
9
|
+
function finite(value) {
|
|
10
|
+
const n = Number(value)
|
|
11
|
+
return Number.isFinite(n) ? n : null
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function weightOf(row, weight) {
|
|
15
|
+
if (weight === 'openInterest') return finite(row.openInterest)
|
|
16
|
+
if (weight === 'volume') return finite(row.volume)
|
|
17
|
+
return 1
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function liquidityPresent(rows) {
|
|
21
|
+
return rows.some((row) => finite(row.volume) != null || finite(row.openInterest) != null)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function slopeOf(points, weightName) {
|
|
25
|
+
let total = 0
|
|
26
|
+
let xBar = 0
|
|
27
|
+
let yBar = 0
|
|
28
|
+
const used = []
|
|
29
|
+
for (const point of points) {
|
|
30
|
+
const x = finite(point.logMoneyness)
|
|
31
|
+
const y = finite(point.iv)
|
|
32
|
+
const w = weightName === 'none' ? 1 : weightOf(point, weightName)
|
|
33
|
+
if (x == null || y == null || !(w > 0)) continue
|
|
34
|
+
used.push({ x, y, w })
|
|
35
|
+
total += w
|
|
36
|
+
xBar += w * x
|
|
37
|
+
yBar += w * y
|
|
38
|
+
}
|
|
39
|
+
if (!(total > 0) || used.length < 2) return { slope: null, totalWeight: total }
|
|
40
|
+
xBar /= total
|
|
41
|
+
yBar /= total
|
|
42
|
+
let num = 0
|
|
43
|
+
let den = 0
|
|
44
|
+
for (const point of used) {
|
|
45
|
+
const dx = point.x - xBar
|
|
46
|
+
num += point.w * dx * (point.y - yBar)
|
|
47
|
+
den += point.w * dx * dx
|
|
48
|
+
}
|
|
49
|
+
return { slope: den > 0 ? num / den : null, totalWeight: total }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function nearest(points, type, target) {
|
|
53
|
+
let best = null
|
|
54
|
+
for (const point of points) {
|
|
55
|
+
if (point.type !== type || finite(point.delta) == null || finite(point.iv) == null) continue
|
|
56
|
+
const distance = Math.abs(point.delta - target)
|
|
57
|
+
if (!best || distance < best.distance) best = { distance, iv: point.iv }
|
|
58
|
+
}
|
|
59
|
+
if (!best || best.distance > 0.1) return null
|
|
60
|
+
return best.iv
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function preparedSvi(sviByExpiry, key) {
|
|
64
|
+
if (!sviByExpiry) return null
|
|
65
|
+
if (sviByExpiry.has(key)) return sviByExpiry.get(key)
|
|
66
|
+
const text = key == null || key === 'none' ? 'none' : String(key)
|
|
67
|
+
if (sviByExpiry.has(text)) return sviByExpiry.get(text)
|
|
68
|
+
return { svi: null, reason: 'thin smile' }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function pointFrom(row) {
|
|
72
|
+
const strike = finite(row.strike)
|
|
73
|
+
const ref = finite(row.forward) ?? finite(row.index) ?? finite(row.spot)
|
|
74
|
+
const iv = finite(row.iv)
|
|
75
|
+
const logMoneyness = strike > 0 && ref > 0 ? Math.log(strike / ref) : null
|
|
76
|
+
return {
|
|
77
|
+
instrumentName: row.instrumentName ?? null,
|
|
78
|
+
type: row.type ?? null,
|
|
79
|
+
strike,
|
|
80
|
+
expiry: finite(row.expiry),
|
|
81
|
+
moneyness: strike > 0 && ref > 0 ? strike / ref : null,
|
|
82
|
+
logMoneyness,
|
|
83
|
+
iv,
|
|
84
|
+
ivVenue: finite(row.ivVenue),
|
|
85
|
+
ivMark: finite(row.ivMark),
|
|
86
|
+
delta: finite(row.delta),
|
|
87
|
+
volume: finite(row.volume),
|
|
88
|
+
openInterest: finite(row.openInterest),
|
|
89
|
+
forward: finite(row.forward) ?? ref,
|
|
90
|
+
time: finite(row.time),
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* One smile per expiry. weight is none, openInterest, or volume.
|
|
96
|
+
* minOpenInterest and minVolume drop thin strikes when liquidity fields exist.
|
|
97
|
+
*/
|
|
98
|
+
export function optionSmile(rows, options = {}) {
|
|
99
|
+
const weight = options.weight ?? 'none'
|
|
100
|
+
if (weight !== 'none' && weight !== 'openInterest' && weight !== 'volume') {
|
|
101
|
+
throw new Error('weight must be none, openInterest, or volume.')
|
|
102
|
+
}
|
|
103
|
+
const minOpenInterest = options.minOpenInterest == null ? null : Number(options.minOpenInterest)
|
|
104
|
+
const minVolume = options.minVolume == null ? null : Number(options.minVolume)
|
|
105
|
+
const source = rows ?? []
|
|
106
|
+
const hasLiquidity = liquidityPresent(source)
|
|
107
|
+
const floorAsked = minOpenInterest != null || minVolume != null
|
|
108
|
+
const weightAsked = weight !== 'none'
|
|
109
|
+
let reason = null
|
|
110
|
+
if ((weightAsked || floorAsked) && !hasLiquidity) {
|
|
111
|
+
reason = 'no liquidity fields'
|
|
112
|
+
}
|
|
113
|
+
let skipped = 0
|
|
114
|
+
const kept = []
|
|
115
|
+
for (const row of source) {
|
|
116
|
+
const thin = hasLiquidity && (
|
|
117
|
+
(minOpenInterest != null && !(finite(row.openInterest) >= minOpenInterest))
|
|
118
|
+
|| (minVolume != null && !(finite(row.volume) >= minVolume))
|
|
119
|
+
)
|
|
120
|
+
if (thin) {
|
|
121
|
+
skipped += 1
|
|
122
|
+
continue
|
|
123
|
+
}
|
|
124
|
+
const point = pointFrom(row)
|
|
125
|
+
if (point.iv == null || point.strike == null) continue
|
|
126
|
+
kept.push(point)
|
|
127
|
+
}
|
|
128
|
+
const byExpiry = new Map()
|
|
129
|
+
for (const point of kept) {
|
|
130
|
+
const key = point.expiry ?? 'none'
|
|
131
|
+
const list = byExpiry.get(key) ?? []
|
|
132
|
+
list.push(point)
|
|
133
|
+
byExpiry.set(key, list)
|
|
134
|
+
}
|
|
135
|
+
const expiries = [...byExpiry.entries()].map(([key, points]) => {
|
|
136
|
+
points.sort((a, b) => a.strike - b.strike || String(a.type).localeCompare(String(b.type)))
|
|
137
|
+
const fit = slopeOf(points, reason ? 'none' : weight)
|
|
138
|
+
const callIv = nearest(points, 'call', 0.25)
|
|
139
|
+
const putIv = nearest(points, 'put', -0.25)
|
|
140
|
+
const sviFit = preparedSvi(options.sviByExpiry, key) ?? fitSvi(points, { now: options.now ?? null })
|
|
141
|
+
const expiry = {
|
|
142
|
+
expiry: key === 'none' ? null : Number(key),
|
|
143
|
+
points,
|
|
144
|
+
slope: fit.slope,
|
|
145
|
+
totalWeight: fit.totalWeight,
|
|
146
|
+
riskReversal25: callIv != null && putIv != null ? callIv - putIv : null,
|
|
147
|
+
svi: sviFit.svi,
|
|
148
|
+
sviReason: sviFit.reason,
|
|
149
|
+
}
|
|
150
|
+
if (options.quoteStrikes) {
|
|
151
|
+
expiry.quoted = options.quoteStrikes.map((strike) => ({
|
|
152
|
+
strike: Number(strike),
|
|
153
|
+
iv: sviFit.svi && Number(strike) > 0
|
|
154
|
+
? sviVolatility({ strike, forward: sviFit.svi.forward, time: sviFit.svi.time, ...sviFit.svi })
|
|
155
|
+
: null,
|
|
156
|
+
}))
|
|
157
|
+
}
|
|
158
|
+
return expiry
|
|
159
|
+
})
|
|
160
|
+
expiries.sort((a, b) => (a.expiry ?? 0) - (b.expiry ?? 0))
|
|
161
|
+
return {
|
|
162
|
+
weight: reason ? 'none' : weight,
|
|
163
|
+
requestedWeight: weight,
|
|
164
|
+
applied: reason == null,
|
|
165
|
+
reason,
|
|
166
|
+
skipped,
|
|
167
|
+
expiries,
|
|
168
|
+
}
|
|
169
|
+
}
|
package/spreads.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Multi-leg spreads from one snapshot.
|
|
3
|
+
* A long leg is bought at the ask and sold at the bid.
|
|
4
|
+
* A short leg is sold at the bid and bought back at the ask.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
function sameLeg(row, leg) {
|
|
8
|
+
if (leg.instrumentName && row.instrumentName === leg.instrumentName) return true
|
|
9
|
+
const type = String(leg.type ?? '').toLowerCase()
|
|
10
|
+
const rowType = String(row.type ?? '').toLowerCase()
|
|
11
|
+
const typeOk = type === rowType || (type === 'c' && rowType === 'call') || (type === 'p' && rowType === 'put')
|
|
12
|
+
|| (type === 'call' && rowType === 'call') || (type === 'put' && rowType === 'put')
|
|
13
|
+
return typeOk && Number(row.strike) === Number(leg.strike) && Number(row.expiry) === Number(leg.expiry)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function label(leg) {
|
|
17
|
+
return leg.instrumentName ?? `${leg.type ?? ''} ${leg.strike ?? ''} ${leg.expiry ?? ''}`.trim()
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function addGreek(sum, size, value) {
|
|
21
|
+
const n = Number(value)
|
|
22
|
+
if (!Number.isFinite(n)) return sum
|
|
23
|
+
return sum + size * n
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Spread rows for the definitions the caller passes. Missing legs are named and skipped. */
|
|
27
|
+
export function buildSpreads(snapshot, definitions) {
|
|
28
|
+
const tickers = snapshot?.tickers ?? []
|
|
29
|
+
return (definitions ?? []).map((definition) => {
|
|
30
|
+
const missing = []
|
|
31
|
+
const legs = []
|
|
32
|
+
let netMark = 0
|
|
33
|
+
let netBid = 0
|
|
34
|
+
let netAsk = 0
|
|
35
|
+
let netDelta = 0
|
|
36
|
+
let netGamma = 0
|
|
37
|
+
let netTheta = 0
|
|
38
|
+
let netVega = 0
|
|
39
|
+
let priced = true
|
|
40
|
+
for (const leg of definition.legs ?? []) {
|
|
41
|
+
const size = Number(leg.size)
|
|
42
|
+
const match = tickers.find((row) => sameLeg(row, leg))
|
|
43
|
+
if (!match || !Number.isFinite(size) || size === 0) {
|
|
44
|
+
missing.push(label(leg))
|
|
45
|
+
priced = false
|
|
46
|
+
continue
|
|
47
|
+
}
|
|
48
|
+
const mark = Number(match.mark)
|
|
49
|
+
const bid = Number(match.bid)
|
|
50
|
+
const ask = Number(match.ask)
|
|
51
|
+
if (!Number.isFinite(mark) || !Number.isFinite(bid) || !Number.isFinite(ask)) {
|
|
52
|
+
missing.push(label(leg))
|
|
53
|
+
priced = false
|
|
54
|
+
continue
|
|
55
|
+
}
|
|
56
|
+
netMark += size * mark
|
|
57
|
+
if (size > 0) {
|
|
58
|
+
netAsk += size * ask
|
|
59
|
+
netBid += size * bid
|
|
60
|
+
} else {
|
|
61
|
+
netAsk += size * bid
|
|
62
|
+
netBid += size * ask
|
|
63
|
+
}
|
|
64
|
+
netDelta = addGreek(netDelta, size, match.delta)
|
|
65
|
+
netGamma = addGreek(netGamma, size, match.gamma)
|
|
66
|
+
netTheta = addGreek(netTheta, size, match.theta)
|
|
67
|
+
netVega = addGreek(netVega, size, match.vega)
|
|
68
|
+
legs.push({
|
|
69
|
+
instrumentName: match.instrumentName ?? null,
|
|
70
|
+
strike: match.strike,
|
|
71
|
+
expiry: match.expiry,
|
|
72
|
+
type: match.type,
|
|
73
|
+
size,
|
|
74
|
+
})
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
name: definition.name ?? null,
|
|
78
|
+
legs,
|
|
79
|
+
missing,
|
|
80
|
+
netMark: priced ? netMark : null,
|
|
81
|
+
netBid: priced ? netBid : null,
|
|
82
|
+
netAsk: priced ? netAsk : null,
|
|
83
|
+
netBidAskWidth: priced ? netAsk - netBid : null,
|
|
84
|
+
netDelta,
|
|
85
|
+
netGamma,
|
|
86
|
+
netTheta,
|
|
87
|
+
netVega,
|
|
88
|
+
}
|
|
89
|
+
})
|
|
90
|
+
}
|
package/store.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Snapshot documents and the append/load store contract.
|
|
3
|
+
* A later Mongo store implements the same two methods.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { readDeriveTicker } from './derive.js'
|
|
7
|
+
|
|
8
|
+
export function selectDocuments(documents, query = {}) {
|
|
9
|
+
const venue = query.venue == null ? null : String(query.venue)
|
|
10
|
+
const underlying = query.underlying == null ? null : String(query.underlying).toUpperCase()
|
|
11
|
+
return (documents ?? [])
|
|
12
|
+
.filter((doc) => {
|
|
13
|
+
if (venue && doc.venue !== venue) return false
|
|
14
|
+
if (underlying && String(doc.underlying ?? '').toUpperCase() !== underlying) return false
|
|
15
|
+
if (query.from != null && Number(doc.ts) < Number(query.from)) return false
|
|
16
|
+
if (query.to != null && Number(doc.ts) > Number(query.to)) return false
|
|
17
|
+
return true
|
|
18
|
+
})
|
|
19
|
+
.sort((a, b) => Number(a.ts) - Number(b.ts))
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** In-memory store. Tests use it as the stand-in for a later Mongo collection. */
|
|
23
|
+
export function memoryStore(seed = []) {
|
|
24
|
+
const docs = seed.map((doc) => structuredClone(doc))
|
|
25
|
+
return {
|
|
26
|
+
async append(document) {
|
|
27
|
+
docs.push(structuredClone(document))
|
|
28
|
+
},
|
|
29
|
+
async load(query) {
|
|
30
|
+
return selectDocuments(docs, query)
|
|
31
|
+
},
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function ryskTicker(quote, spot, ts, underlying) {
|
|
36
|
+
const isPut = quote.isPut === true || quote.type === 'put' || quote.type === 'P'
|
|
37
|
+
return {
|
|
38
|
+
ts,
|
|
39
|
+
venue: 'rysk',
|
|
40
|
+
underlying,
|
|
41
|
+
instrumentName: quote.instrumentName ?? null,
|
|
42
|
+
type: isPut ? 'put' : 'call',
|
|
43
|
+
strike: quote.strike == null ? null : Number(quote.strike),
|
|
44
|
+
expiry: quote.expiry == null ? null : Number(quote.expiry),
|
|
45
|
+
time: quote.time == null ? null : Number(quote.time),
|
|
46
|
+
index: spot,
|
|
47
|
+
forward: quote.forward == null ? null : Number(quote.forward),
|
|
48
|
+
bid: null,
|
|
49
|
+
ask: null,
|
|
50
|
+
mark: quote.price == null ? null : Number(quote.price),
|
|
51
|
+
iv: null,
|
|
52
|
+
bidIv: null,
|
|
53
|
+
askIv: null,
|
|
54
|
+
delta: quote.delta == null || quote.delta === '' || !Number.isFinite(Number(quote.delta)) ? null : Number(quote.delta),
|
|
55
|
+
gamma: null,
|
|
56
|
+
theta: null,
|
|
57
|
+
vega: null,
|
|
58
|
+
rho: null,
|
|
59
|
+
bidAskWidth: null,
|
|
60
|
+
size: quote.size == null ? null : String(quote.size),
|
|
61
|
+
validUntil: quote.validUntil ?? null,
|
|
62
|
+
collateral: quote.collateral ?? null,
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* One document for a cron run.
|
|
68
|
+
* Derive rows are ticker objects. Rysk uses spot, inventory, and quotes.
|
|
69
|
+
*/
|
|
70
|
+
export function buildSnapshot(input) {
|
|
71
|
+
const ts = input.ts
|
|
72
|
+
const venue = input.venue
|
|
73
|
+
const underlying = input.underlying
|
|
74
|
+
if (venue === 'rysk') {
|
|
75
|
+
const spot = input.spot == null ? null : Number(input.spot)
|
|
76
|
+
const tickers = (input.quotes ?? []).map((quote) => ryskTicker(quote, spot, ts, underlying))
|
|
77
|
+
return {
|
|
78
|
+
ts,
|
|
79
|
+
venue,
|
|
80
|
+
underlying,
|
|
81
|
+
spot,
|
|
82
|
+
inventory: input.inventory ?? null,
|
|
83
|
+
tickers,
|
|
84
|
+
spreads: [],
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const tickers = (input.rows ?? []).map((row) => ({
|
|
88
|
+
ts,
|
|
89
|
+
venue,
|
|
90
|
+
underlying,
|
|
91
|
+
...readDeriveTicker(row, input.now ?? ts),
|
|
92
|
+
}))
|
|
93
|
+
return { ts, venue, underlying, tickers, spreads: [] }
|
|
94
|
+
}
|