# Build a CS2 trading bot with the Waxpeer API

This guide shows how to build a CS2 skin trading and arbitrage bot on Waxpeer in Python or Node.js. The bot watches every new listing in real time, compares its price with the market, and buys the ones priced well below it. Buying through the API is an official, documented feature on Waxpeer. You need an API key and nothing else: no scraping, no browser automation, and no Steam bot of your own.

The full script is at the [end of this page](#full-script) in both languages. Each version is about 230 lines, works the same way and runs in dry-run mode by default. The buying path of both was run end to end before publishing.

## What the bot does

1. It subscribes to the public [Socket.IO](/socketio) feed, which pushes every new listing and every price change on Waxpeer as it happens.
2. It keeps the current market price of every item name from [`GET /v1/prices`](/api/buy-items/prices), refreshed every two minutes.
3. It flags a listing as a deal when the listing is much cheaper than the cheapest other listing of the same item and the expected profit covers the sell fee.
4. It checks that the listing is still for sale at that price with [`GET /v1/check-availability`](/api/buy-items/check-availability), then buys it with [`GET /v1/buy-one-p2p`](/api/buy-items/buy-one-p2p).
5. It tracks each purchase with [`GET /v1/check-many-project-id`](/api/buy-items/check-many-project-id) until the item is delivered or the money comes back.

## Before you start

- **API key.** Create or copy it on [waxpeer.com](https://waxpeer.com/profile/user?tab=security). REST calls take it as the `api` query parameter, not as an `Authorization` header. See [Authentication](/authentication).
- **Steam trade link.** Set it in your Waxpeer profile. The bot reads it from [`GET /v1/user`](/api/user/user) and passes its `partner` and `token` to every purchase, so bought items go to your own Steam account.
- **Balance.** Purchases are paid from your Waxpeer balance.
- **Python 3.10 or newer** with two packages, or **Node.js 20 or newer** with one:

```bash
# Python
pip install "python-socketio[client]" requests

# Node.js
npm install socket.io-client
```

## Prices are in thousandths of a dollar

Every price in the API is an integer where 1000 = $1. A price of `22470` is $22.47. The script converts with two helpers so that it never mixes units:

```python
def usd(units: int) -> str:
    return f"${units / 1000:,.2f}"


def to_units(dollars: float) -> int:
    return round(dollars * 1000)
```

```javascript
const usd = units => `$${(units / 1000).toFixed(2)}`;
const toUnits = dollars => Math.round(dollars * 1000);
```

## Step 1. Watch new listings

The feed lives at `wss://waxpeer.com/socket.io/` and speaks the standard Socket.IO v4 protocol. Public item events need no key. After connecting, subscribe to a game with `sub`:

```python
import socketio

sio = socketio.Client(reconnection=True)


@sio.event
def connect():
    sio.emit("sub", {"name": "csgo"})


@sio.on("new")
def on_new(item):
    print(item["name"], item["price"], item["delivery"])


sio.connect("https://waxpeer.com", transports=["websocket"])
sio.wait()
```

```javascript
import { io } from 'socket.io-client';

const socket = io('https://waxpeer.com', { transports: ['websocket'] });

socket.on('connect', () => {
  socket.emit('sub', { name: 'csgo' });
});

socket.on('new', (item) => {
  console.log(item.name, item.price, item.delivery);
});
```

The server emits three events: `new` for a new listing, `update` when a listing changes (a price drop arrives here), and `removed` when it is sold or delisted. Expect a lot of traffic: in a three-minute test the CS2 feed carried about 60,000 `new` and `update` events. Keep the handler cheap and do the slow work, such as HTTP calls, elsewhere: on another thread in Python, in a separate async loop in Node.js.

The feed is a stream of candidates, not a source of truth. Events sent while you are disconnected are not replayed, and not every sale is announced with `removed`. That is why the bot checks a listing again right before buying it (Step 4).

A `new` event looks like this:

```json
{
  "game": "csgo",
  "item_id": "54662725883",
  "name": "M4A4 | Sheet Lightning (Field-Tested)",
  "price": 668,
  "steam_price": 739,
  "delivery": "instant",
  "float": 0.2974646091,
  "paint_index": 1281,
  "phase": "",
  "sticker_names": [],
  "inspect": "steam://run/730//+csgo_econ_action_preview%20..."
}
```

`delivery` tells you how the item reaches you:

| delivery | Meaning |
| --- | --- |
| `instant` | The seller's software sends the trade offer automatically, usually within a minute or two. |
| `regular` | A peer-to-peer listing from a seller who is online. The seller has 5 minutes to send you the Steam trade offer. |
| `hold` | The item is still under a Steam trade lock. You can buy it now, but it is delivered only after `unlock_at`. Buying it needs `allow_trade_locked=1`; without it the purchase is refused with `Item is trade-locked`. |
| `manual` | The seller is offline and has up to 12 hours to send the trade offer. |

The bot buys only `instant` and `regular` listings. All the fields are described on the [Socket.IO page](/socketio#socketio-game-item-event).

## Step 2. Know the market price

[`GET /v1/prices`](/api/buy-items/prices) returns one row per item name with the cheapest price (`min`), the number of listings (`count`) and the Steam price. It needs no key.

```bash
curl "https://api.waxpeer.com/v1/prices?game=csgo&search=AK-47%20%7C%20Redline%20(Field-Tested)"
```

`search` matches every name that contains the text, so this answer also lists the StatTrak™ and Souvenir versions. The row for the exact name looks like this:

```json
{
  "name": "AK-47 | Redline (Field-Tested)",
  "count": 1922,
  "min": 21582,
  "steam_price": 26510,
  "type": "Rifles",
  "rarity": "Classified"
}
```

The full CS2 list is about 7 MB and covers roughly 28,000 names, so load it once and refresh it every minute or two rather than per listing. If you need every single listing instead of one row per name, use the [CSV snapshot](/api/buy-items/prices-snapshot) (`format=csv`).

## Step 3. Decide what is a deal

The example rule compares a new listing with the cheapest other listing of the same name at the last refresh. A listing is a deal when:

- it is at least 15% cheaper than that price;
- the name has at least 20 listings, so the price reflects a real market;
- reselling at that price, after your sell fee, leaves at least $1;
- it costs no more than your per-item limit.

```python
def is_deal(self, item: dict):
    if item.get("game") != GAME or item.get("delivery") not in ("instant", "regular"):
        return None
    ref = self.prices.get(item["name"])
    if not ref or ref["count"] < MIN_LISTINGS or item["price"] > to_units(MAX_PRICE_USD):
        return None
    market = ref["min"]
    if item["price"] > market * (1 - MIN_DISCOUNT):
        return None
    profit = market * self.sell_fee - item["price"]
    if profit < to_units(MIN_PROFIT_USD):
        return None
    return market, profit
```

```javascript
isDeal(item) {
  if (item.game !== GAME || !['instant', 'regular'].includes(item.delivery)) return null;
  const ref = this.prices.get(item.name);
  if (!ref || ref.count < MIN_LISTINGS || item.price > toUnits(MAX_PRICE_USD)) return null;
  const market = ref.min;
  if (item.price > market * (1 - MIN_DISCOUNT)) return null;
  const profit = market * this.sellFee - item.price;
  if (profit < toUnits(MIN_PROFIT_USD)) return null;
  return { market, profit };
}
```

Your sell fee comes from `sell_fees` in [`GET /v1/user`](/api/user/user). It is the share of your listing price you keep, for example `0.94`: Waxpeer pays the seller the listing price times `sell_fees`, rounded up. For CS2 that money is held until the Steam Trade Protection period of the sale ends.

Discounts this deep are rare and other bots compete for them. In a two-minute sample of the live feed, fewer than 20 of about 23,000 events on liquid names were 10% or more below the cheapest listing. Expect the bot to sit idle for long stretches and tune the thresholds to your strategy.

For cross-market arbitrage, set `market` to the price of the same item on another marketplace. Everything else stays the same.

## Step 4. Recheck and buy

A listing can sell in the time it takes your code to react. Ask [`GET /v1/check-availability`](/api/buy-items/check-availability) whether it is still for sale at the price you saw:

```python
live = self.api.check_availability(item_id)
if not live or not live.get("selling") or live.get("unlock_at") or live["price"] > price:
    return
```

```javascript
const live = await this.api.checkAvailability(itemId);
if (!live?.selling || live.unlock_at || live.price > price) return;
```

Then buy with [`GET /v1/buy-one-p2p`](/api/buy-items/buy-one-p2p):

| Parameter | Value |
| --- | --- |
| `api` | Your API key. |
| `item_id` | The listing id from the feed. |
| `price` | The most you agree to pay, in thousandths of a dollar. If the price went up, the purchase is refused instead of charging you more. |
| `partner`, `token` | From your Steam trade link. |
| `project_id` | Your own unique id for this purchase, up to 50 characters. |

`project_id` is what makes retries safe. It is unique per buyer: a second purchase with the same value is refused with `Buy request with projectId: … already exists` and charges nothing. If a request times out, send it again with the same `project_id`. Never generate a new one for a retry, or you may buy twice.

```python
project_id = f"bot-{uuid.uuid4().hex[:24]}"
res = api.get("/v1/buy-one-p2p", item_id=item_id, price=price,
              partner=partner, token=token, project_id=project_id)
```

```javascript
const projectId = `bot-${randomUUID().replaceAll('-', '').slice(0, 24)}`;
const res = await api.get('/v1/buy-one-p2p', {
  item_id: itemId, price, partner, token, project_id: projectId,
});
```

A successful purchase answers with the purchase id and the price you were charged. That is the listing price, which can be lower than your cap:

```json
{ "success": true, "id": 6106, "price": 20000 }
```

When `success` is `false`, `msg` says why. The ones a bot sees most often:

| msg | What to do |
| --- | --- |
| `Item price has increased or item is no longer available` | Someone was faster or the seller changed the price. `error_msg` says which: `Item price has increased` (with the current price in `new_price`) or `Item no longer available`. Skip it. |
| `noFunds` | Your balance is too low. Stop buying. |
| `Buy request with projectId: … already exists` | An earlier request with this `project_id` already went through. Track it instead of buying again. |
| `Your tradelink is incorect, please update it` | Fix the trade link in your profile. |
| `buy_csgo` | Buying CS2 items is paused or has reached its current limit. Try again later. |
| `Too many requests, …` | You hit a purchase rate limit. Slow down. |

The [buy-one-p2p reference](/api/buy-items/buy-one-p2p) lists every message.

## Step 5. Track delivery

Delivery is peer to peer. After a purchase the item goes to the trade link you passed. The seller sends you a Steam trade offer, and you accept it in Steam. If the seller does not send it in time, the purchase is cancelled and what you paid returns to your balance.

Poll [`GET /v1/check-many-project-id`](/api/buy-items/check-many-project-id) with up to 100 project ids per request (`id=a&id=b`), about every 30 seconds. The script sends larger sets in batches of 100:

```python
def track_trades(self):
    if not self.pending:
        return
    for t in self.api.trades(list(self.pending)):
        if not t.get("done"):
            continue
        name = self.pending.pop(t["project_id"], t["name"])
        if t["status"] == 5:
            log.info("completed: %s (Steam trade %s)", name, t.get("trade_id"))
        else:
            log.info("cancelled: %s (%s)", name, t.get("reason"))
```

```javascript
async trackTrades() {
  if (!this.pending.size) return;
  for (const t of await this.api.trades([...this.pending.keys()])) {
    if (!t.done) continue;
    const name = this.pending.get(t.project_id) ?? t.name;
    this.pending.delete(t.project_id);
    if (t.status === 5) log(`completed: ${name} (Steam trade ${t.trade_id})`);
    else log(`cancelled: ${name} (${t.reason})`);
  }
}
```

`done` turns `true` when the purchase is final:

| status | done | Meaning |
| --- | --- | --- |
| `0`, `2`, `4` | `false` | In progress: the trade is being created, waits for the seller, or was sent to you. For CS2, a trade you accepted also stays at `4` during the Steam Trade Protection hold, about 8 days, until `release_date`. |
| `5` | `true` | Completed. |
| `6` | `true` | Cancelled and refunded, or reversed after it was accepted. `reason` says which. |

Do not undo a trade in Steam after accepting it: a reversal by the buyer costs a 30% penalty. All statuses, reasons and timings are on [Trade statuses](/statuses). If you connect to Socket.IO with your API key in the `authorization` header, you also get these updates pushed as `steamTrade` events instead of polling.

## Full script

Run it in dry-run mode first. It then logs the deals it would buy and buys nothing:

```bash
# Python
WAXPEER_API_KEY=your_key python trading_bot.py

# Node.js
WAXPEER_API_KEY=your_key node trading-bot.mjs
```

When you are happy with what it picks, set `DRY_RUN=0`. It then spends real money, within the per-item and daily limits at the top of the file.

```python
"""Waxpeer CS2 trading bot: watch new listings, buy the ones priced well below the market.

pip install "python-socketio[client]" requests
WAXPEER_API_KEY=... python trading_bot.py            # dry run: logs deals, buys nothing
WAXPEER_API_KEY=... DRY_RUN=0 python trading_bot.py  # buys for real
"""
import logging
import os
import queue
import threading
import time
import uuid
from datetime import date
from urllib.parse import parse_qs, urlparse

import requests
import socketio

API_URL = os.environ.get("WAXPEER_API_URL", "https://api.waxpeer.com")
API_KEY = os.environ.get("WAXPEER_API_KEY", "")
DRY_RUN = os.environ.get("DRY_RUN", "1") != "0"

GAME = "csgo"
MIN_DISCOUNT = 0.15       # listing must be at least 15% below the cheapest other listing
MIN_PROFIT_USD = 1.00     # expected profit after the sell fee
MIN_LISTINGS = 20         # skip illiquid names
MAX_PRICE_USD = 100.00    # most the bot pays for one item
DAILY_BUDGET_USD = 300.00 # most the bot spends per day
PRICES_REFRESH_SEC = 120

log = logging.getLogger("bot")


def usd(units: int) -> str:
    return f"${units / 1000:,.2f}"


def to_units(dollars: float) -> int:
    return round(dollars * 1000)


class Waxpeer:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.http = requests.Session()

    def get(self, path: str, **params):
        if self.api_key:
            params["api"] = self.api_key
        for _ in range(5):
            r = self.http.get(f"{API_URL}{path}", params=params, timeout=20)
            if r.status_code == 429:
                time.sleep(float(r.headers.get("Retry-After", "5")))
                continue
            r.raise_for_status()
            return r.json()
        raise RuntimeError(f"{path}: still rate limited")

    def user(self) -> dict:
        data = self.get("/v1/user")
        if not data.get("success"):
            raise RuntimeError(f"/v1/user: {data.get('msg')}")
        return data["user"]

    def prices(self) -> dict:
        data = self.get("/v1/prices", game=GAME)
        return {row["name"]: row for row in data["items"]}

    def check_availability(self, item_id: str):
        data = self.get("/v1/check-availability", item_id=item_id)
        for row in data.get("items") or []:
            if str(row.get("item_id")) == item_id:
                return row
        return None

    def buy(self, item_id: str, price: int, partner: str, token: str, project_id: str) -> dict:
        params = dict(item_id=item_id, price=price, partner=partner, token=token, project_id=project_id)
        try:
            return self.get("/v1/buy-one-p2p", **params)
        except requests.Timeout:
            # Same project_id: if the first request went through, this one is refused and charges nothing.
            return self.get("/v1/buy-one-p2p", **params)

    def trades(self, project_ids: list) -> list:
        rows = []
        for i in range(0, len(project_ids), 100):
            data = self.get("/v1/check-many-project-id", id=project_ids[i:i + 100])
            rows += data.get("trades") or []
        return rows


class Bot:
    def __init__(self, api: Waxpeer):
        self.api = api
        self.prices = {}
        self.prices_at = 0.0
        self.candidates = queue.Queue(maxsize=1000)
        self.pending = {}
        self.spent_today = 0
        self.day = date.today()

        me = api.user()
        link = parse_qs(urlparse(me["tradelink"] or "").query)
        if "partner" not in link or "token" not in link:
            raise SystemExit("Set your Steam trade link on waxpeer.com first")
        self.partner, self.token = link["partner"][0], link["token"][0]
        self.sell_fee = float(me.get("sell_fees") or 0.95)
        log.info("balance %s, dry_run=%s", usd(me["wallet"]), DRY_RUN)

    def refresh_prices(self):
        if time.time() - self.prices_at > PRICES_REFRESH_SEC:
            self.prices = self.api.prices()
            self.prices_at = time.time()
            log.info("loaded prices for %d names", len(self.prices))

    def is_deal(self, item: dict):
        # "hold" listings are still under a Steam trade lock, "manual" ones take up to 12 hours.
        if item.get("game") != GAME or item.get("delivery") not in ("instant", "regular"):
            return None
        ref = self.prices.get(item["name"])
        if not ref or ref["count"] < MIN_LISTINGS or item["price"] > to_units(MAX_PRICE_USD):
            return None
        market = ref["min"]  # cheapest listing at the last refresh; swap in another market's price here
        if item["price"] > market * (1 - MIN_DISCOUNT):
            return None
        profit = market * self.sell_fee - item["price"]
        if profit < to_units(MIN_PROFIT_USD):
            return None
        return market, profit

    def on_listing(self, item: dict):
        # Runs on the Socket.IO thread for every event, so only cheap checks here.
        if self.is_deal(item):
            try:
                self.candidates.put_nowait(item)
            except queue.Full:
                pass

    def try_buy(self, item: dict):
        deal = self.is_deal(item)
        if not deal:
            return
        market, profit = deal
        item_id, price = str(item["item_id"]), item["price"]
        if date.today() != self.day:
            self.day, self.spent_today = date.today(), 0
        if self.spent_today + price > to_units(DAILY_BUDGET_USD):
            log.info("daily budget reached, skip %s", item["name"])
            return

        live = self.api.check_availability(item_id)
        if not live or not live.get("selling") or live.get("unlock_at") or live["price"] > price:
            return
        log.info("DEAL %s for %s (market %s, expected profit %s)",
                 item["name"], usd(price), usd(market), usd(profit))
        if DRY_RUN:
            return

        # Count the money and remember the project_id before calling: if the call dies on a
        # timeout, the purchase may still have gone through, and tracking will find it.
        project_id = f"bot-{uuid.uuid4().hex[:24]}"
        self.spent_today += price
        self.pending[project_id] = item["name"]
        res = self.api.buy(item_id, price, self.partner, self.token, project_id)
        if res.get("success"):
            log.info("bought %s for %s, purchase id %s", item["name"], usd(res.get("price", price)), res.get("id"))
        elif "already exists" not in (res.get("msg") or ""):
            self.spent_today -= price
            self.pending.pop(project_id, None)
            log.info("not bought %s: %s", item["name"], res.get("msg"))

    def track_trades(self):
        if not self.pending:
            return
        for t in self.api.trades(list(self.pending)):
            if not t.get("done"):
                continue
            name = self.pending.pop(t["project_id"], t["name"])
            if t["status"] == 5:
                log.info("completed: %s (Steam trade %s)", name, t.get("trade_id"))
            else:
                log.info("cancelled: %s (%s)", name, t.get("reason"))

    def worker(self):
        last_track = 0.0
        while True:
            try:
                self.refresh_prices()
                if time.time() - last_track > 30:
                    self.track_trades()
                    last_track = time.time()
                self.try_buy(self.candidates.get(timeout=1))
            except queue.Empty:
                continue
            except Exception:
                log.exception("worker error")
                time.sleep(5)


def main():
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
    if not API_KEY:
        raise SystemExit("Set WAXPEER_API_KEY (waxpeer.com > Profile > Security)")
    bot = Bot(Waxpeer(API_KEY))
    bot.refresh_prices()
    threading.Thread(target=bot.worker, daemon=True).start()

    sio = socketio.Client(reconnection=True)

    @sio.event
    def connect():
        sio.emit("sub", {"name": GAME})
        log.info("listening for new %s listings", GAME)

    @sio.on("new")
    def on_new(item):
        bot.on_listing(item)

    @sio.on("update")
    def on_update(item):
        bot.on_listing(item)  # price drops arrive as updates

    sio.connect("https://waxpeer.com", transports=["websocket"])
    sio.wait()


if __name__ == "__main__":
    main()
```

```javascript
// Waxpeer CS2 trading bot: watch new listings, buy the ones priced well below the market.
//
// npm install socket.io-client
// WAXPEER_API_KEY=... node trading-bot.mjs            # dry run: logs deals, buys nothing
// WAXPEER_API_KEY=... DRY_RUN=0 node trading-bot.mjs  # buys for real
import { randomUUID } from 'node:crypto';
import { setTimeout as sleep } from 'node:timers/promises';
import { io } from 'socket.io-client';

const API_URL = process.env.WAXPEER_API_URL || 'https://api.waxpeer.com';
const API_KEY = process.env.WAXPEER_API_KEY || '';
const DRY_RUN = process.env.DRY_RUN !== '0';

const GAME = 'csgo';
const MIN_DISCOUNT = 0.15; // listing must be at least 15% below the cheapest other listing
const MIN_PROFIT_USD = 1; // expected profit after the sell fee
const MIN_LISTINGS = 20; // skip illiquid names
const MAX_PRICE_USD = 100; // most the bot pays for one item
const DAILY_BUDGET_USD = 300; // most the bot spends per day
const PRICES_REFRESH_SEC = 120;

const log = (...args) => console.log(new Date().toISOString(), ...args);
const usd = units => `$${(units / 1000).toFixed(2)}`;
const toUnits = dollars => Math.round(dollars * 1000);

class Waxpeer {
  constructor(apiKey) {
    this.apiKey = apiKey;
  }

  async get(path, params = {}) {
    const url = new URL(API_URL + path);
    for (const [key, value] of Object.entries(params)) {
      for (const v of [value].flat()) url.searchParams.append(key, v);
    }
    if (this.apiKey) url.searchParams.set('api', this.apiKey);
    for (let attempt = 0; attempt < 5; attempt++) {
      const res = await fetch(url, { signal: AbortSignal.timeout(20_000) });
      if (res.status === 429) {
        await sleep(Number(res.headers.get('retry-after') || 5) * 1000);
        continue;
      }
      if (!res.ok) throw new Error(`${path}: HTTP ${res.status}`);
      return await res.json();
    }
    throw new Error(`${path}: still rate limited`);
  }

  async user() {
    const data = await this.get('/v1/user');
    if (!data.success) throw new Error(`/v1/user: ${data.msg}`);
    return data.user;
  }

  async prices() {
    const data = await this.get('/v1/prices', { game: GAME });
    return new Map(data.items.map(row => [row.name, row]));
  }

  async checkAvailability(itemId) {
    const data = await this.get('/v1/check-availability', { item_id: itemId });
    return (data.items || []).find(row => String(row.item_id) === itemId);
  }

  async buy(params) {
    try {
      return await this.get('/v1/buy-one-p2p', params);
    }
    catch (err) {
      if (err.name !== 'TimeoutError') throw err;
      // Same project_id: if the first request went through, this one is refused and charges nothing.
      return await this.get('/v1/buy-one-p2p', params);
    }
  }

  async trades(projectIds) {
    const rows = [];
    for (let i = 0; i < projectIds.length; i += 100) {
      const data = await this.get('/v1/check-many-project-id', { id: projectIds.slice(i, i + 100) });
      rows.push(...(data.trades || []));
    }
    return rows;
  }
}

class Bot {
  prices = new Map();
  pricesAt = 0;
  candidates = [];
  pending = new Map();
  spentToday = 0;
  day = new Date().toDateString();

  constructor(api) {
    this.api = api;
  }

  async init() {
    const me = await this.api.user();
    const link = URL.canParse(me.tradelink || '') ? new URL(me.tradelink).searchParams : new URLSearchParams();
    this.partner = link.get('partner');
    this.token = link.get('token');
    if (!this.partner || !this.token) throw new Error('Set your Steam trade link on waxpeer.com first');
    this.sellFee = Number(me.sell_fees || 0.95);
    log(`balance ${usd(me.wallet)}, dry run: ${DRY_RUN}`);
    await this.refreshPrices();
  }

  async refreshPrices() {
    if (Date.now() - this.pricesAt < PRICES_REFRESH_SEC * 1000) return;
    this.prices = await this.api.prices();
    this.pricesAt = Date.now();
    log(`loaded prices for ${this.prices.size} names`);
  }

  isDeal(item) {
    // "hold" listings are still under a Steam trade lock, "manual" ones take up to 12 hours.
    if (item.game !== GAME || !['instant', 'regular'].includes(item.delivery)) return null;
    const ref = this.prices.get(item.name);
    if (!ref || ref.count < MIN_LISTINGS || item.price > toUnits(MAX_PRICE_USD)) return null;
    const market = ref.min; // cheapest listing at the last refresh; swap in another market's price here
    if (item.price > market * (1 - MIN_DISCOUNT)) return null;
    const profit = market * this.sellFee - item.price;
    if (profit < toUnits(MIN_PROFIT_USD)) return null;
    return { market, profit };
  }

  onListing(item) {
    // Runs for every feed event, so only cheap checks here.
    if (this.candidates.length < 1000 && this.isDeal(item)) this.candidates.push(item);
  }

  async tryBuy(item) {
    const deal = this.isDeal(item);
    if (!deal) return;
    const itemId = String(item.item_id);
    const price = item.price;
    const today = new Date().toDateString();
    if (today !== this.day) {
      this.day = today;
      this.spentToday = 0;
    }
    if (this.spentToday + price > toUnits(DAILY_BUDGET_USD)) {
      log(`daily budget reached, skip ${item.name}`);
      return;
    }

    const live = await this.api.checkAvailability(itemId);
    if (!live?.selling || live.unlock_at || live.price > price) return;
    log(`DEAL ${item.name} for ${usd(price)} (market ${usd(deal.market)}, expected profit ${usd(deal.profit)})`);
    if (DRY_RUN) return;

    // Count the money and remember the project_id before calling: if the call dies on a
    // timeout, the purchase may still have gone through, and tracking will find it.
    const projectId = `bot-${randomUUID().replaceAll('-', '').slice(0, 24)}`;
    this.spentToday += price;
    this.pending.set(projectId, item.name);
    const res = await this.api.buy({
      item_id: itemId,
      price,
      partner: this.partner,
      token: this.token,
      project_id: projectId,
    });
    if (res.success) {
      log(`bought ${item.name} for ${usd(res.price ?? price)}, purchase id ${res.id}`);
    }
    else if (!res.msg?.includes('already exists')) {
      this.spentToday -= price;
      this.pending.delete(projectId);
      log(`not bought ${item.name}: ${res.msg}`);
    }
  }

  async trackTrades() {
    if (!this.pending.size) return;
    for (const t of await this.api.trades([...this.pending.keys()])) {
      if (!t.done) continue;
      const name = this.pending.get(t.project_id) ?? t.name;
      this.pending.delete(t.project_id);
      if (t.status === 5) log(`completed: ${name} (Steam trade ${t.trade_id})`);
      else log(`cancelled: ${name} (${t.reason})`);
    }
  }

  async run() {
    let lastTrack = 0;
    while (true) {
      try {
        await this.refreshPrices();
        if (Date.now() - lastTrack > 30_000) {
          await this.trackTrades();
          lastTrack = Date.now();
        }
        const item = this.candidates.shift();
        if (item) await this.tryBuy(item);
        else await sleep(50);
      }
      catch (err) {
        log('worker error:', err);
        await sleep(5000);
      }
    }
  }
}

if (!API_KEY) {
  console.error('Set WAXPEER_API_KEY (waxpeer.com > Profile > Security)');
  process.exit(1);
}

const bot = new Bot(new Waxpeer(API_KEY));
await bot.init();

const socket = io('https://waxpeer.com', { transports: ['websocket'] });
socket.on('connect', () => {
  socket.emit('sub', { name: GAME });
  log(`listening for new ${GAME} listings`);
});
socket.on('new', item => bot.onListing(item));
socket.on('update', item => bot.onListing(item)); // price drops arrive as updates

await bot.run();
```

## Reselling what you bought

To sell an item on Waxpeer, list it with [`POST /v1/list-items-steam`](/api/sell-items/list-items-steam-post) (up to 50 items per request) and change its price with [`POST /v1/edit-items`](/api/sell-items/edit-items). Selling needs one more setup step than buying: your listings sell as `regular` only while your account is online, which means sending a fresh Steam access token and keeping the trade WebSocket connected. While you are offline, new listings stay paused and live ones switch to `manual`. [Going online](/authentication#going-online) explains how. Items you receive are covered by Steam Trade Protection; see [Trade statuses](/statuses) for how the hold affects a trade.

## Rate limits

Some endpoints, such as search and buy order changes, answer `429 Too Many Requests` with a `Retry-After` header when you go over a limit. The script waits that many seconds and retries. Other limits come back as a normal answer:

- Purchases answer `success: false` with a `msg` that starts with `Too many requests`.
- Listing or editing the same item is limited to 2 requests per 120 seconds. A third request returns the item in `failed` with `You can update price after N seconds`.
- Creating, editing and removing buy orders is limited to 10 requests per 10 seconds.

Use the Socket.IO feed instead of polling item lists in a loop: it is faster and it costs you nothing against these limits.

## Going further

- **Buy orders.** Instead of chasing listings, place standing orders that fill when a seller accepts your price: [`POST /v1/create-buy-order`](/api/buy-order/create-buy-order).
- **Many listings at once.** [`POST /v1/check-availability`](/api/buy-items/check-availability-post) checks up to 1,000 item ids per request and returns float, paint index, phase and sticker names.
- **Float and stickers.** Feed events carry `float`, `paint_index`, `phase` and `sticker_names`, so a bot can also hunt for rare patterns rather than low prices.
- **Everything else.** The [API reference](/get-started) lists all endpoints, and [`/llms.txt`](/llms.txt) indexes these docs for AI assistants.
