Skip to content

Build a trading bot

A small Python bot for Nexwest perpetuals: read prices and your position, place post-only buys on a schedule, cap your risk and test it safely first.

Updated Nov 14, 2026Traders & developers6 min read
On this page

This guide builds a small, complete trading bot in Python. It buys a fixed amount of Bitcoin every hour with a limit order just below the market, a strategy often called dollar-cost averaging, and stops buying once the position reaches a size you set. You can change the market, amount and timing, then use the same building blocks for your own ideas.

You need a funded Nexwest trading account, Python 3.10 or later, and about 20 minutes. No market-making experience is needed.

Trading bots can lose money

A bot trades with real funds and does exactly what its code says, including mistakes. Start in dry-run mode, then trade the smallest size, and watch it before you leave it running.

1. Create a key

  1. Open the API keys page and connect the wallet you trade with.
  2. Pick Read only for your first test. Create a Read & trade key once the bot reads everything correctly.
  3. Choose an expiry. If the bot will run on a server, add the server's IP address to the allow list.
  4. Click Copy as .env and save the three lines in a file named .env next to your bot. Never commit it or share it.
code
NEXWEST_ACCOUNT_ID=0x...
NEXWEST_API_KEY=ed25519:...
NEXWEST_API_SECRET=...

2. Install the libraries

code
pip install requests base58 cryptography python-dotenv

3. Connect and read your account

Every private request is signed with your secret. This helper does it for you, and stops with a clear message when the API refuses a request.

code
import base64, json, os, time
 
import base58
import requests
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from dotenv import load_dotenv
 
load_dotenv()
BASE_URL = "https://api.orderly.org"
ACCOUNT_ID = os.environ["NEXWEST_ACCOUNT_ID"]
API_KEY = os.environ["NEXWEST_API_KEY"]
SECRET = base58.b58decode(os.environ["NEXWEST_API_SECRET"].removeprefix("ed25519:"))
PRIVATE_KEY = Ed25519PrivateKey.from_private_bytes(SECRET)
 
 
def public(path):
    """Market data: no key needed."""
    response = requests.get(BASE_URL + path, timeout=10)
    response.raise_for_status()
    return response.json()["data"]
 
 
def signed(method, path, body=None):
    """Your account: every request is signed with the API secret."""
    payload = "" if body is None else json.dumps(body, separators=(",", ":"))
    timestamp = str(int(time.time() * 1000))
    signature = PRIVATE_KEY.sign(f"{timestamp}{method}{path}{payload}".encode())
    headers = {
        "orderly-account-id": ACCOUNT_ID,
        "orderly-key": API_KEY,
        "orderly-timestamp": timestamp,
        "orderly-signature": base64.urlsafe_b64encode(signature).decode(),
        "Content-Type": "application/json"
        if method in ("POST", "PUT")
        else "application/x-www-form-urlencoded",
    }
    response = requests.request(
        method, BASE_URL + path, headers=headers, data=payload or None, timeout=10
    )
    if response.status_code == 429:
        raise RuntimeError("Rate limit reached. Wait a moment, then try again.")
    result = response.json()
    if not result.get("success"):
        raise RuntimeError(f"{result.get('code')}: {result.get('message')}")
    return result.get("data")
 
 
if __name__ == "__main__":
    mark = public("/v1/public/futures/PERP_BTC_USDC")["mark_price"]
    account = signed("GET", "/v1/positions")
    print("BTC mark price:", mark)
    print("Free collateral:", account["free_collateral"], "USDC")
    for row in account["rows"]:
        print(row["symbol"], row["position_qty"], "at", row["average_open_price"])

Save it as nexwest.py and run python nexwest.py. You should see the Bitcoin price, your free collateral and any open positions. If you get an authentication error, check the three values in .env and that your computer's clock is correct.

4. Respect the market's rules

Each market has a price step, a size step and a minimum order value. Orders that do not follow them are rejected, so the bot rounds every order first. The rules come from /v1/public/info/{symbol}:

FieldMeaningBTC example
quote_tickPrice step0.1
base_tickSize step0.00001
min_notionalMinimum order value in USDC10

5. The bot

Create dca_bot.py next to nexwest.py:

code
"""Buys ORDER_USDC of SYMBOL every INTERVAL seconds with a post-only limit
order just below the mark price, until the position is worth MAX_POSITION_USDC.
"""
import time
from decimal import ROUND_DOWN, Decimal
 
import requests
 
from nexwest import public, signed
 
SYMBOL = "PERP_BTC_USDC"
ORDER_USDC = 20  # size of each buy
MAX_POSITION_USDC = 200  # stop buying at this position value
INTERVAL = 3600  # seconds between buys
DISCOUNT = 0.001  # bid 0.1% below the mark price
DRY_RUN = True  # print orders instead of sending them
 
 
def to_step(value, step):
    """Round down to the market's step, without float noise."""
    step = Decimal(str(step))
    return float((Decimal(str(value)) / step).to_integral_value(ROUND_DOWN) * step)
 
 
def position_value():
    for row in signed("GET", "/v1/positions")["rows"]:
        if row["symbol"] == SYMBOL:
            return abs(float(row["position_qty"])) * float(row["mark_price"])
    return 0.0
 
 
def buy_once():
    """Places one buy and returns its client order ID, or None."""
    rules = public(f"/v1/public/info/{SYMBOL}")
    mark = float(public(f"/v1/public/futures/{SYMBOL}")["mark_price"])
    held = position_value()
    if held + ORDER_USDC > MAX_POSITION_USDC:
        print(f"Position is {held:.2f} USDC, at the cap. Not buying.")
        return None
 
    price = to_step(mark * (1 - DISCOUNT), rules["quote_tick"])
    quantity = to_step(ORDER_USDC / price, rules["base_tick"])
    if quantity * price < float(rules["min_notional"]):
        print(f"Raise ORDER_USDC: the minimum order is {rules['min_notional']} USDC.")
        return None
 
    order = {
        "symbol": SYMBOL,
        "side": "BUY",
        "order_type": "POST_ONLY",  # pays the maker fee, never fills as a taker
        "order_price": price,
        "order_quantity": quantity,
        "client_order_id": f"dca-{int(time.time())}",
    }
    if DRY_RUN:
        print("Dry run, would send:", order)
        return None
    result = signed("POST", "/v1/order", order)
    print(f"Bid {quantity} BTC at {price}, order {result['order_id']}")
    return order["client_order_id"]
 
 
def cancel(client_order_id):
    try:
        signed("DELETE", f"/v1/client/order?client_order_id={client_order_id}&symbol={SYMBOL}")
    except RuntimeError:
        pass  # it filled or was already cancelled
 
 
def main():
    last_id = None
    try:
        while True:
            if last_id:
                cancel(last_id)  # replace last round's bid if it did not fill
            try:
                last_id = buy_once()
            except (requests.RequestException, RuntimeError) as error:
                last_id = None
                print("Skipped this round:", error)
            time.sleep(INTERVAL)
    except KeyboardInterrupt:
        if last_id:
            cancel(last_id)
        print("Bot stopped.")
 
 
if __name__ == "__main__":
    main()

What it does each round:

  1. Cancels last round's bid if it did not fill, so only one bot order rests at a time.
  2. Reads the market's rules, the mark price and your position.
  3. Skips the round when the position would grow past MAX_POSITION_USDC.
  4. Places a post-only buy 0.1% below the mark price, rounded to the market's steps. Post-only orders pay the 0.02% maker fee and are rejected rather than filling as a taker.

Each order carries a client_order_id that starts with dca-, so you can tell the bot's orders apart from your own in the terminal.

6. Test it, then go live

  1. Dry run. Run python dca_bot.py with DRY_RUN = True. It prints the order it would send. Check the price and size, then stop it with Ctrl+C. To test faster, set INTERVAL = 60 for a few rounds.
  2. Smallest size. Create a read and trade key, set DRY_RUN = False and ORDER_USDC to just above the market's minimum. Watch the order appear in the terminal.
  3. Your settings. Set the amount, the cap and the interval you want. Keep MAX_POSITION_USDC at or below your deposit to stay at about 1× effective leverage.
  4. Keep it running. Run the bot on a server or an always-on computer, for example with nohup python dca_bot.py & or as a system service, and add the server's IP address to the key's allow list.

To stop the bot, press Ctrl+C: it cancels its open bid. To stop all trading at once, remove the key on the API keys page; it stops working immediately.

Make it your own

  • Another market. Change SYMBOL, for example to PERP_ETH_USDC, PERP_NVDA_USDC or PERP_XAU_USDC (gold). The bot reads each market's rules itself.
  • Sell on a target. Add a sell limit order with "reduce_only": true above your average entry price, so it can only close the position.
  • A grid. Place several post-only buys below the price and reduce-only sells above it, and replace each one as it fills.
  • Your own signals. Read one-minute candles over the WebSocket stream and decide when to buy or sell in your own code.

The API reference lists every order type, field and stream, and the rate limits to stay under.

Rules that apply to bots

  • Bot trades pay the same fees as the terminal: 0.02% maker and 0.05% taker. See fees.
  • Bot trades earn Season 1 points like any other trade. Wash trading, trading between your own accounts and sybil accounts are excluded from rewards.
  • The terms of service apply. You may not use the API to open positions from restricted regions, including the United States and Canada.

Was this page helpful?