How to Build a Trading Bot
Build a complete automated trading system using Python and the TickAtlas API. This guide covers strategy design, signal generation, risk management, and deployment.
Prerequisites
- Python 3.8+ installed
- TickAtlas API key (get one free)
- Basic understanding of technical indicators
- A broker account for live trading (optional for backtesting)
Step 1: Project Setup
pip install requests schedule python-dotenv Create a .env file:
TICKATLAS_API_KEY=your_api_key_here Step 2: Create the API Client
import os
import requests
from dotenv import load_dotenv
load_dotenv()
class TickAtlasClient:
def __init__(self):
self.base_url = "https://tickatlas.com/v1"
self.headers = {"X-API-Key": os.getenv("TICKATLAS_API_KEY")}
def get_indicator(self, symbol, indicator, timeframe):
"""Get a single indicator value."""
params = {"symbol": symbol, "indicator": indicator, "timeframe": timeframe}
response = requests.get(
f"{self.base_url}/indicator",
headers=self.headers,
params=params
)
response.raise_for_status()
return response.json()
def get_summary(self, symbol, timeframe):
"""Get AI market analysis."""
params = {"symbol": symbol, "timeframe": timeframe}
response = requests.get(
f"{self.base_url}/summary",
headers=self.headers,
params=params
)
response.raise_for_status()
return response.json()
def get_multi(self, symbols, indicators, timeframe):
"""Get multiple indicators for multiple symbols."""
params = {
"symbols": ",".join(symbols),
"indicators": ",".join(indicators),
"timeframe": timeframe
}
response = requests.get(
f"{self.base_url}/multi",
headers=self.headers,
params=params
)
response.raise_for_status()
return response.json() Step 3: Define Your Strategy
We'll implement a simple RSI + MACD confluence strategy:
- Buy signal: RSI < 35 AND MACD histogram turning positive
- Sell signal: RSI > 65 AND MACD histogram turning negative
- Risk management: 2× ATR stop loss, 3× ATR take profit
class TradingStrategy:
def __init__(self, client):
self.client = client
def analyze(self, symbol, timeframe="H1"):
"""Analyze a symbol and return a trading signal."""
rsi = self.client.get_indicator(symbol, "RSI_14", timeframe)
macd = self.client.get_indicator(symbol, "MACD_hist", timeframe)
atr = self.client.get_indicator(symbol, "ATR_14", timeframe)
rsi_value = rsi["value"]
macd_value = macd["value"]
atr_value = atr["value"]
signal = "HOLD"
if rsi_value < 35 and macd_value > 0:
signal = "BUY"
elif rsi_value > 65 and macd_value < 0:
signal = "SELL"
return {
"symbol": symbol,
"signal": signal,
"rsi": rsi_value,
"macd_hist": macd_value,
"atr": atr_value,
"stop_loss": atr_value * 2,
"take_profit": atr_value * 3,
} Step 4: Create the Bot Loop
import schedule
import time
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(message)s")
def run_bot():
client = TickAtlasClient()
strategy = TradingStrategy(client)
symbols = ["EURUSD", "GBPUSD", "USDJPY", "XAUUSD"]
for symbol in symbols:
try:
result = strategy.analyze(symbol)
if result["signal"] != "HOLD":
logging.info(
f"📊 {result['signal']} {symbol} | "
f"RSI: {result['rsi']:.1f} | "
f"MACD: {result['macd_hist']:.5f} | "
f"SL: {result['stop_loss']:.5f} | "
f"TP: {result['take_profit']:.5f}"
)
# Here you would execute the trade via your broker API
else:
logging.debug(f"No signal for {symbol}")
except Exception as e:
logging.error(f"Error analyzing {symbol}: {e}")
# Run every hour at the top of the hour
schedule.every().hour.at(":01").do(run_bot)
logging.info("🤖 Trading bot started. Checking every hour...")
run_bot() # Run immediately on start
while True:
schedule.run_pending()
time.sleep(30) Step 5: Enhance with AI Insights
Use the /v1/summary endpoint for AI-powered confirmation:
def analyze_with_ai(self, symbol, timeframe="H1"):
"""Enhanced analysis using AI market summary."""
basic = self.analyze(symbol, timeframe)
if basic["signal"] != "HOLD":
summary = self.client.get_summary(symbol, timeframe)
ai_bias = summary["bias"] # "BULLISH", "BEARISH", or "NEUTRAL"
confidence = summary.get("confidence", 0)
# Only trade when AI confirms the signal
if basic["signal"] == "BUY" and ai_bias == "BULLISH" and confidence > 0.6:
basic["confirmed"] = True
basic["ai_confidence"] = confidence
elif basic["signal"] == "SELL" and ai_bias == "BEARISH" and confidence > 0.6:
basic["confirmed"] = True
basic["ai_confidence"] = confidence
else:
basic["confirmed"] = False
basic["signal"] = "HOLD" # Override - AI doesn't confirm
return basic Related
Next Steps
- Guide
Backtest Your Strategy
Validate strategies with historical OHLCV data
Read more - Guide
Webhook Alerts
Get notified when indicator conditions are met
Read more - Guide
Multi-Timeframe Analysis
Combine M30, H1, H4, D1 for stronger signals
Read more - Indicator
Relative Strength Index (RSI)
The Relative Strength Index (RSI) is a momentum oscillator that measures the speed and magnitude of price movements on a scale from 0 to 100.
Read more