UNPKG

kalshi-sdk

Version:

A public TypeScript SDK for Kalshi (https://kalshi.com/)

340 lines (332 loc) 11 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { step(generator.next(value)); } catch (e) { reject(e); } }; var rejected = (value) => { try { step(generator.throw(value)); } catch (e) { reject(e); } }; var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); step((generator = generator.apply(__this, __arguments)).next()); }); }; // src/index.ts var index_exports = {}; __export(index_exports, { KalshiClient: () => KalshiClient }); module.exports = __toCommonJS(index_exports); // src/kalshi/kalshiClient.ts var import_axios = __toESM(require("axios"), 1); var import_crypto = __toESM(require("crypto"), 1); var import_fs = __toESM(require("fs"), 1); // src/constants/constants.ts var KALSHI_DEFAULT_URL = "https://api.elections.kalshi.com"; // src/kalshi/marketClient.ts var KalshiMarketsClient = class { constructor(client) { this.client = client; } getEvents(eventsRequest) { return __async(this, null, function* () { return this.client.sendGetRequest( `${this.client.apiUrl}/trade-api/v2/events`, eventsRequest ); }); } getEvent(eventTicker, with_nested_markets) { return __async(this, null, function* () { return this.client.sendGetRequest( `${this.client.apiUrl}/trade-api/v2/events/${eventTicker}`, { with_nested_markets } ); }); } getMarkets(marketsRequest) { return __async(this, null, function* () { return this.client.sendGetRequest( `${this.client.apiUrl}/trade-api/v2/markets`, marketsRequest ); }); } getMarket(marketTicker) { return __async(this, null, function* () { return this.client.sendGetRequest( `${this.client.apiUrl}/trade-api/v2/markets/${marketTicker}` ); }); } getTrades(tradeRequest) { return __async(this, null, function* () { return this.client.sendGetRequest( `${this.client.apiUrl}/trade-api/v2/trades`, tradeRequest ); }); } getMarketOrderBook(marketTicker, depth) { return __async(this, null, function* () { return this.client.sendGetRequest( `${this.client.apiUrl}/trade-api/v2/markets/${marketTicker}/orderbook`, { depth } ); }); } getSeries(seriesTicker) { return __async(this, null, function* () { return this.client.sendGetRequest( `${this.client.apiUrl}/trade-api/v2/series/${seriesTicker}` ); }); } getMarketCandlesticks(ticker, seriesTicker, candleStickRequest) { return __async(this, null, function* () { return this.client.sendGetRequest( `${this.client.apiUrl}/trade-api/v2/series/${seriesTicker}/markets/${ticker}/candlesticks` ); }); } createKalshiOrder(orderRequest) { return __async(this, null, function* () { return this.client.sendWriteRequest( `${this.client.apiUrl}/trade-api/v2/portfolio/orders`, "POST", orderRequest ); }); } cancelKalshiOrder(orderId) { return __async(this, null, function* () { return this.client.sendWriteRequest( `${this.client.apiUrl}/trade-api/v2/portfolio/orders/${orderId}`, "DELETE" ); }); } }; // src/kalshi/exchangeClient.ts var KalshiExchangeClient = class { constructor(client) { this.client = client; } getExchangeAnnouncment() { return __async(this, null, function* () { const response = yield this.client.sendGetRequest( `${this.client.apiUrl}/trade-api/v2/exchange/announcements` ); return response.announcements; }); } getExchangeSchedule() { return __async(this, null, function* () { return this.client.sendGetRequest( `${this.client.apiUrl}/trade-api/v2/exchange/schedule` ); }); } getExchangeStatus() { return __async(this, null, function* () { return this.client.sendGetRequest( `${this.client.apiUrl}/trade-api/v2/xchange/status` ); }); } }; // src/kalshi/collectionsClient.ts var KalshiCollectionsClient = class { constructor(client) { this.client = client; } getMultivariateEventCollections(params) { return __async(this, null, function* () { return this.client.sendGetRequest( `${this.client.apiUrl}/trade-api/v2/multivariate_event_collections/`, params ); }); } getMultivariateEventCollection(collectionTicker) { return __async(this, null, function* () { return this.client.sendGetRequest( `${this.client.apiUrl}/trade-api/v2/multivariate_event_collections/${collectionTicker}` ); }); } createMarketInMultivariateEventCollection(collectionTicker, selectedMarkets) { return __async(this, null, function* () { return this.client.sendWriteRequest( `${this.client.apiUrl}/trade-api/v2/multivariate_event_collections/${collectionTicker}`, "POST", { selected_markets: selectedMarkets } ); }); } getMultivariateEventCollectionLookupHistory(collectionTicker, lookbackSeconds) { return __async(this, null, function* () { const response = yield this.client.sendGetRequest( `${this.client.apiUrl}/trade-api/v2/multivariate_event_collections/${collectionTicker}/lookup`, { lookback_seconds: lookbackSeconds } ); return response.lookup_points; }); } lookupTickersForMarketInMultivariateEventCollection(collectionTicker, selectedMarkets) { return __async(this, null, function* () { return this.client.sendWriteRequest( `${this.client.apiUrl}/trade-api/v2/multivariate_event_collections/${collectionTicker}/lookup`, "PUT", { selected_markets: selectedMarkets } ); }); } }; // src/kalshi/kalshiClient.ts var CRYPTO_SIGNING_TYPE = "sha256"; var KalshiClient = class _KalshiClient { constructor(key, kalshiAPIid, apiUrl) { this.privateKey = key; this.kalshiAPIId = kalshiAPIid; this.apiUrl = apiUrl || KALSHI_DEFAULT_URL; this.markets = new KalshiMarketsClient(this); this.exchange = new KalshiExchangeClient(this); this.collections = new KalshiCollectionsClient(this); } static fromFile(filePath, kalshiAPIId, apiUrl) { const keyData = import_fs.default.readFileSync(filePath, "utf8"); return new _KalshiClient( import_crypto.default.createPrivateKey({ key: keyData, format: "pem" }), kalshiAPIId, apiUrl ); } static fromKey(key, kalshiAPIId, apiUrl) { return new _KalshiClient(key, kalshiAPIId, apiUrl); } ////////////////////// HELPERS ////////////////////// signPssText(privateKey, text) { const message = Buffer.from(text, "utf-8"); try { const signature = import_crypto.default.sign(CRYPTO_SIGNING_TYPE, message, { key: privateKey, padding: import_crypto.default.constants.RSA_PKCS1_PSS_PADDING, saltLength: import_crypto.default.constants.RSA_PSS_SALTLEN_DIGEST }); return signature.toString("base64"); } catch (error) { throw new Error("RSA sign PSS failed: " + error.message); } } generateRequestHeaders(path, method) { const currentTime = /* @__PURE__ */ new Date(); const currentTimeMilliseconds = currentTime.getTime(); const timestampStr = currentTimeMilliseconds.toString(); const msgString = timestampStr + method + path; const sig = this.signPssText(this.privateKey, msgString); const headers = { "KALSHI-ACCESS-KEY": this.kalshiAPIId, "KALSHI-ACCESS-SIGNATURE": sig, "KALSHI-ACCESS-TIMESTAMP": timestampStr, "Content-Type": "application/json" }; return headers; } sendWriteRequest(url, method, body) { return __async(this, null, function* () { let axiosFunc; const headers = this.generateRequestHeaders(url, method); switch (method) { case "POST": axiosFunc = import_axios.default.post; break; case "PUT": axiosFunc = import_axios.default.put; break; case "DELETE": axiosFunc = import_axios.default.delete; break; } try { const response = yield this.sendWithRetries(() => axiosFunc(`${url}`, body, { headers })); return response.data; } catch (error) { console.error(error); throw error; } }); } sendGetRequest(url, params) { return __async(this, null, function* () { const headers = this.generateRequestHeaders(url, "GET"); try { const response = yield this.sendWithRetries(() => import_axios.default.get(url, { headers, params })); return response.data; } catch (error) { console.error(error); throw error; } }); } sendWithRetries(func, retries = 3) { return __async(this, null, function* () { var _a; for (let attempt = 1; attempt <= retries; attempt++) { try { return yield func(); } catch (error) { if (((_a = error.response) == null ? void 0 : _a.status) === 429) { const delay = attempt * 250; yield new Promise((res) => setTimeout(res, delay)); } else { throw error; } } } throw new Error(`Request failed after ${retries} attempts`); }); } }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { KalshiClient });