Skip to content

Commit 8fff4d4

Browse files
committed
fix(integrations): route kalshi cancels by ticker and harden the read-first order writes
1 parent cbdcbeb commit 8fff4d4

13 files changed

Lines changed: 379 additions & 77 deletions

File tree

‎apps/docs/content/docs/integrations/kalshi.mdx‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -791,6 +791,7 @@ Cancel an existing order on Kalshi
791791
| Parameter | Type | Required | Description |
792792
| --------- | ---- | -------- | ----------- |
793793
| `orderId` | string | Yes | Order ID to cancel \(e.g., "abc123-def456-ghi789"\) |
794+
| `ticker` | string | No | Market ticker of the order \(e.g., "KXBTC-24DEC31"\), so the cancel reaches the order's exchange shard. Leave empty to look it up from the order first |
794795

795796
#### Output
796797

@@ -851,7 +852,7 @@ Modify the price or quantity of an existing order on Kalshi
851852
| `action` | string | Yes | Action type: "buy" or "sell" |
852853
| `clientOrderId` | string | No | Original client-specified order ID |
853854
| `updatedClientOrderId` | string | No | New client-specified order ID after amendment |
854-
| `count` | string | No | New total contracts for the order: already filled plus desired resting \(e.g., "10"\). Leave empty to keep the current total |
855+
| `count` | string | No | New total contracts for the order: already filled plus desired resting \(e.g., "10"\). Leave empty to keep the current total, only if the order hasn't just changed; Kalshi's order reads can briefly lag |
855856
| `yesPrice` | string | No | Updated yes price in cents \(1-99\) |
856857
| `noPrice` | string | No | Updated no price in cents \(1-99\) |
857858
| `yesPriceDollars` | string | No | Updated yes price in dollars \(e.g., "0.56"\) |
@@ -910,7 +911,7 @@ Modify the price or quantity of an existing order on Kalshi
910911
| ↳ `action` | string | Action \(buy/sell\) |
911912
| ↳ `count` | number | Number of contracts |
912913
| ↳ `remaining_count` | number | Remaining contracts |
913-
| ↳ `fill_count_fp` | string | Filled count \(fixed-point\) |
914+
| ↳ `fill_count_fp` | string | Contracts filled by this amend \(fixed-point\) |
914915
| ↳ `remaining_count_fp` | string | Remaining count \(fixed-point\) |
915916
| ↳ `created_time` | string | Order creation time |
916917
| ↳ `expiration_time` | string | Order expiration time |

‎apps/sim/blocks/blocks/dspy.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ describe('DSPy block params', () => {
1616

1717
it('fails on Additional Inputs that are not valid JSON instead of dropping them', () => {
1818
expect(() => mapParams({ additionalInputs: '{"topic": ' })).toThrow(
19-
'Invalid JSON for Additional Inputs'
19+
'Additional Inputs must be valid JSON'
2020
)
2121
})
2222

‎apps/sim/blocks/blocks/dspy.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,13 @@ import { failToolCallOnError, mapperOperation, parseOptionalJsonInput } from '@/
66

77
/** Predict's Additional Inputs: a JSON object as text from the canvas, or an object from an agent. */
88
function parseAdditionalInputs(value: unknown): Record<string, unknown> | undefined {
9-
const parsed = parseOptionalJsonInput(value, 'Additional Inputs')
9+
let parsed: unknown
10+
try {
11+
parsed = parseOptionalJsonInput(value, 'Additional Inputs')
12+
} catch {
13+
// Static on purpose: the parser's message quotes the input, which can hold a resolved secret.
14+
throw new Error('Additional Inputs must be valid JSON')
15+
}
1016
if (parsed === undefined) return undefined
1117
if (!isPlainRecord(parsed)) {
1218
throw new Error('Additional Inputs must be a JSON object')

‎apps/sim/blocks/blocks/kalshi.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,13 @@ Return ONLY the numeric timestamp (seconds since Unix epoch) - no explanations,
431431
required: true,
432432
condition: { field: 'operation', value: ['get_order', 'cancel_order', 'amend_order'] },
433433
},
434+
{
435+
id: 'cancelTicker',
436+
title: 'Market Ticker',
437+
type: 'short-input',
438+
placeholder: "Order's market ticker (optional; looked up from the order when empty)",
439+
condition: { field: 'operation', value: ['cancel_order'] },
440+
},
434441
{
435442
id: 'tickerOrder',
436443
title: 'Market Ticker',
@@ -726,6 +733,7 @@ Return ONLY the numeric timestamp (seconds since Unix epoch) - no explanations,
726733
tickerOrder,
727734
orderType,
728735
orderSelfTradePrevention,
736+
cancelTicker,
729737
countAmend,
730738
clientOrderIdAmend,
731739
...rest
@@ -799,6 +807,11 @@ Return ONLY the numeric timestamp (seconds since Unix epoch) - no explanations,
799807
mapField('ticker', tickerOrder)
800808
}
801809

810+
// Routes the cancel to the order's exchange shard; the tool looks it up when empty.
811+
if (operation === 'cancel_order') {
812+
mapField('ticker', cancelTicker)
813+
}
814+
802815
if (operation === 'create_order') {
803816
mapField('type', orderType)
804817
mapField('selfTradePreventionType', orderSelfTradePrevention)

‎apps/sim/blocks/blocks/lemlist.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,8 @@ export const LemlistBlock: BlockConfig = {
7373
{ label: 'Email Sent', id: 'emailsSent' },
7474
{ label: 'Email Bounced', id: 'emailsBounced' },
7575
{ label: 'Paused', id: 'paused' },
76-
{ label: 'Interested', id: 'interested' },
77-
{ label: 'Not Interested', id: 'notInterested' },
76+
{ label: 'Email Interested', id: 'interested' },
77+
{ label: 'Email Not Interested', id: 'notInterested' },
7878
],
7979
value: () => '',
8080
condition: { field: 'operation', value: 'get_activities' },

‎apps/sim/tools/generated/tool-metadata.ts‎

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

‎apps/sim/tools/generated/tool-outputs.ts‎

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

‎apps/sim/tools/kalshi/amend_order.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,4 +188,48 @@ describe('Kalshi amend order on the V2 event-order endpoint', () => {
188188
remaining_count_fp: '6.00',
189189
})
190190
})
191+
192+
it("reads Kalshi's 6-decimal response values when the extra digits are zeros", async () => {
193+
const params = { ...BASE, count: '10' }
194+
const read = await kalshiAmendOrderV2Tool.transformResponse?.(
195+
Response.json({
196+
order: {
197+
...CURRENT_ORDER,
198+
yes_price_dollars: '0.560000',
199+
fill_count_fp: '2.000',
200+
remaining_count_fp: '6.00',
201+
},
202+
}),
203+
{ ...BASE }
204+
)
205+
const postProcess = kalshiAmendOrderV2Tool.postProcess
206+
if (!read || !postProcess) throw new Error('amend tool cannot read the order')
207+
const boundary = amendBoundary(kalshiAmendOrderV2Tool)
208+
await postProcess(read, { ...BASE }, boundary.executeTool)
209+
expect(boundary.sent[0].body).toMatchObject({ price: '0.5600', count: '8.00' })
210+
211+
const subPenny = await kalshiAmendOrderV2Tool.transformResponse?.(
212+
Response.json({ order: { ...CURRENT_ORDER, yes_price_dollars: '0.560050' } }),
213+
params
214+
)
215+
if (!subPenny) throw new Error('amend tool cannot read the order')
216+
const rejected = await postProcess(subPenny, params, boundary.executeTool)
217+
expect(rejected.success).toBe(false)
218+
expect(boundary.sent).toHaveLength(1)
219+
})
220+
221+
it('reports a failed amend, not the successful read, when the amend throws', async () => {
222+
const params = { ...BASE, yesPrice: '57' }
223+
const read = await kalshiAmendOrderV2Tool.transformResponse?.(
224+
Response.json({ order: CURRENT_ORDER }),
225+
params
226+
)
227+
const postProcess = kalshiAmendOrderV2Tool.postProcess
228+
if (!read || !postProcess) throw new Error('amend tool cannot read the order')
229+
const result = await postProcess(read, params, async () => {
230+
throw new Error('network down')
231+
})
232+
expect(result.success).toBe(false)
233+
expect(result.error).toContain('network down')
234+
})
191235
})

‎apps/sim/tools/kalshi/amend_order.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,15 @@ async function amendWithCurrentOrder(
5959
error: `Could not read the order's current count and price to amend it: ${getErrorMessage(error)}`,
6060
}
6161
}
62-
return executeTool(toolId, { ...params, ...next })
62+
try {
63+
return await executeTool(toolId, { ...params, ...next })
64+
} catch (error) {
65+
return {
66+
success: false,
67+
output: {},
68+
error: `Could not amend the order: ${getErrorMessage(error)}`,
69+
}
70+
}
6371
}
6472

6573
export interface KalshiAmendOrderParams extends KalshiAuthParams {
@@ -78,6 +86,7 @@ export interface KalshiAmendOrderParams extends KalshiAuthParams {
7886

7987
export interface KalshiAmendOrderResponse {
8088
success: boolean
89+
error?: string
8190
output: {
8291
order: Record<string, unknown>
8392
}
@@ -144,7 +153,7 @@ export const kalshiAmendOrderTool: ToolConfig<KalshiAmendOrderParams, KalshiAmen
144153
required: false,
145154
visibility: 'user-or-llm',
146155
description:
147-
'New total contracts for the order: already filled plus desired resting (e.g., "10"). Leave empty to keep the current total',
156+
'New total contracts for the order: already filled plus desired resting (e.g., "10"). Leave empty to keep the current total, only if the order hasn\'t just changed; Kalshi\'s order reads can briefly lag',
148157
},
149158
yesPrice: {
150159
type: 'string',
@@ -317,6 +326,7 @@ function mapOrder(order: Record<string, unknown>): KalshiAmendOrderV2Order {
317326

318327
export interface KalshiAmendOrderV2Response {
319328
success: boolean
329+
error?: string
320330
output: {
321331
old_order: KalshiAmendOrderV2Order
322332
order: KalshiAmendOrderV2Order
@@ -387,7 +397,7 @@ export const kalshiAmendOrderV2Tool: ToolConfig<
387397
required: false,
388398
visibility: 'user-or-llm',
389399
description:
390-
'New total contracts for the order: already filled plus desired resting (e.g., "10"). Leave empty to keep the current total',
400+
'New total contracts for the order: already filled plus desired resting (e.g., "10"). Leave empty to keep the current total, only if the order hasn\'t just changed; Kalshi\'s order reads can briefly lag',
391401
},
392402
yesPrice: {
393403
type: 'string',
@@ -553,7 +563,7 @@ export const kalshiAmendOrderV2Tool: ToolConfig<
553563
remaining_count: { type: 'number', description: 'Remaining contracts', nullable: true },
554564
fill_count_fp: {
555565
type: 'string',
556-
description: 'Filled count (fixed-point)',
566+
description: 'Contracts filled by this amend (fixed-point)',
557567
nullable: true,
558568
},
559569
remaining_count_fp: {

0 commit comments

Comments
 (0)