Build a Kalshi API trading bot with a live X feed

Stream X posts next to your Kalshi API client over WebSocket. Try it free on the keyless sandbox in a few lines of JavaScript.

Last updated: November 12, 2026

The script below connects to TweetStream's free sandbox, reads each post as it arrives, and flags the ones that match your terms or link a Kalshi market. Swap the log line for a call to your own Kalshi API client and you have the core of a Kalshi trading bot.

bot.mjsjavascript
// Node.js 22 or later. No key and no dependencies: node bot.mjs
const WATCH = ["rate cut", "tariff", "approved"]; // your terms
// Skip posts older than this when they arrive. The sandbox runs 60 s behind;
// on a live key, set it to what your strategy allows.
const MAX_AGE_SECONDS = 120;
// How far a post's createdAt may run ahead of this machine's clock.
const MAX_SKEW_SECONDS = 60;
const ageSeconds = (ms) => (Date.now() - ms) / 1000;
// Posts already handled, by key, each kept until a replay of it would be skipped as too old.
const seen = new Map();
let failures = 0;
 
function connect() {
  const ws = new WebSocket("wss://sandbox.tweetstream.io/ws", "tweetstream.v1");
 
  ws.addEventListener("message", (event) => {
    // Every frame is a v1 envelope: { v: 1, t, op, id?, ts, d }.
    const { v, t, op, d } = JSON.parse(event.data);
    if (v !== 1) return;
 
    if (t === "control" && op === "sandbox_welcome") {
      failures = 0;
      console.log(`sandbox: ${d.accounts} accounts, ${d.delaySeconds} s behind`);
    }
 
    if (t === "tweet" && op === "content") {
      // createdAt is the post's own time in milliseconds.
      const age = ageSeconds(d.createdAt);
      if (age > MAX_AGE_SECONDS || age < -MAX_SKEW_SECONDS) return;
 
      // Act once per post, across reconnects. author.platform is "twitter" when it is missing.
      const key = `${d.author.platform ?? "twitter"}:${d.tweetId}`;
      if (seen.has(key)) return;
      for (const [oldKey, keptFrom] of seen) {
        if (ageSeconds(keptFrom) > MAX_AGE_SECONDS) seen.delete(oldKey);
      }
      seen.set(key, Math.max(d.createdAt, Date.now()));
 
      const term = WATCH.find((word) => d.text.toLowerCase().includes(word));
      if (term) {
        // Your rule decides here; your own Kalshi client places any order.
        console.log("signal", d.author.handle, d.kind, term, d.text);
      }
    }
 
    if (t === "tweet" && op === "meta") {
      for (const market of d.detected?.prediction ?? []) {
        if (market.exchange === "kalshi") {
          console.log("Kalshi market in post", d.tweetId, market.marketId, market.url);
        }
      }
    }
  });
 
  ws.addEventListener("close", (event) => {
    // Sessions end after 30 minutes, and connections drop. Reconnect, waiting
    // longer after each failure, up to 30 seconds.
    const wait = Math.min(30, 2 ** failures);
    failures += 1;
    console.log("closed", event.code, event.reason, `reconnecting in ${wait} s`);
    setTimeout(connect, wait * 1000);
  });
}
 
connect();
 

Build it in 6 steps

  1. Connect to the sandbox. Run the script with Node.js 22 or later. It opens wss://sandbox.tweetstream.io/ws with the tweetstream.v1 subprotocol and no key. The first frame is control/sandbox_welcome.
  2. Route on t and op. Each frame is a v1 envelope. tweet/content is a new post with tweetId, text, kind and author. When a post links a Kalshi market, tweet/meta follows with it under detected.prediction, with exchange set to kalshi, marketId, title and url.
  3. Write your rule. Map accounts and terms to the Kalshi markets you trade. Act once per platform and tweetId, and skip posts whose createdAt is too old for your strategy.
  4. Test on Kalshi's demo first. Kalshi's demo environment has mock funds and its own API keys. Point your Kalshi client at it until the orders your rule sends look right.
  5. Hand off to your Kalshi API client. TweetStream supplies the posts and never places an order. Your own Kalshi API client reads market state, checks your position limits and sends any order.
  6. Go live with your own accounts. Start a trial, pick the X accounts your markets depend on, and connect with your API key to get their posts in real time instead of a fixed list on a delay.

Connect your Kalshi API client

Kalshi API keys are key pairs: you sign each request with the private key, and Kalshi checks it against the public key it holds. Ed25519 keys are the default, and RSA keys signed with RSA-PSS also work. Every request carries three headers: KALSHI-ACCESS-KEY, KALSHI-ACCESS-TIMESTAMP and KALSHI-ACCESS-SIGNATURE. See Kalshi's API key guide.

Build against the demo environment first. It has mock funds and separate credentials, so a bug can't cost real money. Read markets and prices over REST, and use Kalshi's WebSocket for live order book updates; it needs your API key to connect, even for public channels.

Below: the latest X posts from accounts behind tweet-count and breaking-news markets, shown at least 60 seconds after TweetStream receives each one. Every tracked account is on the live board.

Updated 0s ago · Free board, delayed at least 60 s

Latest posts

  1. Breaking newsReuters post countCaught in 90 ms

  2. Post

    JUST IN: Chinese man Li Ming reportedly ran the network that moved Nvidia chips to China

    Post imagePost image

    Breaking newsKalshi post countCaught in 243 ms

  3. Post

    JUST IN: Meta reportedly restricted more than 5.4 million posts or accounts in India during the first half of 2026.

    Breaking newsPolymarket post countCaught in 78 ms

  4. Reply
    1. Some people thought we meant 25% improvement, no we mean 25 times! Welcome to the singularity. Hope you’re enjoying your stay.

      FSD V15 is 25x safer than V14 I would have guessed V14 is at MINIMUM 2x safer than a human (probably more). These numbers are getting insane. Singularity is here.

      Quoting Phil Duanv15 is 25x safer than v14 across the fleet. That’s hard to notice on any individual drive because most drives are already very safe. The difference only becom…

    We’re going to make the annoying “Promote” button borderline invisible

    Tweet-count marketsElon Musk post countCaught in 88 ms

  5. Quote

    Some people thought we meant 25% improvement, no we mean 25 times! Welcome to the singularity. Hope you’re enjoying your stay. https://x.com/dirtytesla/status/2124267166132285555

    FSD V15 is 25x safer than V14 I would have guessed V14 is at MINIMUM 2x safer than a human (probably more). These numbers are getting insane. Singularity is here.

    Quoting Phil Duanv15 is 25x safer than v14 across the fleet. That’s hard to notice on any individual drive because most drives are already very safe. The difference only becom…

    Tweet-count marketsElon Musk post countCaught in 146 ms

  6. Breaking newsReuters post countCaught in 84 ms

  7. Repost
    Elon Musk reposted

    Here is my initial FSD v15 review after driving with it all afternoon and evening: First off, Elon was right. This update is a BANGER! Tesla Reality View is out of this world and so insanely cool I’m still trying to process it all. FSD V15.0.1 brings so many improvements behind the scenes, in addition to the wildly cool UI. Tesla Reality View IS AMAZING! Pictures and video don’t do it any justice, this is something that has to be experienced to truly understand. Got to take a few friends tonight on drives to show them and every single person was blown away by it. The amount of detail it shows and generates is wild and so impressive. It shows reflection in the car, buildings, trees, turn arrows on the display and more. FSD v15 now has pothole avoidance! I had it swerve and avoid/straddle a few potholes tonight that were difficult for me to see in the dark. Another great new feature in FSD v15 is speed camera slowdown. As you approach a speed camera, it automatically slows smoothly to the speed limit if you are in a quicker profile. This is a huge quality of life improvement especially as more cities get speed cameras. Parking seems near unchanged from the last build, I feel it picking spots quicker especially at the supercharger I went to tonight. Seems to be preferring to park in the first or second open spot it sees which is great, but it tried to park in one handicap spot- otherwise good. By far, the coolest part is Tesla Reality View. Holy crap is it insane to watch while parking. It’s the best backup/360 camera money can buy and such a detailed and clear view. Another new change I haven’t seen many people talk about is the turn signal fade. On FSD, the turn signal sound gets quieter after a few clicks. This is so nice if you’re sitting at a red light and makes drives more peaceful. Quiet Mode is also so nice at night. It darkens the display and just shows arrival time; music, climate on the bottom and a quick grok button on the top. Another feature that makes it feel like a Robotaxi UI and a peaceful supervising experience. Another improvement is much better handling of dips and speed bumps. The past couple updates it’s been a bit too fast in my Model Y, and it’s now so smooth. The nag is definitely reduced. The last couple versions of v14.3 had been sometimes a bit strict, but definitely more relaxed in v15.0.1. Another thing I noticed is way less wiper washing, a very welcome change. Personalized parking preferences are SO cool. At home, I can click on a person icon on the map and choose street parking or driveway, and it backs into the driveway EXACTLY in the spot I park my Model Y. It leared where I park and knows it. It also now lets you choose which lot you want to park in if the mall or store has multiple lots, you can select it on the map, worked at the mall, Costco, and Home Depot tonight. I need to touch on Tesla Reality View again because it’s just that cool. It really feels like you’re in a video game like NFS or GTA. I’m blown away by this and didn’t expect it at all. Tesla teams COOKED with it, I’ve seen so many on X now wanting Teslas because of it. I drove down Rodeo Drive tonight as well as by the SpaceX Falcon 9 and the views were so cool. Another place it’s cool is in wooded areas or tree filled streets, the way it shows everything is spectacular. Parking garages also give a cool look to them with the roof incorporated into the top of the UI. I didn’t think FSD could get this much better, as it was already so good and it did. I absolutely can’t wait to see what else is coming in the future and driving this more on road trips. @elonmusk, you were right- V15 is incredible and super human! Huge congrats to the Tesla team on this, what a sick update. @TeslaSI and UI teams did a fantastic job, thank you all.

    Post image

    Tweet-count marketsElon Musk post countCaught in 87 ms

  8. Repost
    Elon Musk reposted

    Here's my 25-minute drive on @Tesla FSD V15 tonight. I go over the new Tesla Reality View, new parking behavior/options, navigation and more. Tesla Reality View is even more mind-blowing in person than how it appears online. It really is something special. It's the best "Birds Eye" view I've ever seen. V15 will also park straight into your garage at home, does a much better job at handling debris in the road, potholes, etc. I'll have more footage in the coming days/weeks showing all this stuff, but here's a quick first impressions video:

    Tweet-count marketsElon Musk post countCaught in 81 ms

Where TweetStream fits in a Kalshi bot

The Kalshi API gives your bot markets, prices and orders. A Kalshi bot that trades on news also needs the posts that move those markets, and TweetStream supplies them. It streams posts from the X accounts you choose over one WebSocket, as JSON envelopes your code routes on t and op. Your bot owns everything after that: which posts matter, which Kalshi market they map to, and whether to trade.

The sandbox in the script above is free and needs no key. It streams a fixed set of 50 accounts, 60 seconds behind, in the same envelopes the paid stream sends, so the code keeps working when you switch. A paid key gives you your own accounts in real time; TweetStream catches posts in typically 166 ms. Change the host and add your key as the connection docs show.

Trading on Polymarket too? See the Polymarket bot guide. For every event and field, read the docs or the Twitter WebSocket API overview.

Questions

Can you automate trading on Kalshi?
Yes. Kalshi's Trade API takes orders from your own code, each request signed with an API key, and its demo environment has mock funds for testing.
Does Kalshi have a public API?
Kalshi documents a REST API and a WebSocket API at docs.kalshi.com. The WebSocket needs API key authentication to connect, even for channels that carry only public market data.
Does TweetStream place trades?
No. TweetStream delivers posts and never touches an exchange account. Your own client signs and sends every order, under your own limits.

Get these alerts in your bot or Discord, 3-day free trial

Pick your own accounts and get each post in your bot over WebSocket or in your Discord server without this board's 60-second delay. TweetStream catches X posts in typically 166 ms.