kalshi-sdk
Version:
A public TypeScript SDK for Kalshi (https://kalshi.com/)
304 lines (297 loc) • 9.17 kB
JavaScript
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/kalshi/kalshiClient.ts
import axios from "axios";
import crypto from "crypto";
import fs from "fs";
// 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 = fs.readFileSync(filePath, "utf8");
return new _KalshiClient(
crypto.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 = crypto.sign(CRYPTO_SIGNING_TYPE, message, {
key: privateKey,
padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
saltLength: crypto.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 = axios.post;
break;
case "PUT":
axiosFunc = axios.put;
break;
case "DELETE":
axiosFunc = axios.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(() => axios.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`);
});
}
};
export {
KalshiClient
};