News
New 1-Click Apps are now available in the Serverspace control panel
AC
May 26 2026
Updated May 28 2026

How to Build a Trading Bot in Python and Run It on a VPS

Linux Ubuntu Web server

A trading bot is a program that watches a market, applies rules, and sends orders to an exchange through an API. People who want to know how to build a trading bot usually run into the same problem fast. Writing the strategy is one piece. Keeping it running 24/7 is another. Markets do not pause, and a laptop that goes to sleep at 2 a.m. misses every signal that happens overnight. This guide walks through the full path: pick a stack, choose a strategy, write a working example in Python, and deploy it on a Linux VPS so it runs without supervision. The goal is to show how to build a cryptocurrency trading bot you understand from top to bottom.

What a Trading Bot Actually Does (and What It Does Not)

At its core, a trading bot is an execution system. It reads market data, runs the numbers, checks rules, and places orders. If the rules are weak, the bot will simply execute weak trades faster than a human could. Automation amplifies the strategy. It does not invent one.

Bots come in a few common shapes. Rule based bots follow fixed logic, like buying when RSI drops below 30. Signal based bots react to alerts from TradingView or other providers. AI assisted bots use machine learning models on top of standard indicators. Custom coded bots in Python give the most flexibility and are what most serious traders eventually move to. The category we cover in this how to build a trading bot tutorial is the custom coded one. A bot will not predict black swan events. It does exactly what its code says, on every tick. That predictability is the advantage and also the risk.

Why Python and a VPS Form the Standard Stack for Automated Trading

Python became the default language for retail and institutional algo trading because the ecosystem is hard to beat. Pandas and NumPy handle time series data with very little code. Libraries like ccxt, alpaca-py, and ib_insync wrap exchange APIs into clean Python objects. TA-Lib and pandas-ta cover more than 150 technical indicators out of the box. C++ wins for high frequency trading where microseconds matter, but for the strategies most retail traders run, Python is fast enough and far more productive.

The second half of the stack is infrastructure. Crypto markets trade 24/7. Stock and futures markets still run during your sleep and your commute. A bot on a laptop competes with system updates, Wi-Fi drops, and a lid that closes when you leave the room. A virtual private server removes all of that. The bot runs on a remote Linux box with a stable connection, predictable resources, and uptime measured against an SLA.

Latency matters too. A VPS placed near the exchange data center cuts round trip time to a few milliseconds. For a Binance bot, a server in Tokyo or Frankfurt can reach the API in under two milliseconds. Cloud providers like Serverspace spin up a Linux VPS in under a minute in regions close to the major exchanges, which is enough infrastructure for most strategies that are not pure HFT.

Five Trading Bot Strategies, Compared by Market Conditions

Before writing code, pick a strategy that matches the market you want to trade. Each approach has a personality. Trend followers love directional moves and suffer in chop. Mean reversion bots are the opposite. DCA bots ignore market timing entirely. The table below maps the five most common strategies to the conditions where each one tends to work.

Strategy How it works Works best in Pros Cons
Trend following (SMA crossover) Buy when short SMA crosses above long SMA, sell on reverse cross Strong directional moves Simple logic, easy to backtest, catches big trends Whipsaws in sideways markets, late entries and exits
Mean reversion (RSI) Buy when RSI falls below 30, sell when it climbs above 70 Range bound or sideways markets Many trade opportunities, defined entry signals Bleeds money in trending markets, hard stop losses essential
DCA Buy a fixed amount on a fixed schedule, no timing Long term accumulation, any market Removes emotion, easy to automate, good for beginners No edge over manual DCA, not a short term strategy
Grid trading Place buy and sell orders at fixed price intervals Low volatility, ranging markets Profits from oscillation, no directional guess needed Large drawdown if price breaks the range, capital intensive
Arbitrage Exploit price gaps between exchanges or instruments Fragmented markets with latency edges Theoretically market neutral, no view on direction Needs low latency, fees and transfer times kill thin spreads

For this guide we will build an SMA crossover bot. The logic is the easiest to explain and to verify visually on a chart, which makes it a good first project. Once the pipeline works, swapping in RSI or another rule set is a small change.

Choosing an Exchange and Connecting Through ccxt

The exchange you pick determines which API library to use. For crypto, ccxt is the practical default. It is a Python library that wraps more than a hundred exchanges behind the same interface, so the same code can talk to Binance, Coinbase, Kraken, Bybit, and OKX with only a one line change. This is the foundation of any how to build a trading bot python ccxt tutorial worth reading.

For US stocks and ETFs, Alpaca is the cleanest starting point and the answer to how to build a stock trading bot without paying commissions. It offers a paper trading sandbox, an API first design, and zero commission orders. For options and futures, Interactive Brokers through ib_insync is the institutional choice. For currency pairs and how to build a forex trading bot, OANDA and MetaTrader 4/5 bridges are the usual paths.

We will use Binance Testnet for this guide. It is a full replica of the production exchange that runs on fake balances, with no KYC. Sign up at testnet.binance.vision, generate an API key, and you are ready to write code without risking a cent. Two security rules matter from day one. First, never grant withdrawal permission to a bot key, only trading and reading. Second, if the exchange supports IP whitelisting, enable it and lock the key to your VPS address before going live.

Building a Simple SMA Crossover Bot Step by Step

Here is where we move from theory to a working script. The bot will pull recent candles from Binance Testnet, compute two simple moving averages, and place a market order when they cross. This section is the core of how to build a crypto trading bot in the simplest reproducible form.

Setting up the Python environment

Create a project folder, set up a virtual environment, and install the three libraries we need. A virtual environment keeps dependencies isolated from your system Python, which prevents version conflicts later.

mkdir trading-bot && cd trading-bot

python3 -m venv venv

source venv/bin/activate

pip install ccxt pandas python-dotenv

Three packages cover the whole bot. ccxt talks to the exchange, pandas crunches the candle data, and python-dotenv loads API keys from a file instead of hardcoding them in the script.

Storing API keys safely with .env

Create a file called .env in the project folder. Add your testnet credentials. Then add .env to your .gitignore so you never commit it by accident. This single habit prevents the most common way trading bot accounts get drained, which is leaking keys to a public repository.

BINANCE_API_KEY=your_testnet_key_here

BINANCE_SECRET=your_testnet_secret_here

Fetching market data from the exchange

The first script connects to Binance Testnet and downloads recent candles for a symbol. Each candle is one OHLCV record: open price, high, low, close, and volume over a time window. We will pull one hour candles for BTC/USDT.

import ccxt, os, pandas as pd

from dotenv import load_dotenv

load_dotenv()

exchange = ccxt.binance({

"apiKey": os.getenv("BINANCE_API_KEY"),

"secret": os.getenv("BINANCE_SECRET"),

"enableRateLimit": True,

})

exchange.set_sandbox_mode(True)

ohlcv = exchange.fetch_ohlcv("BTC/USDT", "1h", limit=100)

df = pd.DataFrame(ohlcv, columns=["ts","open","high","low","close","volume"])

The set_sandbox_mode call points ccxt at testnet endpoints. Drop that line later for live trading.

Calculating SMA signals

Add two moving averages to the dataframe. A 20 period SMA is the fast signal, a 50 period SMA is the slow one. A long position opens when the fast SMA crosses above the slow SMA. The position closes on the opposite cross.

df["sma_fast"] = df["close"].rolling(20).mean()

df["sma_slow"] = df["close"].rolling(50).mean()

df["signal"] = 0

df.loc[df["sma_fast"] > df["sma_slow"], "signal"] = 1

df.loc[df["sma_fast"] < df["sma_slow"], "signal"] = -1

Plain English: when the recent average price runs above the longer term average, the short term trend is up, so the bot wants to be long. When it slips back below, the trend has turned, so the bot exits.

Placing orders safely with size limits

Never let the bot bet the whole account on one trade. Define a position size as a fixed percentage of the balance, and wrap every API call in try except. Real exchanges fail for many reasons: rate limits, brief outages, expired keys. The bot has to survive all of them.

def place_buy(symbol, usdt_amount):

try:

price = exchange.fetch_ticker(symbol)["last"]

qty = round(usdt_amount / price, 5)

order = exchange.create_market_buy_order(symbol, qty)

return order

except Exception as e:

print(f"order failed: {e}")

return None

Risk management lives here. A common rule is to risk no more than 1 to 2 percent of the account on a single trade. If the strategy can lose 50 trades in a row and still leave most of the account intact, the math is on your side.

Putting it all together in a main loop

The main loop ties everything into a continuous cycle. Fetch candles, calculate signals, check the current position, place an order if the signal changed, log the action, and sleep before the next iteration. For an hourly strategy, polling every minute is more than enough.

import time, logging

logging.basicConfig(filename="bot.log", level=logging.INFO)

position = 0

while True:

try:

df = get_candles("BTC/USDT")

signal = df["signal"].iloc[-1]

if signal == 1 and position == 0:

place_buy("BTC/USDT", 100)

position = 1

elif signal == -1 and position == 1:

place_sell("BTC/USDT", 100)

position = 0

logging.info(f"loop ok, signal={signal}")

except Exception as e:

logging.error(f"loop error: {e}")

time.sleep(60)

For scalping or anything faster than one minute candles, replace the polling loop with a WebSocket stream. ccxt has a ccxt.pro version that handles real time data with persistent connections, which is the right tool for sub second logic.

Deploying the Bot on a Linux VPS for 24/7 Operation

A working script on your laptop is half the project. The other half is putting it on a server that runs around the clock. The remaining sections of this how to build a trading bot guide cover server choice, secure setup, and a systemd service that keeps the bot alive through crashes and reboots.

Choosing a VPS that fits a trading bot

A starter bot does not need expensive hardware. Two virtual CPU cores, 2 to 4 GB of RAM, and 30 to 50 GB of SSD storage cover most strategies. Ubuntu 22.04 LTS or 24.04 LTS is the standard image. Linux uses about 1 GB of RAM at idle, while Windows Server can eat 4 to 8 GB just to run the desktop, so Linux frees up resources for the bot.

Location matters more than raw specs. A Frankfurt or Amsterdam server reaches Binance EU endpoints in 1 to 2 milliseconds. A Tokyo VPS gets similar numbers to Binance Asia. For Alpaca and US brokers, look at New York or New Jersey. Serverspace USA VPS runs data centers in the United States, Europe, and Asia and provisions Linux VPS instances in around 40 seconds, which makes it straightforward to put a bot close to whatever exchange you target. Plans start small and scale up as the strategy grows.

Initial server setup over SSH

After the VPS is provisioned, the panel shows the public IP and a root password. Connect over SSH from your local machine.

ssh root@your-server-ip

apt update && apt upgrade -y

adduser botuser

usermod -aG sudo botuser

Working as root is dangerous because any mistake can wipe the system. Create a regular user, give it sudo rights, and log in as that user from now on.

Securing the server before anything else

Three steps lock down the box. Generate an SSH key on your laptop, copy the public key to the server, then disable password login. After that, set up a firewall that allows only SSH inbound. A trading bot does not need any inbound ports open because it initiates outbound connections to the exchange API.

ssh-keygen -t ed25519

ssh-copy-id botuser@your-server-ip

sudo ufw allow OpenSSH

sudo ufw enable

Edit /etc/ssh/sshd_config and set PasswordAuthentication to no, then restart the SSH service. The server is now reachable only with your private key.

Installing Python and project dependencies

Ubuntu ships with Python 3, but you still need pip and venv. Upload the bot script with scp or clone it from a private Git repo, then build the same virtual environment you used locally.

sudo apt install python3-pip python3-venv -y

mkdir ~/tradingbot && cd ~/tradingbot

python3 -m venv venv

source venv/bin/activate

pip install -r requirements.txt

Create the .env file directly on the server with nano. Do not push it through Git. The closer the API key stays to the machine that uses it, the smaller the blast radius if something leaks.

Running the bot 24/7 with systemd

systemd is the Linux service manager. A small unit file tells it to run the bot at boot, restart it if it crashes, and stream its output to the system journal. This step is what separates a one off script from a production deployment.

sudo nano /etc/systemd/system/tradingbot.service

Paste a minimal unit file like the one below, adjust paths, save, and enable the service.

[Unit]

Description=Trading Bot

After=network.target

 

[Service]

User=botuser

WorkingDirectory=/home/botuser/tradingbot

ExecStart=/home/botuser/tradingbot/venv/bin/python bot.py

Restart=on-failure

RestartSec=10

 

[Install]

WantedBy=multi-user.target

sudo systemctl enable tradingbot

sudo systemctl start tradingbot

journalctl -u tradingbot -f

Now the bot survives crashes, server reboots, and SSH disconnects. The last command tails its live log so you can confirm everything works.

Mistakes That Quietly Drain Trading Bot Accounts

Most blown accounts trace back to the same handful of mistakes. Knowing them in advance is the cheapest insurance available.

Overfitting on backtest. A strategy that returns 400 percent on five years of history often loses money in live trading because it was tuned to noise. Use walk forward optimization and reserve unseen data for the final test.

Ignoring fees and slippage. Commissions and slippage eat 10 to 15 percent of paper profits in a real environment. Subtract them in every backtest.

No stop loss or position sizing. One outsized loss can wipe months of gains. Hard limits on per trade risk and a server side stop loss order prevent the worst outcomes.

Hardcoded API keys. Keys in the script, keys in a committed config file, keys in a public GitHub repo. All are common and all are fatal. Use .env, add it to .gitignore, disable withdrawal permission, and turn on IP whitelisting on the exchange.

Going live with no testnet time. Two to four weeks on a testnet or paper account is the minimum. The bot should survive a sharp price move during that window without breaking.

No error handling. A single network blip will crash a bot that has no try except around its API calls. Add retries with backoff and log every failure. Consider a Telegram alert for unrecoverable errors.

Running the script with nohup in an SSH session. The bot dies when the session closes for good. systemd, screen, or Docker are the real options.

Five Practical Scenarios Where Trading Bots Outperform Manual Trading

The cases below cover the most common reasons people learn how to build a trading bot in the first place.

Scheduled DCA on crypto. A bot buys a fixed dollar amount of BTC every week regardless of price. Boring on purpose, which removes emotion and discipline failures.

Grid trading in a range. When a market chops between two levels, a grid bot stacks buy orders below the price and sell orders above. Every oscillation books a small profit, which explains why people search for how to build a bitcoin trading bot during sideways months.

Trend following on equities. An SMA crossover on daily candles for SPY or AAPL, executed through Alpaca. The bot ignores intraday noise and acts only on confirmed trend shifts. For anyone curious how to build a stock trading bot without a broker terminal, this is the starter project.

Cross exchange arbitrage. Two crypto exchanges show a 0.4 percent gap on the same pair. A bot using ccxt watches both order books and trades the spread, after subtracting fees and transfer time. A low latency VPS is mandatory.

Signal execution. A TradingView alert fires when a custom indicator triggers. A small Flask endpoint on the VPS catches the webhook, validates it, and forwards the trade. The pattern works for crypto, forex pairs, and US stocks alike.

Pre Launch Checklist Before You Switch from Testnet to Live

Run through every item below before pointing the bot at a real funded account. None of these checks take long. Skipping them is what people regret later.

Check Why it matters
30+ days of stable testnet results Short runs hide bugs that only show up over time and across market regimes
Strategy survived a 5 percent intraday move Confirms the risk rules actually trigger when volatility spikes
Clean logs, no recurring errors Repeated exceptions in logs mean the bot is one bad day away from a crash
Stop loss tested by manual trigger A stop you never fired in testing is a stop you cannot trust in production
API key without withdrawal permission Limits damage if the key leaks, since funds cannot be moved off the exchange
.env file outside Git Public repos with leaked keys get scraped by bots within minutes
systemd service auto restarts after manual kill Proves the service definition is correct before you depend on it
Telegram or email alert on critical errors Lets you react in minutes instead of hours when something breaks
Position sizing limits hardcoded Caps the worst case on any single trade, regardless of signal logic
Initial live capital small enough to lose Reality usually finds at least one bug paper trading missed

Conclusion: From Testnet to Real Trades

A trading bot is two things stacked together. The first is the strategy, a clear set of rules you can defend in plain English. The second is the infrastructure, the code and the server that turn rules into orders without supervision. We covered both, from a working SMA crossover script in Python to a systemd service running on a Linux VPS.

Next steps are simple. Run the bot on Binance Testnet for at least a month. Watch the logs daily. Survive at least one sharp move without losing your stop loss. Then provision a production VPS, copy the project over, and start live with a small amount. Serverspace offers Linux and Windows VPS options across multiple regions with quick deployment and pay as you go pricing, which fits the way most traders scale from one bot to several.

FAQ

How much money do I need to start?

Zero for testnet. For live, $100 to $500 is enough to validate that the bot behaves the same on real fills as on paper. Scale up only after a few months of stable returns. Starting big is the fastest way to discover bugs the expensive way.

Is it legal to run a trading bot?

In most jurisdictions yes, and exchanges officially publish APIs for that purpose. In the United States, pattern day trader rules apply to bots that trade equities with leverage on small accounts. Check the rules of your broker and your local regulator before going live.

Can I run several bots on the same VPS?

Yes, as long as the resources stretch. Each bot should live in its own virtual environment with its own systemd service, so a crash in one cannot take down the others. Two or three light bots fit on a 4 GB VPS. Heavier strategies with machine learning models need more RAM and CPU.

Vote:
5 out of 5
Аverage rating : 5
Rated by: 1
33401 West Palm Beach, FL 700 S Rosemary Ave, Suite 204
+1 302 425-97-76
700 300
ITGLOBAL.COM CORP | All rights reserved
700 300

You might also like...

We use cookies to make your experience on the Serverspace better. By continuing to browse our website, you agree to our
Use of Cookies and Privacy Policy.