mirror of
https://github.com/multipleof4/KalBot.git
synced 2026-03-17 05:51:02 +00:00
405 lines
12 KiB
JavaScript
405 lines
12 KiB
JavaScript
import { getActiveBTCEvents, getEventMarkets, getOrderbook, getMarket } from '../kalshi/rest.js';
|
|
import { KalshiWS } from '../kalshi/websocket.js';
|
|
import { EventEmitter } from 'events';
|
|
|
|
const OPEN_MARKET_STATUSES = new Set(['open', 'active', 'initialized', 'trading']);
|
|
const TRADABLE_MARKET_STATUSES = new Set(['open', 'active', 'trading']);
|
|
|
|
/**
|
|
* Tracks the currently active BTC 15-min market.
|
|
* Auto-rotates when the current market expires.
|
|
* Emits 'update' with full market state on every change.
|
|
*/
|
|
export class MarketTracker extends EventEmitter {
|
|
constructor() {
|
|
super();
|
|
this.ws = new KalshiWS();
|
|
this.currentTicker = null;
|
|
this.currentEvent = null;
|
|
this.marketData = null;
|
|
this.orderbook = { yes: [], no: [] };
|
|
this.rotateInterval = null;
|
|
}
|
|
|
|
async start() {
|
|
console.log('[Tracker] Starting market tracker...');
|
|
|
|
this.ws.connect();
|
|
this.ws.on('orderbook', (msg) => this._onOrderbook(msg));
|
|
this.ws.on('ticker', (msg) => this._onTicker(msg));
|
|
|
|
await this._findAndSubscribe();
|
|
this.rotateInterval = setInterval(() => this._checkRotation(), 30000);
|
|
}
|
|
|
|
stop() {
|
|
clearInterval(this.rotateInterval);
|
|
this.ws.disconnect();
|
|
}
|
|
|
|
getState() {
|
|
if (!this.marketData) return null;
|
|
|
|
const quotes = this._extractMarketQuotes(this.marketData);
|
|
const bestYesBook = this._bestBookPrice(this.orderbook.yes);
|
|
const bestNoBook = this._bestBookPrice(this.orderbook.no);
|
|
|
|
const yesBid = quotes.yesBid ?? bestYesBook;
|
|
const noBid = quotes.noBid ?? bestNoBook;
|
|
const yesAsk = quotes.yesAsk ?? (noBid != null ? 100 - noBid : null);
|
|
const noAsk = quotes.noAsk ?? (yesBid != null ? 100 - yesBid : null);
|
|
|
|
let yesPct = yesAsk ?? yesBid ?? bestYesBook;
|
|
let noPct = noAsk ?? noBid ?? bestNoBook;
|
|
|
|
if (yesPct == null && noPct != null) yesPct = 100 - noPct;
|
|
if (noPct == null && yesPct != null) noPct = 100 - yesPct;
|
|
|
|
if (yesPct == null && noPct == null && quotes.lastPrice != null) {
|
|
yesPct = quotes.lastPrice;
|
|
noPct = 100 - quotes.lastPrice;
|
|
}
|
|
|
|
if (yesPct == null || noPct == null) {
|
|
yesPct = 50;
|
|
noPct = 50;
|
|
}
|
|
|
|
yesPct = this._clampPct(yesPct) ?? 50;
|
|
noPct = this._clampPct(noPct) ?? 50;
|
|
|
|
const yesOdds = yesPct > 0 ? (100 / yesPct).toFixed(2) : '0.00';
|
|
const noOdds = noPct > 0 ? (100 / noPct).toFixed(2) : '0.00';
|
|
|
|
return {
|
|
ticker: this.currentTicker,
|
|
eventTicker: this.currentEvent,
|
|
title: this.marketData.title || 'BTC Up or Down - 15 min',
|
|
subtitle: this.marketData.subtitle || '',
|
|
yesPct,
|
|
noPct,
|
|
yesOdds: parseFloat(yesOdds),
|
|
noOdds: parseFloat(noOdds),
|
|
yesBid: this._clampPct(yesBid),
|
|
yesAsk: this._clampPct(yesAsk),
|
|
noBid: this._clampPct(noBid),
|
|
noAsk: this._clampPct(noAsk),
|
|
volume: this._num(this.marketData.volume) ?? 0,
|
|
volume24h: this._num(this.marketData.volume_24h) ?? 0,
|
|
openInterest: this._num(this.marketData.open_interest) ?? 0,
|
|
lastPrice: this._clampPct(quotes.lastPrice),
|
|
closeTime: this.marketData.close_time || this.marketData.expiration_time,
|
|
status: this.marketData.status,
|
|
result: this.marketData.result,
|
|
timestamp: Date.now()
|
|
};
|
|
}
|
|
|
|
_num(value) {
|
|
if (value == null) return null;
|
|
const n = Number(value);
|
|
return Number.isFinite(n) ? n : null;
|
|
}
|
|
|
|
_clampPct(value) {
|
|
const n = this._num(value);
|
|
if (n == null) return null;
|
|
return Math.max(0, Math.min(100, n));
|
|
}
|
|
|
|
_toTs(value) {
|
|
if (!value) return null;
|
|
const ts = new Date(value).getTime();
|
|
return Number.isFinite(ts) ? ts : null;
|
|
}
|
|
|
|
_extractMarketQuotes(market) {
|
|
const pick = (...keys) => {
|
|
for (const key of keys) {
|
|
const v = this._num(market?.[key]);
|
|
if (v != null) return v;
|
|
}
|
|
return null;
|
|
};
|
|
|
|
return {
|
|
yesBid: pick('yes_bid', 'yesBid'),
|
|
yesAsk: pick('yes_ask', 'yesAsk'),
|
|
noBid: pick('no_bid', 'noBid'),
|
|
noAsk: pick('no_ask', 'noAsk'),
|
|
lastPrice: pick('last_price', 'lastPrice', 'yes_price', 'yesPrice')
|
|
};
|
|
}
|
|
|
|
_normalizeBookSide(levels) {
|
|
if (!Array.isArray(levels)) return [];
|
|
|
|
const out = [];
|
|
|
|
for (const level of levels) {
|
|
let price = null;
|
|
let qty = null;
|
|
|
|
if (Array.isArray(level)) {
|
|
price = level[0];
|
|
qty = level[1];
|
|
} else if (level && typeof level === 'object') {
|
|
price = level.price ?? level[0];
|
|
qty = level.qty ?? level.quantity ?? level.size ?? level.count ?? level[1];
|
|
}
|
|
|
|
const p = this._num(price);
|
|
const q = this._num(qty);
|
|
|
|
if (p == null || q == null || q <= 0) continue;
|
|
out.push([p, q]);
|
|
}
|
|
|
|
return out.sort((a, b) => b[0] - a[0]);
|
|
}
|
|
|
|
_normalizeOrderbook(book) {
|
|
const root = book?.orderbook && typeof book.orderbook === 'object' ? book.orderbook : book;
|
|
return {
|
|
yes: this._normalizeBookSide(root?.yes),
|
|
no: this._normalizeBookSide(root?.no)
|
|
};
|
|
}
|
|
|
|
_bestBookPrice(sideBook) {
|
|
if (!Array.isArray(sideBook) || !sideBook.length) return null;
|
|
return this._num(sideBook[0][0]);
|
|
}
|
|
|
|
_pickBestMarket(markets = []) {
|
|
const now = Date.now();
|
|
|
|
const ranked = markets
|
|
.filter(Boolean)
|
|
.map((market) => {
|
|
const status = String(market?.status || '').toLowerCase();
|
|
const closeTs =
|
|
this._toTs(market?.close_time) ||
|
|
this._toTs(market?.expiration_time) ||
|
|
this._toTs(market?.settlement_time) ||
|
|
null;
|
|
|
|
const tradable = TRADABLE_MARKET_STATUSES.has(status);
|
|
const openLike = OPEN_MARKET_STATUSES.has(status);
|
|
const notClearlyExpired = closeTs == null || closeTs > now - 60_000;
|
|
|
|
return { market, tradable, openLike, notClearlyExpired, closeTs };
|
|
})
|
|
.filter((x) => x.openLike || x.notClearlyExpired);
|
|
|
|
if (!ranked.length) return markets[0] || null;
|
|
|
|
ranked.sort((a, b) => {
|
|
if (a.tradable !== b.tradable) return a.tradable ? -1 : 1;
|
|
if (a.openLike !== b.openLike) return a.openLike ? -1 : 1;
|
|
if (a.notClearlyExpired !== b.notClearlyExpired) return a.notClearlyExpired ? -1 : 1;
|
|
const aTs = a.closeTs ?? Number.MAX_SAFE_INTEGER;
|
|
const bTs = b.closeTs ?? Number.MAX_SAFE_INTEGER;
|
|
return aTs - bTs;
|
|
});
|
|
|
|
return ranked[0].market;
|
|
}
|
|
|
|
async _findAndSubscribe() {
|
|
try {
|
|
const candidates = await getActiveBTCEvents(12);
|
|
|
|
if (!candidates.length) {
|
|
if (!this.currentTicker) this.emit('update', null);
|
|
console.log('[Tracker] No active BTC 15m event found. Retrying in 30s...');
|
|
return;
|
|
}
|
|
|
|
let selectedEvent = null;
|
|
let selectedMarket = null;
|
|
|
|
for (const event of candidates) {
|
|
const eventTicker = event?.event_ticker;
|
|
if (!eventTicker) continue;
|
|
|
|
let markets = Array.isArray(event.markets) ? event.markets : [];
|
|
if (!markets.length) {
|
|
try {
|
|
markets = await getEventMarkets(eventTicker);
|
|
} catch (e) {
|
|
console.error(`[Tracker] Failed loading markets for ${eventTicker}:`, e.message);
|
|
continue;
|
|
}
|
|
}
|
|
|
|
if (!markets.length) continue;
|
|
|
|
const market = this._pickBestMarket(markets);
|
|
if (!market?.ticker) continue;
|
|
|
|
selectedEvent = event;
|
|
selectedMarket = market;
|
|
break;
|
|
}
|
|
|
|
if (!selectedEvent || !selectedMarket) {
|
|
if (!this.currentTicker) this.emit('update', null);
|
|
console.log('[Tracker] No tradable BTC 15m market found yet. Retrying...');
|
|
return;
|
|
}
|
|
|
|
const newTicker = selectedMarket.ticker;
|
|
|
|
if (newTicker === this.currentTicker) {
|
|
this.currentEvent = selectedEvent.event_ticker || this.currentEvent;
|
|
this.marketData = { ...(this.marketData || {}), ...selectedMarket };
|
|
this.emit('update', this.getState());
|
|
return;
|
|
}
|
|
|
|
const oldTicker = this.currentTicker;
|
|
|
|
if (oldTicker) {
|
|
console.log(`[Tracker] Rotating from ${oldTicker} → ${newTicker}`);
|
|
this.ws.unsubscribeTicker(oldTicker);
|
|
}
|
|
|
|
this.currentTicker = newTicker;
|
|
this.currentEvent = selectedEvent.event_ticker;
|
|
this.marketData = selectedMarket;
|
|
this.orderbook = { yes: [], no: [] };
|
|
|
|
try {
|
|
const [freshMarket, ob] = await Promise.all([
|
|
getMarket(newTicker).catch(() => null),
|
|
getOrderbook(newTicker).catch(() => null)
|
|
]);
|
|
|
|
if (freshMarket) this.marketData = { ...selectedMarket, ...freshMarket };
|
|
if (ob) this.orderbook = this._normalizeOrderbook(ob);
|
|
} catch (e) {
|
|
console.error('[Tracker] Initial market bootstrap error:', e.message);
|
|
}
|
|
|
|
this.ws.subscribeTicker(newTicker);
|
|
|
|
console.log(
|
|
`[Tracker] Now tracking: ${newTicker} (${this.marketData?.title || this.marketData?.subtitle || selectedEvent.event_ticker})`
|
|
);
|
|
|
|
this.emit('update', this.getState());
|
|
this.emit('market-rotated', { from: oldTicker, to: newTicker });
|
|
} catch (err) {
|
|
console.error('[Tracker] Discovery error:', err.message);
|
|
}
|
|
}
|
|
|
|
async _checkRotation() {
|
|
if (this.currentTicker) {
|
|
try {
|
|
const fresh = await getMarket(this.currentTicker);
|
|
this.marketData = { ...(this.marketData || {}), ...(fresh || {}) };
|
|
|
|
const state = this.getState();
|
|
this.emit('update', state);
|
|
|
|
const status = String(fresh?.status || '').toLowerCase();
|
|
const settledLike = status === 'closed' || status === 'settled' || status === 'expired' || status === 'finalized';
|
|
|
|
if (settledLike || fresh?.result) {
|
|
console.log(`[Tracker] Market ${this.currentTicker} settled (result: ${fresh.result}). Rotating...`);
|
|
this.emit('settled', { ticker: this.currentTicker, result: fresh.result });
|
|
this.currentTicker = null;
|
|
await this._findAndSubscribe();
|
|
}
|
|
} catch (e) {
|
|
console.error('[Tracker] Refresh error:', e.message);
|
|
}
|
|
} else {
|
|
await this._findAndSubscribe();
|
|
}
|
|
}
|
|
|
|
_onOrderbook(msg) {
|
|
if (msg.market_ticker !== this.currentTicker) return;
|
|
|
|
if (msg.type === 'orderbook_snapshot') {
|
|
this.orderbook = this._normalizeOrderbook(msg);
|
|
} else if (msg.type === 'orderbook_delta') {
|
|
const side = String(msg.side || '').toLowerCase();
|
|
const price = this._num(msg.price);
|
|
const delta = this._num(msg.delta);
|
|
const absoluteQty = this._num(msg.qty ?? msg.quantity ?? msg.size);
|
|
|
|
if ((side === 'yes' || side === 'no') && price != null) {
|
|
const book = this.orderbook[side] || [];
|
|
const map = new Map(book);
|
|
|
|
const current = this._num(map.get(price)) ?? 0;
|
|
const next = delta != null ? current + delta : (absoluteQty ?? current);
|
|
|
|
if (next <= 0) map.delete(price);
|
|
else map.set(price, next);
|
|
|
|
this.orderbook[side] = [...map.entries()].sort((a, b) => b[0] - a[0]);
|
|
} else {
|
|
if (Array.isArray(msg.yes)) this.orderbook.yes = this._applyDelta(this.orderbook.yes, msg.yes);
|
|
if (Array.isArray(msg.no)) this.orderbook.no = this._applyDelta(this.orderbook.no, msg.no);
|
|
}
|
|
}
|
|
|
|
this.emit('update', this.getState());
|
|
}
|
|
|
|
_onTicker(msg) {
|
|
if (msg.market_ticker !== this.currentTicker) return;
|
|
|
|
if (this.marketData) {
|
|
const yesBid = this._num(msg.yes_bid);
|
|
const yesAsk = this._num(msg.yes_ask);
|
|
const noBid = this._num(msg.no_bid);
|
|
const noAsk = this._num(msg.no_ask);
|
|
const lastPrice = this._num(msg.last_price);
|
|
const volume = this._num(msg.volume);
|
|
|
|
Object.assign(this.marketData, {
|
|
yes_bid: yesBid ?? this.marketData.yes_bid,
|
|
yes_ask: yesAsk ?? this.marketData.yes_ask,
|
|
no_bid: noBid ?? this.marketData.no_bid,
|
|
no_ask: noAsk ?? this.marketData.no_ask,
|
|
last_price: lastPrice ?? this.marketData.last_price,
|
|
volume: volume ?? this.marketData.volume
|
|
});
|
|
}
|
|
|
|
this.emit('update', this.getState());
|
|
}
|
|
|
|
_applyDelta(book, deltas) {
|
|
const map = new Map(book || []);
|
|
|
|
for (const delta of Array.isArray(deltas) ? deltas : []) {
|
|
let price = null;
|
|
let qty = null;
|
|
|
|
if (Array.isArray(delta)) {
|
|
price = delta[0];
|
|
qty = delta[1];
|
|
} else if (delta && typeof delta === 'object') {
|
|
price = delta.price ?? delta[0];
|
|
qty = delta.qty ?? delta.quantity ?? delta.size ?? delta[1];
|
|
}
|
|
|
|
const p = this._num(price);
|
|
const q = this._num(qty);
|
|
if (p == null || q == null) continue;
|
|
|
|
if (q <= 0) map.delete(p);
|
|
else map.set(p, q);
|
|
}
|
|
|
|
return [...map.entries()].sort((a, b) => b[0] - a[0]);
|
|
}
|
|
}
|