I Built a Self-Hosted Crypto Trading Agent That Never Sees the Internet (My Keys Stay Home)
When you use 3Commas, Cryptohopper, or any cloud crypto bot, you give them three things:
- Your exchange API keys
- Your trading strategy
- Your complete trading history
All three live on their servers. You trust their security team to protect them. Sometimes that trust is betrayed.
In November 2022, 3Commas had a data incident. API keys for thousands of users were exposed. Funds were stolen. 3Commas initially denied it was their fault. They later admitted the keys were obtained through their platform.
That incident taught a generation of algo traders a lesson: your keys belong on your machine, not theirs.
This guide shows how to build a crypto trading agent that runs entirely on your local hardware. No cloud. No subscriptions. No third parties with access to your keys.
Not financial advice. Paper trading only. Run this in paper trading mode before considering any live deployment.
Why Local Matters More Than You Think
Cloud bots know your strategy.
When 3Commas or Cryptohopper executes your trades, they can see your entry/exit rules. Your competitive advantage — the specific parameters you tested and optimized — is visible to their engineering team and any attacker who compromises their systems.
Cloud bots know your portfolio.
Every position, every balance, every trade history flows through their servers. If their database is breached, your financial history is exposed.
Cloud bots hold your keys.
With withdraw permissions disabled, the risk is limited to trading losses. But many users grant withdraw permissions for convenience. That's the attack surface that caused real losses in 2022.
The local alternative:
Your API keys never leave your laptop. Your strategy runs in a Python script on your own machine. Your trade history lives in a local SQLite database. The only connection to the outside world is read-only market data fetches and order placement — and you control exactly what goes where.
What We're Building
An OpenClaw AI agent that:
- Monitors BTC/USDT on a 4-hour chart
- Detects trading signals using RSI + EMA indicators
- Runs entirely on your local machine
- Sends Telegram alerts when signals fire
- Logs everything to a local database
- Never stores your API keys in plaintext
Total cost: $0/month
Cloud dependency: None
External services: Binance API (read + trade only), Telegram bot (alerts only)
Setup (45 Minutes)
Step 1: Install OpenClaw
npm install -g openclaw
openclaw gateway start
This starts the local OpenClaw service. No account creation, no email required.
Step 2: Install Python Dependencies
pip install ccxt pandas ta python-dotenv
Step 3: Set Up Your API Keys (Securely)
Create a .env file in your project directory. Never commit this file to git.
# .env — NEVER SHARE THIS FILE
BINANCE_API_KEY=your_key_here
BINANCE_SECRET=your_secret_here
TELEGRAM_BOT_TOKEN=your_bot_token
TELEGRAM_CHAT_ID=your_chat_id
Add to .gitignore:
.env
*.db
paper_trades.db
Critical security step: Create a Binance API key with:
- ✅ Read info enabled
- ✅ Spot trading enabled (for paper/live trading)
- ❌ Withdraw disabled — always
- ❌ Futures disabled (unless explicitly needed)
- ✅ IP restriction: your home IP only
With no withdraw permission and an IP restriction, even if your key is somehow exposed, an attacker can't steal your funds — only see your balances and potentially place trades. That's still bad, but it's not catastrophic.
Step 4: The Core Agent
# crypto_agent.py
import os
import json
import sqlite3
import urllib.request
from datetime import datetime
from dotenv import load_dotenv
import ccxt
import pandas as pd
import ta
load_dotenv()
# Exchange setup — keys loaded from .env, never hardcoded
exchange = ccxt.binance({
"apiKey": os.getenv("BINANCE_API_KEY"),
"secret": os.getenv("BINANCE_SECRET"),
"enableRateLimit": True,
"options": {"defaultType": "spot"},
})
def fetch_data(symbol="BTC/USDT", timeframe="4h", limit=250):
"""Fetch OHLCV from Binance. No data stored on external servers."""
raw = exchange.fetch_ohlcv(symbol, timeframe, limit=limit)
df = pd.DataFrame(raw, columns=["ts","open","high","low","close","volume"])
df["datetime"] = pd.to_datetime(df["ts"], unit="ms")
df.set_index("datetime", inplace=True)
return df
def add_indicators(df):
df["rsi"] = ta.momentum.RSIIndicator(df["close"], 14).rsi()
df["ema_200"] = ta.trend.EMAIndicator(df["close"], 200).ema_indicator()
df["ema_50"] = ta.trend.EMAIndicator(df["close"], 50).ema_indicator()
return df.dropna()
def check_signal(df):
latest = df.iloc[-1]
price = latest["close"]
rsi = latest["rsi"]
ema200 = latest["ema_200"]
ema50 = latest["ema_50"]
if rsi < 35 and price > ema200:
return "BUY", price, rsi
elif rsi > 65 or price < ema200:
return "SELL", price, rsi
else:
return "HOLD", price, rsi
def send_telegram(message):
"""Send alert via Telegram. Your strategy logic stays local."""
token = os.getenv("TELEGRAM_BOT_TOKEN")
chat_id = os.getenv("TELEGRAM_CHAT_ID")
if not token or not chat_id:
print(f"[ALERT] {message}")
return
payload = {"chat_id": chat_id, "text": message, "parse_mode": "Markdown"}
data = json.dumps(payload).encode()
req = urllib.request.Request(
f"https://api.telegram.org/bot{token}/sendMessage",
data=data,
headers={"Content-Type": "application/json"}
)
urllib.request.urlopen(req, timeout=10)
def log_signal(signal, price, rsi):
"""Log everything locally. No cloud database."""
conn = sqlite3.connect("crypto_agent.db")
conn.execute("""
CREATE TABLE IF NOT EXISTS signals (
id INTEGER PRIMARY KEY,
timestamp TEXT,
signal TEXT,
price REAL,
rsi REAL
)
""")
conn.execute(
"INSERT INTO signals (timestamp, signal, price, rsi) VALUES (?,?,?,?)",
(datetime.utcnow().isoformat(), signal, price, rsi)
)
conn.commit()
conn.close()
def run():
print(f"[{datetime.utcnow().strftime('%Y-%m-%d %H:%M')} UTC] Running analysis...")
df = fetch_data("BTC/USDT", "4h", 250)
df = add_indicators(df)
signal, price, rsi = check_signal(df)
log_signal(signal, price, rsi)
if signal == "BUY":
msg = f"🟢 *BTC BUY Signal*\nPrice: ${price:,.0f}\nRSI: {rsi:.1f}\nCondition: Oversold + above EMA200"
send_telegram(msg)
print(f"BUY signal sent: ${price:,.0f}, RSI {rsi:.1f}")
elif signal == "SELL":
msg = f"🔴 *BTC SELL Signal*\nPrice: ${price:,.0f}\nRSI: {rsi:.1f}"
send_telegram(msg)
print(f"SELL signal sent: ${price:,.0f}, RSI {rsi:.1f}")
else:
print(f"HOLD: ${price:,.0f}, RSI {rsi:.1f}")
if __name__ == "__main__":
run()
Step 5: Connect to OpenClaw
Create an OpenClaw skill file:
// skills/crypto-monitor/skill.json
{
"name": "crypto-monitor",
"description": "Local BTC signal monitor",
"heartbeat": "every 4 hours",
"command": "python crypto_agent.py"
}
Run it:
openclaw skill run crypto-monitor
Your agent now checks for signals every 4 hours and messages you on Telegram when conditions are met.
Security Checklist
Before you run this on a live account (after thorough paper trading), check every item:
[ ] .env file is NOT committed to git
[ ] .gitignore includes .env and *.db
[ ] Binance API key has WITHDRAW DISABLED
[ ] Binance API key has IP restriction set to your home IP
[ ] You have tested all signals in paper trading mode for 30+ days
[ ] You understand every line of code and why it does what it does
[ ] Your machine has full-disk encryption enabled
[ ] You're running on a secure network (not public WiFi)
[ ] You have 2FA on your Binance account
[ ] Your Telegram bot token is not shared anywhere
If any item is unchecked, do not run with live capital.
How This Compares to Cloud Bots
| OpenClaw (Local) | 3Commas | Cryptohopper | |
|---|---|---|---|
| API keys location | Your machine only | Their servers | Their servers |
| Strategy visibility | You only | Their team | Their team |
| Trade history | Local SQLite | Their cloud | Their cloud |
| Cost | $0/month | $25-99/month | $19-107/month |
| If they're breached | You're unaffected | Your keys exposed | Your keys exposed |
| If their servers go down | Your agent keeps running | Your trades stop | Your trades stop |
The tradeoff is setup time and technical skill. You invest 45 minutes once instead of $600-$1,200/year forever.
The Privacy Argument, Precisely
Here's the threat model for cloud bots:
Scenario 1: Cloud provider data breach
→ Cloud bot: Your API keys, strategy, and trade history are exposed
→ Local bot: Attacker gets nothing — your data was never there
Scenario 2: Insider threat (employee at cloud provider)
→ Cloud bot: They can see your keys and strategy
→ Local bot: No access possible
Scenario 3: Cloud provider shutdown
→ Cloud bot: Your automation stops immediately
→ Local bot: Completely unaffected
Scenario 4: Your machine is compromised
→ Both options: Your keys are exposed
→ Mitigation: IP restriction + no withdraw permission = limited damage
The local approach doesn't eliminate all risk. But it eliminates the risk that's most likely and most damaging: third-party breach or shutdown.
Running 24/7 Without Your Laptop
If you want the agent running when your laptop is off, the options are:
Option A: Raspberry Pi (~$60 one-time)
# On the Pi
git clone your-private-repo
pip install -r requirements.txt
# Add to cron: */240 * * * * python /home/pi/crypto_agent.py
Option B: Cheap VPS (~$5-10/month)
Hetzner, DigitalOcean, Vultr. SSH in, set up your agent, run as a cron job. Note: keys are now on a remote server, so IP restriction to the VPS IP becomes essential.
Option C: Just run it when you're at your machine
For alert-only (no execution), running 12-16 hours/day is fine. You'll miss overnight signals but you'll also review every trade before acting.
What You Can't Do Locally (And That's Fine)
Running locally means:
- Your bot stops when your machine stops — unless you use a Pi or VPS
- No fancy UI — you're working in terminals and Python scripts
- No social features — no signal marketplace, no copy trading
If those features matter to you, cloud bots serve real needs. The question is whether the convenience is worth the privacy cost and monthly fee.
For traders who want full control and zero recurring cost, local wins decisively.
Next Steps
- Run paper trading for 30 days with this setup
- Review every signal in your local database
- Only then consider small live capital ($100-500 to test execution)
The code above is a starting point. The discipline to follow it is the real work.
Expand Your Setup
The full OpenClaw kit — including pre-built local skills, paper trading database, regime detection, and Telegram integration:
👉 OpenClaw Home AI Agent Kit — Full Setup Guide
Also check out CryptoClaw Skills Hub — browse and install crypto skills for your OpenClaw agent:
👉 https://paarthurnax970-debug.github.io/cryptoclawskills/
Your keys. Your machine. Your strategy.
Not financial advice. Paper trading only. The security practices described are general guidance and not a guarantee of protection. Always conduct your own security assessment before handling real assets.
Top comments (0)