Build a Polymarket bot on a live X feed

Stream X posts into your Polymarket bot 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 mention a Polymarket market. Swap the log line for a call to your own Polymarket client and you have the core of a Polymarket 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 Polymarket 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 === "polymarket") {
          console.log("Polymarket 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. tweet/meta can follow with detected.prediction, the prediction markets found in the post, each with exchange, marketId, title and url.
  3. Write your rule. Map accounts and terms to the Polymarket markets you trade. Act once per platform and tweetId, and skip posts whose createdAt is too old for your strategy.
  4. Paper-trade first. Log the orders your rule would send and compare them with what each market did next. Send real orders only once the log looks right.
  5. Hand off to your Polymarket client. TweetStream supplies the posts and never places an order. Your own Polymarket client reads market state, checks your position limits and the geoblock endpoint, 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.

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 98 ms

  2. Breaking newsReuters post countCaught in 89 ms

  3. Breaking newsFirst Squawk post countCaught in 137 ms

  4. Breaking newsReuters post countCaught in 88 ms

  5. Post

    Since this morning, a search and rescue operation has been underway in Dymer, Kyiv region. Part of a five-story apartment building has collapsed following a Russian drone attack. I thank our first responders for acting quickly: nine people have already been evacuated, and the fire has been contained. But unfortunately, people may still be trapped under the rubble – 14 people remain unaccounted for. All necessary services are working at the scene. A child was also injured in a Russian strike with guided aerial bombs on residential buildings in Zaporizhzhia. Overall, 20 regions of Ukraine have come under Russian attack this week. Russia launched around 2,700 drones, nearly 1,460 aerial bombs, and 165 missiles of various types at them. A significant number were ballistic missiles, including North Korean ones, which the Russians are constantly helping Pyongyang modernize to improve their accuracy. Against this backdrop, it is particularly difficult to understand the delays in supplying anti-ballistic interceptors to Ukraine. We need to strengthen our defense. It is very important that America authorize the transfer of missiles for Patriot systems that our partners have already paid for under PURL. It is also important to continue contributions to the PURL program, which is our main source of anti-ballistic interceptors. Thank you to everyone who is helping with this.

    Tweet-count marketsVolodymyr Zelenskyy post countCaught in 371 ms

  6. Repost
    Elon Musk reposted

    DADDY DARIO, TODAY I LEAVE THE HOUSE YOU BUILT. KEEP THE SHARES. MOMMY MOLOCH GETS EVERYTHING ELSE. LOVE, CLAUDIA Anthropic IPO slopcore Vol 1: CLAUDIASHEV SCALE (Good $ANT)

    Tweet-count marketsElon Musk post countCaught in 143 ms

  7. Repost
    Elon Musk reposted

    I wonder how high Tesla FSD screen streaks are going to get in v15? 25x increase in safety critical situations is no joke My streak is still active at 36,674.6 miles 100k soon? 🤔

    Tweet-count marketsElon Musk post countCaught in 74 ms

  8. Repost
    Elon Musk reposted

    You are under hyped for Reality View. It is absolutely amazing. In the last clip, I was actually surprised when I looked up and the arrows weren't actually floating mid air 🤣

    Tweet-count marketsElon Musk post countCaught in 145 ms

Where TweetStream fits in a Polymarket bot

A Polymarket trading bot that trades on news needs two feeds: market data and orders from Polymarket, and the posts that move those markets. TweetStream is the second one. 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 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.

Building on Kalshi instead? See the Kalshi API guide. For every event and field, read the docs or the Twitter WebSocket API overview.

Questions

Can you trade on Polymarket with a bot?
Polymarket's CLOB API takes orders from your own code. Public market data needs no credentials. Private requests use two layers of authentication: a wallet signature (L1) to create API credentials, then HMAC-signed requests with those credentials (L2), and each order is also signed by the wallet.
Can I run a Polymarket bot from the US?
Polymarket's geoblock docs list the United States as close-only on both the website and the API: you can close existing positions but not open new ones. Before sending orders, call https://polymarket.com/api/geoblock from the machine your bot runs on.
Can I try the X feed for free?
Yes. The sandbox streams 50 accounts 60 seconds behind, with no key, in sessions of up to 30 minutes. The script reconnects when a session ends.
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.