@continuumdao/quantlib 0.0.0-stage → 0.1.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/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,52 @@
1
+ /*
2
+ * Fair value of one Rysk listed strike against an RFQ premium.
3
+ * Rysk inventory has no implied vol. A Derive Heston fit is used when the caller passes one.
4
+ */
5
+
6
+ import { blackScholesMerton, dividendForForward } from './black.js'
7
+ import { hestonPrice } from './heston.js'
8
+
9
+ function contractType(input) {
10
+ if (input.isPut === true || input.type === 'put' || input.type === 'P') return 'put'
11
+ return 'call'
12
+ }
13
+
14
+ /**
15
+ * side sell is the node taker default (isTakerBuy false): take when the quote pays at least the model.
16
+ * side buy takes when the quote costs at most the model.
17
+ */
18
+ export function ryskFairValue(input) {
19
+ const strike = Number(input.strike)
20
+ const spot = Number(input.spot ?? input.index)
21
+ const time = Number(input.time)
22
+ const rate = input.rate == null ? 0 : Number(input.rate)
23
+ const forward = input.forward == null ? spot : Number(input.forward)
24
+ const type = contractType(input)
25
+ const trade = input.side === 'buy' ? 'buy' : 'sell'
26
+ if (!(strike > 0) || !(spot > 0) || !(time > 0) || !(forward > 0)) {
27
+ return { decision: 'skip', reason: 'missing contract', model: null, quote: null, side: trade }
28
+ }
29
+ const dividend = input.dividend == null ? dividendForForward(spot, forward, time, rate) : Number(input.dividend)
30
+ let model = null
31
+ if (input.heston) {
32
+ model = hestonPrice({
33
+ type,
34
+ spot,
35
+ strike,
36
+ time,
37
+ rate,
38
+ dividend,
39
+ ...input.heston,
40
+ }, input.points ?? 400).price
41
+ } else if (Number(input.vol) > 0) {
42
+ model = blackScholesMerton({ type, spot, strike, vol: Number(input.vol), time, rate, dividend }).price
43
+ } else {
44
+ return { decision: 'skip', reason: 'no vol', model: null, quote: null, side: trade }
45
+ }
46
+ const quote = input.quotePrice == null ? null : Number(input.quotePrice)
47
+ if (quote == null || !Number.isFinite(quote)) {
48
+ return { decision: 'skip', reason: 'no quote', model, quote: null, side: trade }
49
+ }
50
+ const favorable = trade === 'buy' ? quote <= model : quote >= model
51
+ return { decision: favorable ? 'take' : 'pass', reason: null, model, quote, side: trade }
52
+ }
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: null,
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
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.