pmxtjs 0.3.0 → 0.4.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.
Files changed (50) hide show
  1. package/API_REFERENCE.md +448 -51
  2. package/dist/BaseExchange.d.ts +38 -3
  3. package/dist/BaseExchange.js +43 -1
  4. package/dist/exchanges/Kalshi.js +10 -2
  5. package/dist/exchanges/Polymarket.js +12 -4
  6. package/dist/exchanges/kalshi/auth.d.ts +23 -0
  7. package/dist/exchanges/kalshi/auth.js +99 -0
  8. package/dist/exchanges/kalshi/fetchMarkets.d.ts +3 -0
  9. package/dist/exchanges/kalshi/fetchMarkets.js +84 -0
  10. package/dist/exchanges/kalshi/fetchOHLCV.d.ts +3 -0
  11. package/dist/exchanges/kalshi/fetchOHLCV.js +78 -0
  12. package/dist/exchanges/kalshi/fetchOrderBook.d.ts +2 -0
  13. package/dist/exchanges/kalshi/fetchOrderBook.js +32 -0
  14. package/dist/exchanges/kalshi/fetchTrades.d.ts +3 -0
  15. package/dist/exchanges/kalshi/fetchTrades.js +31 -0
  16. package/dist/exchanges/kalshi/getMarketsBySlug.d.ts +7 -0
  17. package/dist/exchanges/kalshi/getMarketsBySlug.js +46 -0
  18. package/dist/exchanges/kalshi/index.d.ts +21 -0
  19. package/dist/exchanges/kalshi/index.js +273 -0
  20. package/dist/exchanges/kalshi/kalshi.test.d.ts +1 -0
  21. package/dist/exchanges/kalshi/kalshi.test.js +309 -0
  22. package/dist/exchanges/kalshi/searchMarkets.d.ts +3 -0
  23. package/dist/exchanges/kalshi/searchMarkets.js +28 -0
  24. package/dist/exchanges/kalshi/utils.d.ts +4 -0
  25. package/dist/exchanges/kalshi/utils.js +70 -0
  26. package/dist/exchanges/polymarket/auth.d.ts +32 -0
  27. package/dist/exchanges/polymarket/auth.js +98 -0
  28. package/dist/exchanges/polymarket/fetchMarkets.d.ts +3 -0
  29. package/dist/exchanges/polymarket/fetchMarkets.js +75 -0
  30. package/dist/exchanges/polymarket/fetchOHLCV.d.ts +7 -0
  31. package/dist/exchanges/polymarket/fetchOHLCV.js +73 -0
  32. package/dist/exchanges/polymarket/fetchOrderBook.d.ts +6 -0
  33. package/dist/exchanges/polymarket/fetchOrderBook.js +38 -0
  34. package/dist/exchanges/polymarket/fetchPositions.d.ts +2 -0
  35. package/dist/exchanges/polymarket/fetchPositions.js +27 -0
  36. package/dist/exchanges/polymarket/fetchTrades.d.ts +11 -0
  37. package/dist/exchanges/polymarket/fetchTrades.js +59 -0
  38. package/dist/exchanges/polymarket/getMarketsBySlug.d.ts +7 -0
  39. package/dist/exchanges/polymarket/getMarketsBySlug.js +39 -0
  40. package/dist/exchanges/polymarket/index.d.ts +23 -0
  41. package/dist/exchanges/polymarket/index.js +216 -0
  42. package/dist/exchanges/polymarket/searchMarkets.d.ts +3 -0
  43. package/dist/exchanges/polymarket/searchMarkets.js +35 -0
  44. package/dist/exchanges/polymarket/utils.d.ts +7 -0
  45. package/dist/exchanges/polymarket/utils.js +95 -0
  46. package/dist/index.d.ts +4 -4
  47. package/dist/index.js +8 -8
  48. package/dist/types.d.ts +38 -0
  49. package/package.json +5 -1
  50. package/readme.md +44 -24
@@ -0,0 +1,273 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.KalshiExchange = void 0;
7
+ const axios_1 = __importDefault(require("axios"));
8
+ const BaseExchange_1 = require("../../BaseExchange");
9
+ const fetchMarkets_1 = require("./fetchMarkets");
10
+ const searchMarkets_1 = require("./searchMarkets");
11
+ const getMarketsBySlug_1 = require("./getMarketsBySlug");
12
+ const fetchOHLCV_1 = require("./fetchOHLCV");
13
+ const fetchOrderBook_1 = require("./fetchOrderBook");
14
+ const fetchTrades_1 = require("./fetchTrades");
15
+ const auth_1 = require("./auth");
16
+ class KalshiExchange extends BaseExchange_1.PredictionMarketExchange {
17
+ constructor(credentials) {
18
+ super(credentials);
19
+ if (credentials?.apiKey && credentials?.privateKey) {
20
+ this.auth = new auth_1.KalshiAuth(credentials);
21
+ }
22
+ }
23
+ get name() {
24
+ return "Kalshi";
25
+ }
26
+ // ----------------------------------------------------------------------------
27
+ // Helpers
28
+ // ----------------------------------------------------------------------------
29
+ ensureAuth() {
30
+ if (!this.auth) {
31
+ throw new Error('Trading operations require authentication. ' +
32
+ 'Initialize KalshiExchange with credentials (apiKey and privateKey).');
33
+ }
34
+ return this.auth;
35
+ }
36
+ // ----------------------------------------------------------------------------
37
+ // Market Data Methods
38
+ // ----------------------------------------------------------------------------
39
+ async fetchMarkets(params) {
40
+ return (0, fetchMarkets_1.fetchMarkets)(params);
41
+ }
42
+ async searchMarkets(query, params) {
43
+ return (0, searchMarkets_1.searchMarkets)(query, params);
44
+ }
45
+ async getMarketsBySlug(slug) {
46
+ return (0, getMarketsBySlug_1.getMarketsBySlug)(slug);
47
+ }
48
+ async fetchOHLCV(id, params) {
49
+ return (0, fetchOHLCV_1.fetchOHLCV)(id, params);
50
+ }
51
+ async fetchOrderBook(id) {
52
+ return (0, fetchOrderBook_1.fetchOrderBook)(id);
53
+ }
54
+ async fetchTrades(id, params) {
55
+ return (0, fetchTrades_1.fetchTrades)(id, params);
56
+ }
57
+ // ----------------------------------------------------------------------------
58
+ // User Data Methods
59
+ // ----------------------------------------------------------------------------
60
+ async fetchBalance() {
61
+ const auth = this.ensureAuth();
62
+ const path = '/trade-api/v2/portfolio/balance';
63
+ // Use demo-api if it's a sandbox key (usually indicated by config, but defaulting to prod for now)
64
+ // Or we could detect it. For now, let's assume Production unless specified.
65
+ // TODO: Make base URL configurable in credentials
66
+ const baseUrl = 'https://trading-api.kalshi.com';
67
+ const headers = auth.getHeaders('GET', path);
68
+ try {
69
+ const response = await axios_1.default.get(`${baseUrl}${path}`, { headers });
70
+ // Kalshi response structure:
71
+ // - balance: Available balance in cents (for trading)
72
+ // - portfolio_value: Total portfolio value in cents (includes positions)
73
+ // - updated_ts: Unix timestamp of last update
74
+ const balanceCents = response.data.balance;
75
+ const portfolioValueCents = response.data.portfolio_value;
76
+ const available = balanceCents / 100;
77
+ const total = portfolioValueCents / 100;
78
+ const locked = total - available;
79
+ return [{
80
+ currency: 'USD',
81
+ total: total, // Total portfolio value (cash + positions)
82
+ available: available, // Available for trading
83
+ locked: locked // Value locked in positions
84
+ }];
85
+ }
86
+ catch (error) {
87
+ console.error("Kalshi fetchBalance error:", error?.response?.data || error.message);
88
+ throw error;
89
+ }
90
+ }
91
+ // ----------------------------------------------------------------------------
92
+ // Trading Methods
93
+ // ----------------------------------------------------------------------------
94
+ async createOrder(params) {
95
+ const auth = this.ensureAuth();
96
+ const path = '/trade-api/v2/portfolio/orders';
97
+ const baseUrl = 'https://trading-api.kalshi.com';
98
+ const headers = auth.getHeaders('POST', path);
99
+ // Map unified params to Kalshi format
100
+ // Kalshi uses 'yes'/'no' for side and 'buy'/'sell' for action
101
+ const isYesSide = params.side === 'buy';
102
+ const kalshiOrder = {
103
+ ticker: params.marketId, // Kalshi uses ticker for market identification
104
+ client_order_id: `pmxt-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
105
+ side: isYesSide ? 'yes' : 'no',
106
+ action: params.side === 'buy' ? 'buy' : 'sell',
107
+ count: params.amount, // Number of contracts
108
+ type: params.type === 'limit' ? 'limit' : 'market'
109
+ };
110
+ // Add price field based on side (yes_price for yes side, no_price for no side)
111
+ if (params.price) {
112
+ const priceInCents = Math.round(params.price * 100);
113
+ if (isYesSide) {
114
+ kalshiOrder.yes_price = priceInCents;
115
+ }
116
+ else {
117
+ kalshiOrder.no_price = priceInCents;
118
+ }
119
+ }
120
+ try {
121
+ const response = await axios_1.default.post(`${baseUrl}${path}`, kalshiOrder, { headers });
122
+ const order = response.data.order;
123
+ return {
124
+ id: order.order_id,
125
+ marketId: params.marketId,
126
+ outcomeId: params.outcomeId,
127
+ side: params.side,
128
+ type: params.type,
129
+ price: params.price,
130
+ amount: params.amount,
131
+ status: this.mapKalshiOrderStatus(order.status),
132
+ filled: order.queue_position === 0 ? params.amount : 0,
133
+ remaining: order.remaining_count || params.amount,
134
+ timestamp: new Date(order.created_time).getTime()
135
+ };
136
+ }
137
+ catch (error) {
138
+ console.error("Kalshi createOrder error:", error?.response?.data || error.message);
139
+ throw error;
140
+ }
141
+ }
142
+ async cancelOrder(orderId) {
143
+ const auth = this.ensureAuth();
144
+ const path = `/trade-api/v2/portfolio/orders/${orderId}`;
145
+ const baseUrl = 'https://trading-api.kalshi.com';
146
+ const headers = auth.getHeaders('DELETE', path);
147
+ try {
148
+ const response = await axios_1.default.delete(`${baseUrl}${path}`, { headers });
149
+ const order = response.data.order;
150
+ return {
151
+ id: order.order_id,
152
+ marketId: order.ticker,
153
+ outcomeId: order.ticker,
154
+ side: order.side === 'yes' ? 'buy' : 'sell',
155
+ type: 'limit',
156
+ amount: order.count,
157
+ status: 'cancelled',
158
+ filled: order.count - (order.remaining_count || 0),
159
+ remaining: 0,
160
+ timestamp: new Date(order.created_time).getTime()
161
+ };
162
+ }
163
+ catch (error) {
164
+ console.error("Kalshi cancelOrder error:", error?.response?.data || error.message);
165
+ throw error;
166
+ }
167
+ }
168
+ async fetchOrder(orderId) {
169
+ const auth = this.ensureAuth();
170
+ const path = `/trade-api/v2/portfolio/orders/${orderId}`;
171
+ const baseUrl = 'https://trading-api.kalshi.com';
172
+ const headers = auth.getHeaders('GET', path);
173
+ try {
174
+ const response = await axios_1.default.get(`${baseUrl}${path}`, { headers });
175
+ const order = response.data.order;
176
+ return {
177
+ id: order.order_id,
178
+ marketId: order.ticker,
179
+ outcomeId: order.ticker,
180
+ side: order.side === 'yes' ? 'buy' : 'sell',
181
+ type: order.type === 'limit' ? 'limit' : 'market',
182
+ price: order.yes_price ? order.yes_price / 100 : undefined,
183
+ amount: order.count,
184
+ status: this.mapKalshiOrderStatus(order.status),
185
+ filled: order.count - (order.remaining_count || 0),
186
+ remaining: order.remaining_count || 0,
187
+ timestamp: new Date(order.created_time).getTime()
188
+ };
189
+ }
190
+ catch (error) {
191
+ console.error("Kalshi fetchOrder error:", error?.response?.data || error.message);
192
+ throw error;
193
+ }
194
+ }
195
+ async fetchOpenOrders(marketId) {
196
+ const auth = this.ensureAuth();
197
+ // CRITICAL: Query parameters must NOT be included in the signature
198
+ const basePath = '/trade-api/v2/portfolio/orders';
199
+ let queryParams = '?status=resting';
200
+ if (marketId) {
201
+ queryParams += `&ticker=${marketId}`;
202
+ }
203
+ const baseUrl = 'https://trading-api.kalshi.com';
204
+ // Sign only the base path, not the query parameters
205
+ const headers = auth.getHeaders('GET', basePath);
206
+ try {
207
+ const response = await axios_1.default.get(`${baseUrl}${basePath}${queryParams}`, { headers });
208
+ const orders = response.data.orders || [];
209
+ return orders.map((order) => ({
210
+ id: order.order_id,
211
+ marketId: order.ticker,
212
+ outcomeId: order.ticker,
213
+ side: order.side === 'yes' ? 'buy' : 'sell',
214
+ type: order.type === 'limit' ? 'limit' : 'market',
215
+ price: order.yes_price ? order.yes_price / 100 : undefined,
216
+ amount: order.count,
217
+ status: 'open',
218
+ filled: order.count - (order.remaining_count || 0),
219
+ remaining: order.remaining_count || 0,
220
+ timestamp: new Date(order.created_time).getTime()
221
+ }));
222
+ }
223
+ catch (error) {
224
+ console.error("Kalshi fetchOpenOrders error:", error?.response?.data || error.message);
225
+ return [];
226
+ }
227
+ }
228
+ async fetchPositions() {
229
+ const auth = this.ensureAuth();
230
+ const path = '/trade-api/v2/portfolio/positions';
231
+ const baseUrl = 'https://trading-api.kalshi.com';
232
+ const headers = auth.getHeaders('GET', path);
233
+ try {
234
+ const response = await axios_1.default.get(`${baseUrl}${path}`, { headers });
235
+ const positions = response.data.market_positions || [];
236
+ return positions.map((pos) => {
237
+ const absPosition = Math.abs(pos.position);
238
+ // Prevent division by zero
239
+ const entryPrice = absPosition > 0 ? pos.total_cost / absPosition / 100 : 0;
240
+ return {
241
+ marketId: pos.ticker,
242
+ outcomeId: pos.ticker,
243
+ outcomeLabel: pos.ticker, // Kalshi uses ticker as the outcome label
244
+ size: pos.position, // Positive for long, negative for short
245
+ entryPrice: entryPrice,
246
+ currentPrice: pos.market_price ? pos.market_price / 100 : entryPrice,
247
+ unrealizedPnL: pos.market_exposure ? pos.market_exposure / 100 : 0,
248
+ realizedPnL: pos.realized_pnl ? pos.realized_pnl / 100 : 0
249
+ };
250
+ });
251
+ }
252
+ catch (error) {
253
+ console.error("Kalshi fetchPositions error:", error?.response?.data || error.message);
254
+ return [];
255
+ }
256
+ }
257
+ // Helper to map Kalshi order status to unified status
258
+ mapKalshiOrderStatus(status) {
259
+ switch (status.toLowerCase()) {
260
+ case 'resting':
261
+ return 'open';
262
+ case 'canceled':
263
+ case 'cancelled':
264
+ return 'cancelled';
265
+ case 'executed':
266
+ case 'filled':
267
+ return 'filled';
268
+ default:
269
+ return 'open';
270
+ }
271
+ }
272
+ }
273
+ exports.KalshiExchange = KalshiExchange;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,309 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const kalshi_1 = require("../kalshi");
7
+ const axios_1 = __importDefault(require("axios"));
8
+ const auth_1 = require("./auth");
9
+ // Mock axios
10
+ jest.mock('axios');
11
+ const mockedAxios = axios_1.default;
12
+ // Mock KalshiAuth
13
+ jest.mock('./auth');
14
+ const MockedKalshiAuth = auth_1.KalshiAuth;
15
+ describe('KalshiExchange', () => {
16
+ let exchange;
17
+ const mockCredentials = {
18
+ apiKey: 'test-api-key',
19
+ privateKey: 'mock-private-key'
20
+ };
21
+ beforeEach(() => {
22
+ jest.clearAllMocks();
23
+ // Mock the getHeaders method
24
+ MockedKalshiAuth.prototype.getHeaders = jest.fn().mockReturnValue({
25
+ 'KALSHI-ACCESS-KEY': 'test-api-key',
26
+ 'KALSHI-ACCESS-TIMESTAMP': '1234567890',
27
+ 'KALSHI-ACCESS-SIGNATURE': 'mock-signature',
28
+ 'Content-Type': 'application/json'
29
+ });
30
+ });
31
+ describe('Authentication', () => {
32
+ it('should throw error when trading without credentials', async () => {
33
+ exchange = new kalshi_1.KalshiExchange();
34
+ await expect(exchange.fetchBalance()).rejects.toThrow('Trading operations require authentication');
35
+ });
36
+ it('should initialize with credentials', () => {
37
+ exchange = new kalshi_1.KalshiExchange(mockCredentials);
38
+ expect(exchange).toBeDefined();
39
+ });
40
+ });
41
+ describe('Market Data Methods', () => {
42
+ beforeEach(() => {
43
+ exchange = new kalshi_1.KalshiExchange();
44
+ });
45
+ it('should fetch markets', async () => {
46
+ const mockResponse = {
47
+ data: {
48
+ markets: [
49
+ {
50
+ ticker: 'TEST-MARKET',
51
+ title: 'Test Market',
52
+ yes_bid: 50,
53
+ yes_ask: 52,
54
+ volume: 1000
55
+ }
56
+ ]
57
+ }
58
+ };
59
+ mockedAxios.get.mockResolvedValue(mockResponse);
60
+ const markets = await exchange.fetchMarkets();
61
+ expect(markets).toBeDefined();
62
+ });
63
+ });
64
+ describe('Trading Methods', () => {
65
+ beforeEach(() => {
66
+ exchange = new kalshi_1.KalshiExchange(mockCredentials);
67
+ });
68
+ describe('createOrder', () => {
69
+ it('should create buy order with yes_price for buy side', async () => {
70
+ const orderParams = {
71
+ marketId: 'TEST-MARKET',
72
+ outcomeId: 'yes',
73
+ side: 'buy',
74
+ type: 'limit',
75
+ amount: 10,
76
+ price: 0.55
77
+ };
78
+ const mockResponse = {
79
+ data: {
80
+ order: {
81
+ order_id: 'order-123',
82
+ ticker: 'TEST-MARKET',
83
+ status: 'resting',
84
+ count: 10,
85
+ remaining_count: 10,
86
+ created_time: '2026-01-13T12:00:00Z',
87
+ queue_position: 1
88
+ }
89
+ }
90
+ };
91
+ mockedAxios.post.mockResolvedValue(mockResponse);
92
+ const order = await exchange.createOrder(orderParams);
93
+ expect(mockedAxios.post).toHaveBeenCalledWith('https://trading-api.kalshi.com/trade-api/v2/portfolio/orders', expect.objectContaining({
94
+ ticker: 'TEST-MARKET',
95
+ side: 'yes',
96
+ action: 'buy',
97
+ count: 10,
98
+ type: 'limit',
99
+ yes_price: 55 // 0.55 * 100
100
+ }), expect.any(Object));
101
+ expect(order.id).toBe('order-123');
102
+ expect(order.status).toBe('open');
103
+ });
104
+ it('should create sell order with no_price for sell side', async () => {
105
+ const orderParams = {
106
+ marketId: 'TEST-MARKET',
107
+ outcomeId: 'no',
108
+ side: 'sell',
109
+ type: 'limit',
110
+ amount: 5,
111
+ price: 0.45
112
+ };
113
+ const mockResponse = {
114
+ data: {
115
+ order: {
116
+ order_id: 'order-456',
117
+ ticker: 'TEST-MARKET',
118
+ status: 'resting',
119
+ count: 5,
120
+ remaining_count: 5,
121
+ created_time: '2026-01-13T12:00:00Z',
122
+ queue_position: 1
123
+ }
124
+ }
125
+ };
126
+ mockedAxios.post.mockResolvedValue(mockResponse);
127
+ await exchange.createOrder(orderParams);
128
+ expect(mockedAxios.post).toHaveBeenCalledWith('https://trading-api.kalshi.com/trade-api/v2/portfolio/orders', expect.objectContaining({
129
+ ticker: 'TEST-MARKET',
130
+ side: 'no',
131
+ action: 'sell',
132
+ count: 5,
133
+ type: 'limit',
134
+ no_price: 45 // 0.45 * 100
135
+ }), expect.any(Object));
136
+ });
137
+ });
138
+ describe('fetchOpenOrders', () => {
139
+ it('should sign request without query parameters', async () => {
140
+ const mockResponse = {
141
+ data: {
142
+ orders: [
143
+ {
144
+ order_id: 'order-123',
145
+ ticker: 'TEST-MARKET',
146
+ side: 'yes',
147
+ type: 'limit',
148
+ yes_price: 55,
149
+ count: 10,
150
+ remaining_count: 10,
151
+ created_time: '2026-01-13T12:00:00Z'
152
+ }
153
+ ]
154
+ }
155
+ };
156
+ mockedAxios.get.mockResolvedValue(mockResponse);
157
+ await exchange.fetchOpenOrders();
158
+ // Verify the request URL includes query params
159
+ expect(mockedAxios.get).toHaveBeenCalledWith('https://trading-api.kalshi.com/trade-api/v2/portfolio/orders?status=resting', expect.any(Object));
160
+ // Verify getHeaders was called with base path only (no query params)
161
+ expect(MockedKalshiAuth.prototype.getHeaders).toHaveBeenCalledWith('GET', '/trade-api/v2/portfolio/orders');
162
+ });
163
+ it('should include ticker in query params when marketId provided', async () => {
164
+ const mockResponse = { data: { orders: [] } };
165
+ mockedAxios.get.mockResolvedValue(mockResponse);
166
+ await exchange.fetchOpenOrders('TEST-MARKET');
167
+ expect(mockedAxios.get).toHaveBeenCalledWith('https://trading-api.kalshi.com/trade-api/v2/portfolio/orders?status=resting&ticker=TEST-MARKET', expect.any(Object));
168
+ });
169
+ });
170
+ describe('fetchPositions', () => {
171
+ it('should handle positions with zero contracts', async () => {
172
+ const mockResponse = {
173
+ data: {
174
+ market_positions: [
175
+ {
176
+ ticker: 'TEST-MARKET',
177
+ position: 0,
178
+ total_cost: 0,
179
+ market_exposure: 0,
180
+ realized_pnl: 0
181
+ }
182
+ ]
183
+ }
184
+ };
185
+ mockedAxios.get.mockResolvedValue(mockResponse);
186
+ const positions = await exchange.fetchPositions();
187
+ expect(positions).toHaveLength(1);
188
+ expect(positions[0].size).toBe(0);
189
+ expect(positions[0].entryPrice).toBe(0); // Should not throw division by zero
190
+ });
191
+ it('should correctly calculate average price and PnL', async () => {
192
+ const mockResponse = {
193
+ data: {
194
+ market_positions: [
195
+ {
196
+ ticker: 'TEST-MARKET',
197
+ position: 10,
198
+ total_cost: 550, // 10 contracts at $0.55 each = $5.50 = 550 cents
199
+ market_exposure: 100, // $1.00 unrealized PnL
200
+ realized_pnl: 50 // $0.50 realized PnL
201
+ }
202
+ ]
203
+ }
204
+ };
205
+ mockedAxios.get.mockResolvedValue(mockResponse);
206
+ const positions = await exchange.fetchPositions();
207
+ expect(positions).toHaveLength(1);
208
+ expect(positions[0].size).toBe(10);
209
+ expect(positions[0].entryPrice).toBe(0.55); // 550 / 10 / 100
210
+ expect(positions[0].unrealizedPnL).toBe(1.00); // 100 / 100
211
+ expect(positions[0].realizedPnL).toBe(0.50); // 50 / 100
212
+ });
213
+ it('should handle short positions', async () => {
214
+ const mockResponse = {
215
+ data: {
216
+ market_positions: [
217
+ {
218
+ ticker: 'TEST-MARKET',
219
+ position: -5, // Short position
220
+ total_cost: 250,
221
+ market_exposure: -50,
222
+ realized_pnl: 25
223
+ }
224
+ ]
225
+ }
226
+ };
227
+ mockedAxios.get.mockResolvedValue(mockResponse);
228
+ const positions = await exchange.fetchPositions();
229
+ expect(positions[0].size).toBe(-5); // Negative for short
230
+ expect(Math.abs(positions[0].size)).toBe(5); // Absolute value
231
+ });
232
+ });
233
+ describe('fetchBalance', () => {
234
+ it('should correctly convert cents to dollars', async () => {
235
+ const mockResponse = {
236
+ data: {
237
+ balance: 10000, // $100.00 available
238
+ portfolio_value: 15000 // $150.00 total
239
+ }
240
+ };
241
+ mockedAxios.get.mockResolvedValue(mockResponse);
242
+ const balances = await exchange.fetchBalance();
243
+ expect(balances).toHaveLength(1);
244
+ expect(balances[0].currency).toBe('USD');
245
+ expect(balances[0].available).toBe(100.00);
246
+ expect(balances[0].total).toBe(150.00);
247
+ expect(balances[0].locked).toBe(50.00); // 150 - 100
248
+ });
249
+ });
250
+ describe('cancelOrder', () => {
251
+ it('should cancel order successfully', async () => {
252
+ const mockResponse = {
253
+ data: {
254
+ order: {
255
+ order_id: 'order-123',
256
+ ticker: 'TEST-MARKET',
257
+ side: 'yes',
258
+ count: 10,
259
+ remaining_count: 5,
260
+ created_time: '2026-01-13T12:00:00Z'
261
+ }
262
+ }
263
+ };
264
+ mockedAxios.delete.mockResolvedValue(mockResponse);
265
+ const order = await exchange.cancelOrder('order-123');
266
+ expect(order.status).toBe('cancelled');
267
+ expect(order.filled).toBe(5); // count - remaining_count
268
+ expect(order.remaining).toBe(0);
269
+ });
270
+ });
271
+ });
272
+ describe('Order Status Mapping', () => {
273
+ beforeEach(() => {
274
+ exchange = new kalshi_1.KalshiExchange(mockCredentials);
275
+ });
276
+ it('should map resting to open', async () => {
277
+ const mockResponse = {
278
+ data: {
279
+ order: {
280
+ order_id: 'order-123',
281
+ ticker: 'TEST',
282
+ status: 'resting',
283
+ count: 10,
284
+ created_time: '2026-01-13T12:00:00Z'
285
+ }
286
+ }
287
+ };
288
+ mockedAxios.get.mockResolvedValue(mockResponse);
289
+ const order = await exchange.fetchOrder('order-123');
290
+ expect(order.status).toBe('open');
291
+ });
292
+ it('should map executed to filled', async () => {
293
+ const mockResponse = {
294
+ data: {
295
+ order: {
296
+ order_id: 'order-123',
297
+ ticker: 'TEST',
298
+ status: 'executed',
299
+ count: 10,
300
+ created_time: '2026-01-13T12:00:00Z'
301
+ }
302
+ }
303
+ };
304
+ mockedAxios.get.mockResolvedValue(mockResponse);
305
+ const order = await exchange.fetchOrder('order-123');
306
+ expect(order.status).toBe('filled');
307
+ });
308
+ });
309
+ });
@@ -0,0 +1,3 @@
1
+ import { MarketFilterParams } from '../../BaseExchange';
2
+ import { UnifiedMarket } from '../../types';
3
+ export declare function searchMarkets(query: string, params?: MarketFilterParams): Promise<UnifiedMarket[]>;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.searchMarkets = searchMarkets;
4
+ const fetchMarkets_1 = require("./fetchMarkets");
5
+ async function searchMarkets(query, params) {
6
+ // We must fetch ALL markets to search them locally since we don't have server-side search
7
+ const fetchLimit = 100000;
8
+ try {
9
+ const markets = await (0, fetchMarkets_1.fetchMarkets)({ ...params, limit: fetchLimit });
10
+ const lowerQuery = query.toLowerCase();
11
+ const searchIn = params?.searchIn || 'title'; // Default to title-only search
12
+ const filtered = markets.filter(market => {
13
+ const titleMatch = (market.title || '').toLowerCase().includes(lowerQuery);
14
+ const descMatch = (market.description || '').toLowerCase().includes(lowerQuery);
15
+ if (searchIn === 'title')
16
+ return titleMatch;
17
+ if (searchIn === 'description')
18
+ return descMatch;
19
+ return titleMatch || descMatch; // 'both'
20
+ });
21
+ const limit = params?.limit || 20;
22
+ return filtered.slice(0, limit);
23
+ }
24
+ catch (error) {
25
+ console.error("Error searching Kalshi data:", error);
26
+ return [];
27
+ }
28
+ }
@@ -0,0 +1,4 @@
1
+ import { UnifiedMarket, CandleInterval } from '../../types';
2
+ export declare const KALSHI_API_URL = "https://api.elections.kalshi.com/trade-api/v2/events";
3
+ export declare function mapMarketToUnified(event: any, market: any): UnifiedMarket | null;
4
+ export declare function mapIntervalToKalshi(interval: CandleInterval): number;