DEV Community

Cover image for Build a Kalshi Trading Bot in Python: From Zero to Ubuntu VPS Deployment (2026)

Build a Kalshi Trading Bot in Python: From Zero to Ubuntu VPS Deployment (2026)

Real API data, fixed-point order books, automated tests, and a Linux service you can operate from SSH.

The first thing I want to know when someone shows me a trading bot repository is whether I can run it.

Not whether it has a dashboard. Not how many strategies the README mentions.

Can I clone it onto a clean machine, start the application, inspect its output, and understand what happens when something fails?

That's what we're going to do here.

We'll build around a small Python project that reads Kalshi's public API, discovers open markets, reconstructs an order book, and continuously prints structured market snapshots.

Then we'll move it to an Ubuntu VPS, run it under systemd, inspect the logs, and cover the problems you're likely to encounter during setup.

The project has no trading credentials, no order-submission method, and no live execution functionality.

What you'll get by the end:

  • A working Python 3.11+ environment on Windows, macOS, or Linux.
  • A read-only Kalshi market scanner that uses actual public API endpoints.
  • A correct YES/NO order-book calculation using fixed-point prices.
  • Automated tests and a deterministic offline example.
  • An Ubuntu VPS deployment with SSH, a dedicated service user, and systemd.
  • Commands for logs, restarts, troubleshooting, and basic operational checks.

The project uses the Python standard library. No third-party dependencies are required.

Verification: I reran the offline example and all 10 automated tests on November 25, 2026; they passed locally. The API paths were checked against Kalshi's official documentation. I could not verify a live Kalshi API connection or run the deployment on a real VPS from this environment, so those steps are provided for readers to execute and verify themselves.

1. What We're Actually Building

The architecture is straightforward:

               Kalshi REST API
                     |
           GET /markets?status=open
                     |
              Select a ticker
                     |
            GET /markets/{ticker}
                     |
          Confirm market is open
                     |
       GET /markets/{ticker}/orderbook
                     |
           Validate price levels
                     |
          Calculate YES / NO BBO
                     |
           Emit JSON snapshots
                     |
             Terminal / VPS
                     |
              systemd journal
Enter fullscreen mode Exit fullscreen mode

BBO means best bid and offer.

The program has three commands:

Command Purpose
offline Read a synthetic fixture without internet access
list Find open Kalshi market tickers
scan Read one market's order book and publish a snapshot

It also supports continuous polling, bounded API retries, and graceful termination.

This is the foundation for a more sophisticated market-data service. It isn't an executable trading strategy.

2. Which Kalshi API and Python SDK Should We Use?

Kalshi currently documents this production Trade API endpoint:

https://external-api.kalshi.com/trade-api/v2
Enter fullscreen mode Exit fullscreen mode

Public market-data requests do not need authentication.

Kalshi also has a separate demo API:

https://external-api.demo.kalshi.co/trade-api/v2
Enter fullscreen mode Exit fullscreen mode

For authenticated applications, Kalshi publishes two official Python SDK packages:

pip install kalshi_python_sync
Enter fullscreen mode Exit fullscreen mode

or:

pip install kalshi_python_async
Enter fullscreen mode Exit fullscreen mode

The older kalshi-python package is deprecated.

For this first project, I'm not using either SDK.

We're making public GET requests with urllib.request, which is included with Python.

That reduces the number of moving parts and makes the request path easy to inspect.

It also means the project doesn't need an API key or a Kalshi account.

Official references:

3. Get the Source Code

GitHub repository: [INSERT PUBLIC REPOSITORY URL BEFORE PUBLISHING]

The accompanying project is structured like this:

kalshi-python-vps-tutorial/
├── kalshi_reader/
│   ├── __init__.py
│   ├── __main__.py
│   ├── client.py
│   └── book.py
├── examples/
│   └── sample_orderbook.json
├── tests/
│   └── test_reader.py
├── deploy/
│   └── kalshi-reader.service
├── .env.example
├── .gitignore
├── requirements.txt
├── README.md
└── LICENSE
Enter fullscreen mode Exit fullscreen mode

client.py handles public HTTP requests and retries.

book.py validates the fixed-point order-book data and calculates quotes.

__main__.py provides the command-line interface.

The test suite is in tests/test_reader.py, and the service file is under deploy/.

Download or clone the repository and open your terminal in the project root.

4. Install on Windows

Install Python 3.11 or newer from python.org.

Open PowerShell and check the installation:

py --version
Enter fullscreen mode Exit fullscreen mode

Navigate into the project:

cd path\to\kalshi-python-vps-tutorial
Enter fullscreen mode Exit fullscreen mode

Create a virtual environment:

py -m venv .venv
Enter fullscreen mode Exit fullscreen mode

Now start the offline example:

.\.venv\Scripts\python.exe -m kalshi_reader offline
Enter fullscreen mode Exit fullscreen mode

You don't have to activate the virtual environment.

Calling its interpreter directly also avoids PowerShell script-execution-policy issues.

Run the tests:

.\.venv\Scripts\python.exe -m unittest discover -s tests -v
Enter fullscreen mode Exit fullscreen mode

If everything is installed correctly, the tests should complete without failures.

We'll look at the actual expected output shortly.

5. Install on macOS

Install Python 3.11+ from python.org or your preferred trusted package manager.

Open Terminal in the project directory.

python3 --version

python3 -m venv .venv

./.venv/bin/python -m kalshi_reader offline
Enter fullscreen mode Exit fullscreen mode

Run the tests:

./.venv/bin/python -m unittest discover -s tests -v
Enter fullscreen mode Exit fullscreen mode

The source code is identical on macOS, Windows, and Linux. Only the path to the virtual-environment interpreter changes.

6. Install on Ubuntu or Linux

On Ubuntu 24.04:

sudo apt update

sudo apt install -y python3 python3-venv
Enter fullscreen mode Exit fullscreen mode

Then inside the project directory:

python3 -m venv .venv

./.venv/bin/python -m kalshi_reader offline

./.venv/bin/python -m unittest discover -s tests -v
Enter fullscreen mode Exit fullscreen mode

The project requires Python 3.11 or newer.

If your Linux distribution has an older version, use its supported installation method rather than replacing the system Python.

Check the expected output

The offline command reads a synthetic order book.

The important fields should look like this:

{
  "event": "offline_snapshot",
  "status": "OK",
  "yes_bid": "0.4200",
  "yes_ask": "0.4400",
  "no_bid": "0.5600",
  "no_ask": "0.5800",
  "yes_spread": "0.0200"
}
Enter fullscreen mode Exit fullscreen mode

The actual program also prints a UTC timestamp and a note identifying the data as synthetic.

I verified this output locally.

At this stage, you've established that Python can import the project, parse its fixture, and calculate the book correctly.

You haven't contacted Kalshi yet.

That's intentional. When debugging installations, I prefer proving the local environment works before introducing network failures.

7. Connect to Kalshi's Public API

Now we can retrieve actual market data.

The program's market-discovery command calls:

GET /trade-api/v2/markets?status=open&limit=20
Enter fullscreen mode Exit fullscreen mode

On macOS/Linux:

./.venv/bin/python -m kalshi_reader list --limit 20
Enter fullscreen mode Exit fullscreen mode

On Windows:

.\.venv\Scripts\python.exe -m kalshi_reader list --limit 20
Enter fullscreen mode Exit fullscreen mode

The scanner prints market tickers, titles, and statuses as JSON lines.

You can narrow discovery to a particular series:

./.venv/bin/python -m kalshi_reader list --series KXHIGHNY --limit 20
Enter fullscreen mode Exit fullscreen mode

KXHIGHNY is a series used in Kalshi's documentation. If there are no currently open markets in that series, run the listing without the filter.

Important: use a current ticker

Don't copy a market ticker from a tutorial written months ago.

Prediction-market contracts expire, close, and settle.

Use the list output to identify an open market.

Then run:

./.venv/bin/python -m kalshi_reader scan \
  --ticker YOUR_OPEN_MARKET_TICKER \
  --once
Enter fullscreen mode Exit fullscreen mode

Replace the placeholder with an actual ticker.

The program reads market metadata, checks its status, and requests the order book.

It doesn't submit an order.

Keep the scanner running

Once a single scan succeeds:

./.venv/bin/python -m kalshi_reader scan \
  --ticker YOUR_OPEN_MARKET_TICKER \
  --interval 30
Enter fullscreen mode Exit fullscreen mode

That polls the selected market every 30 seconds.

Stop it with Ctrl+C.

The implementation enforces a minimum 10-second polling interval and includes bounded retries for rate limits and transient server failures.

For demo public data, add:

--env demo
Enter fullscreen mode Exit fullscreen mode

The production and demo environments have separate datasets. Don't assume the same ticker is available in both.

Market discovery is paginated

The example's list command retrieves only the first page.

Kalshi's /markets API uses a cursor for additional pages. The correct production implementation must preserve the returned cursor, stop when it is empty, and deduplicate by ticker.

Kalshi documents that an invalid cursor can be ignored, causing the first page to be returned again.

A collector that blindly appends every response could duplicate markets or repeatedly process the same page.

That's a useful next improvement if you want a full market catalog.

Reference: Get Markets API.

8. Kalshi Order Books: The Detail You Need to Get Right

Kalshi's order-book response contains bids on two sides.

An abbreviated response looks like this:

{
  "orderbook_fp": {
    "yes_dollars": [
      ["0.4100", "10.00"],
      ["0.4200", "13.00"]
    ],
    "no_dollars": [
      ["0.4400", "29.00"],
      ["0.5600", "17.00"]
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

Each level contains:

[price_dollars, contract_quantity]
Enter fullscreen mode Exit fullscreen mode

The values are fixed-point strings.

The arrays are ordered by ascending price, so the highest bid is the last entry.

There are no separate ask arrays.

In a binary market:

YES ask = $1.00 - best NO bid
NO ask  = $1.00 - best YES bid
Enter fullscreen mode Exit fullscreen mode

Using the sample data:

Best YES bid = $0.42
Best NO bid  = $0.56

Implied YES ask = $1.00 - $0.56
                = $0.44

YES spread = $0.44 - $0.42
           = $0.02
Enter fullscreen mode Exit fullscreen mode

The best NO bid has 17 contracts in this example, so the implied YES ask has 17 contracts at that level.

The size doesn't disappear when you convert the quote.

Why I use Decimal

Don't assume every Kalshi price is restricted to whole cents.

Kalshi documents fixed-point price and contract-size representations, including support for subpenny pricing and fractional contract quantities in applicable markets.

Python's Decimal avoids introducing binary floating-point errors into the conversion.

Here's the essential calculation:

from decimal import Decimal

ONE = Decimal("1")

def best_quotes(book):
    yes = [
        (Decimal(price), Decimal(quantity))
        for price, quantity in book["yes_dollars"]
    ]

    no = [
        (Decimal(price), Decimal(quantity))
        for price, quantity in book["no_dollars"]
    ]

    if not yes or not no:
        return None

    yes_bid, yes_bid_size = max(yes)
    no_bid, yes_ask_size = max(no)

    yes_ask = ONE - no_bid
    spread = yes_ask - yes_bid

    return {
        "yes_bid": yes_bid,
        "yes_ask": yes_ask,
        "yes_bid_size": yes_bid_size,
        "yes_ask_size": yes_ask_size,
        "spread": spread,
    }
Enter fullscreen mode Exit fullscreen mode

This snippet demonstrates the math; it deliberately omits input validation.

The actual book.py implementation also rejects invalid numeric values, prices outside the allowed range, and nonpositive quantities.

It identifies two cases that should not be trusted as normal quotes:

INCOMPLETE_BOOK — one or both sides have no resting bids.

CROSSED_OR_LOCKED — the reconstructed spread is nonpositive.

Don't turn either condition into an executable signal.

An unknown ticker can also return an empty order book, rather than a useful 404 response. That's why the scanner checks the market metadata first.

Reference: Kalshi Orderbook Responses.

9. What the Automated Tests Actually Verify

Run:

./.venv/bin/python -m unittest discover -s tests -v
Enter fullscreen mode Exit fullscreen mode

The project has 10 unit tests covering:

  • Correct implied YES ask calculation.
  • Empty order-book handling.
  • Crossed-book detection.
  • Invalid fixed-point prices and quantities.
  • Missing response arrays.
  • HTTP 429 retry behavior.
  • Market-close handling.
  • GET-only HTTP requests.
  • Ticker validation.
  • Offline command output.

I reran these tests locally on November 25, 2026.

Result:

Ran 10 tests

OK
Enter fullscreen mode Exit fullscreen mode

That means the tested functions behaved as expected with the supplied fixtures and mocked network responses.

It does not mean we've proven live API connectivity, real trading performance, or uptime on a VPS.

Those require separate tests in their actual environments.

10. Deploy the Kalshi Python Bot on an Ubuntu VPS

Let's move the scanner off the development machine.

For this lightweight read-only program, an Ubuntu 24.04 VPS with approximately 1 vCPU, 1 GB RAM, and outbound HTTPS access is a reasonable starting configuration.

That is a planning recommendation, not a measured hardware benchmark.

You don't need a GPU or an exposed web application port.

Step 1: Connect using SSH

Create an Ubuntu VPS with an SSH public key configured through your hosting provider.

From your local terminal:

ssh ubuntu@YOUR_SERVER_IP
Enter fullscreen mode Exit fullscreen mode

Replace the address and username with those supplied by your provider.

Step 2: Update the server

On the VPS:

sudo apt update
sudo apt upgrade -y

sudo apt install -y \
  python3 \
  python3-venv \
  git \
  rsync \
  ufw
Enter fullscreen mode Exit fullscreen mode

Verify Python:

python3 --version
Enter fullscreen mode Exit fullscreen mode

Allow SSH before activating the firewall:

sudo ufw allow OpenSSH
sudo ufw enable
sudo ufw status
Enter fullscreen mode Exit fullscreen mode

If you use a custom SSH port, allow that port instead.

Confirm you can connect using your SSH key from another terminal before changing password-authentication settings.

Step 3: Copy the source to the VPS

From your local computer, in the directory containing the extracted project:

scp -r kalshi-python-vps-tutorial \
  ubuntu@YOUR_SERVER_IP:~/kalshi-reader-src
Enter fullscreen mode Exit fullscreen mode

Back on the VPS, create a dedicated system user and group.

sudo groupadd --system kalshi-reader

sudo useradd --system \
  --gid kalshi-reader \
  --home-dir /opt/kalshi-reader \
  --shell /usr/sbin/nologin \
  kalshi-reader
Enter fullscreen mode Exit fullscreen mode

Create the application directories:

sudo mkdir -p /opt/kalshi-reader
sudo mkdir -p /etc/kalshi-reader
Enter fullscreen mode Exit fullscreen mode

Copy the files:

sudo rsync -a \
  --exclude .venv \
  --exclude __pycache__ \
  ~/kalshi-reader-src/ \
  /opt/kalshi-reader/
Enter fullscreen mode Exit fullscreen mode

Keep the application source owned by root:

sudo chown -R root:root /opt/kalshi-reader
Enter fullscreen mode Exit fullscreen mode

Create its virtual environment:

sudo python3 -m venv /opt/kalshi-reader/.venv
Enter fullscreen mode Exit fullscreen mode

Now verify the code on the server:

cd /opt/kalshi-reader

sudo .venv/bin/python -m kalshi_reader offline

sudo .venv/bin/python -m unittest discover -s tests -v
Enter fullscreen mode Exit fullscreen mode

Don't proceed just because the files copied successfully.

Check the output.

Step 4: Configure the selected market

Use an open ticker from the market-discovery command.

Create the service environment file:

sudo tee /etc/kalshi-reader/reader.env >/dev/null <<'CONFIG'
KALSHI_ENV=production
KALSHI_TICKER=YOUR_OPEN_MARKET_TICKER
CONFIG
Enter fullscreen mode Exit fullscreen mode

Replace the placeholder.

Restrict access:

sudo chown root:root /etc/kalshi-reader/reader.env
sudo chmod 600 /etc/kalshi-reader/reader.env
Enter fullscreen mode Exit fullscreen mode

The service configuration will load this file through systemd.

There are no trading credentials to store because we're only using public endpoints.

Step 5: Install the systemd service

The repository already contains a service file:

deploy/kalshi-reader.service

Its important settings are:

[Unit]
Description=Casatrick Kalshi Public Market Reader
Wants=network-online.target
After=network-online.target

[Service]
Type=simple
User=kalshi-reader
Group=kalshi-reader
WorkingDirectory=/opt/kalshi-reader
EnvironmentFile=/etc/kalshi-reader/reader.env
ExecStart=/opt/kalshi-reader/.venv/bin/python -m kalshi_reader scan --interval 30
Restart=on-failure
RestartSec=15
TimeoutStopSec=20
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
RestrictSUIDSGID=true
LockPersonality=true
UMask=0077
StandardOutput=journal
StandardError=journal
SyslogIdentifier=kalshi-reader

[Install]
WantedBy=multi-user.target
Enter fullscreen mode Exit fullscreen mode

Notice a few decisions here.

The service runs as kalshi-reader, not root.

The application source is treated as read-only.

Restart=on-failure restarts the process if it exits unexpectedly.

Logs go to the system journal, so we don't need to expose a dashboard or create a public HTTP endpoint.

Install the included service:

sudo cp \
  /opt/kalshi-reader/deploy/kalshi-reader.service \
  /etc/systemd/system/kalshi-reader.service

sudo systemctl daemon-reload
sudo systemctl enable --now kalshi-reader
Enter fullscreen mode Exit fullscreen mode

Step 6: Verify the service

Check whether it started:

sudo systemctl status kalshi-reader --no-pager
Enter fullscreen mode Exit fullscreen mode

Inspect recent output:

sudo journalctl -u kalshi-reader -n 50 --no-pager
Enter fullscreen mode Exit fullscreen mode

Follow logs continuously:

sudo journalctl -u kalshi-reader -f
Enter fullscreen mode Exit fullscreen mode

Restart the service after changing its configuration:

sudo systemctl restart kalshi-reader
Enter fullscreen mode Exit fullscreen mode

Stop it:

sudo systemctl stop kalshi-reader
Enter fullscreen mode Exit fullscreen mode

Check whether it is enabled for system startup:

sudo systemctl is-enabled kalshi-reader
Enter fullscreen mode Exit fullscreen mode

Step 7: Verify recovery behavior

A service reporting active (running) is only one piece of information.

You also want to check:

  • Is it receiving recent market-data responses?
  • Is the selected market still open?
  • Are JSON snapshots appearing at the configured interval?
  • Are rate-limit or connection errors being logged?
  • Can the service restart and resume operation?

For a basic operational check:

sudo systemctl restart kalshi-reader

sudo journalctl -u kalshi-reader -n 30 --no-pager
Enter fullscreen mode Exit fullscreen mode

For reboot recovery, perform a controlled restart of the VPS when it's safe to do so, reconnect, and inspect the service status and logs.

Deployment verification is still required. The steps above have been reviewed against the project's configuration, but they haven't been executed on a real Ubuntu VPS as part of this article.

11. Troubleshooting Problems You're Likely to Hit

Here are common failure cases and where I'd start investigating.

Problem What to check
python: command not found Python installation and interpreter name
No module named kalshi_reader Current working directory
Invalid ticker Use an open ticker returned by list
MARKET_NOT_OPEN The selected contract may have closed or paused
INCOMPLETE_BOOK The order book lacks one or both bid sides
CROSSED_OR_LOCKED Reject the quote as a normal trading signal
HTTP 429 Increase polling interval; inspect retry behavior
Connection errors DNS, outbound HTTPS, TLS, or service availability
systemd service fails User/group, paths, environment file and permissions
Service running but no valid quotes Check JSON statuses, timestamps and market lifecycle

For Linux, start with:

sudo journalctl -u kalshi-reader -n 100 --no-pager
Enter fullscreen mode Exit fullscreen mode

For network connectivity, test the public endpoint separately:

curl -i \
  "https://external-api.kalshi.com/trade-api/v2/markets?status=open&limit=1"
Enter fullscreen mode Exit fullscreen mode

If this request fails, the problem may be connectivity or API access rather than your Python parser.

If it works but the application fails, inspect the response shape and the application's error logs.

What happens when a market closes?

The scanner checks market status before requesting the order book.

If the market is no longer open, it emits MARKET_NOT_OPEN.

It does not automatically roll to the next market.

That would require a separate contract-selection policy using series information and market metadata.

For a research scanner, this limitation is acceptable if it's documented.

For an unattended production strategy, it would need deliberate handling.

12. What I'd Change Before Calling This a Production Bot

The example works with REST snapshots.

Kalshi's public market-data responses can be cached, and a snapshot can be stale by the time your process receives it.

If your strategy depends on current order-book depth, you need a properly synchronized WebSocket feed.

Kalshi's WebSocket order-book channel sends snapshots followed by incremental deltas. It also has sequence numbers and documented recovery behavior.

A correct implementation would need to:

  1. Subscribe to the appropriate market.
  2. Build the initial order book from a snapshot.
  3. Apply signed level changes in message sequence.
  4. Detect missing messages.
  5. Request a fresh snapshot or resubscribe when necessary.
  6. Stop using the book if its state is uncertain.

For conflated updates, Kalshi documents an additional subtlety: exchange clocks can decrease between delta messages. A consumer that discards every delta with a lower clock can corrupt its local book.

That's why a production WebSocket implementation should follow the feed's sequence and recovery rules rather than invent a simple monotonic-clock filter.

Reference: Kalshi WebSocket Orderbook Updates.

And if we add trading, the project becomes considerably larger.

It will need authenticated requests, durable order records, duplicate-safe submission handling, position reconciliation, risk reservations, partial-fill handling, and restart recovery.

A running Python process with a working API connection isn't enough to claim production readiness.

13. What I'd Build Next

The next iteration of this project should be a WebSocket market-data service.

I'd give it five specific goals:

  • Maintain a normalized order book per market.
  • Track snapshot age and message-sequence continuity.
  • Rebuild state safely after disconnects.
  • Persist useful observations for research.
  • Expose health information without exposing credentials or trading controls.

After that, a separate demo-only execution project could test authenticated order-state handling using Kalshi's mock-funds environment.

The demo environment is useful for testing supported workflows, but its liquidity and price behavior may not resemble live markets.

I wouldn't claim the application is ready to trade real money simply because a demo request succeeds.

That needs a different level of validation.

14. Building Something More Complex?

If you've followed this guide, you now have the foundations of a Kalshi market-data service.

You can run Python locally, discover markets, inspect an order book, test the parser, and work through deploying it as a background service.

But maybe your project needs more than that.

Maybe you already have a strategy and need reliable execution. Maybe you're connecting Kalshi and Polymarket. Or maybe you have a bot running on a VPS, but its order handling, latency, or recovery behavior isn't good enough.

That's the kind of engineering work I focus on.

I work on custom prediction-market trading infrastructure: API integrations, execution engines, risk controls, strategy automation, and production deployment.

If you need a custom Kalshi or Polymarket bot built or an existing system fixed, contact me.

Include your platform, what you need built or fixed, your approximate development budget, and timeline.

I'll review the requirements and let you know whether it's something I can help with.


Official References

Part 1 of Casatrick's Prediction Market Bot Engineering series. Updated November 25, 2026. The example is read-only and educational. Local tests passed; live API and VPS deployment remain to be independently verified. No trading outcomes are implied or guaranteed.

Top comments (0)