Here's a complete code implementation for deploying an automated trading bot on Cloudflare infrastructure:
Project Structure
trading-bot/
├── src/
│ ├── index.ts
│ ├── durable-objects/
│ │ └── TradingBot.ts
│ ├── services/
│ │ ├── ExchangeService.ts
│ │ └── TradingStrategy.ts
│ └── types/
│ └── index.ts
├── wrangler.toml
└── package.json
1. wrangler.toml
name = "trading-bot"
main = "src/index.ts"
compatibility_date = "2024-01-15"
[env.production]
kv_namespaces = [
{ binding = "SECRETS", id = "your-kv-namespace-id" }
]
durable_objects.bindings = [
{ name = "TRADING_BOT", class_name = "TradingBot" }
]
[[migrations]]
tag = "v1"
new_classes = ["TradingBot"]
[triggers]
crons = ["*/1 * * * *"] # Every minute
2. package.json
{
"name": "trading-bot",
"version": "1.0.0",
"scripts": {
"dev": "wrangler dev",
"deploy": "wrangler publish"
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20240117.0",
"typescript": "^5.0.0",
"wrangler": "^3.0.0"
}
}
3. src/types/index.ts
export interface Env {
SECRETS: KVNamespace;
TRADING_BOT: DurableObjectNamespace;
}
export interface MarketData {
symbol: string;
price: number;
timestamp: number;
volume?: number;
}
export interface Trade {
id: string;
symbol: string;
side: 'buy' | 'sell';
quantity: number;
price: number;
timestamp: number;
status: 'pending' | 'filled' | 'cancelled';
}
export interface BotState {
balance: number;
positions: Record<string, number>;
lastTrade?: Trade;
isActive: boolean;
strategy: {
name: string;
parameters: Record<string, any>;
};
}
export interface ExchangeConfig {
apiKey: string;
apiSecret: string;
baseUrl: string;
testnet?: boolean;
}
4. src/services/ExchangeService.ts
import { MarketData, Trade, ExchangeConfig } from '../types';
export class ExchangeService {
private config: ExchangeConfig;
constructor(config: ExchangeConfig) {
this.config = config;
}
async getMarketData(symbol: string): Promise<MarketData> {
try {
const response = await fetch(`${this.config.baseUrl}/api/v3/ticker/price?symbol=${symbol}`, {
headers: {
'X-MBX-APIKEY': this.config.apiKey
}
});
if (!response.ok) {
throw new Error(`Exchange API error: ${response.status}`);
}
const data = await response.json();
return {
symbol: data.symbol,
price: parseFloat(data.price),
timestamp: Date.now()
};
} catch (error) {
console.error('Failed to fetch market data:', error);
throw error;
}
}
async placeTrade(trade: Omit<Trade, 'id' | 'timestamp' | 'status'>): Promise<Trade> {
// Simulate trade placement (replace with actual exchange API call)
const tradeId = `trade_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
try {
// Example Binance spot order (testnet)
const orderParams = new URLSearchParams({
symbol: trade.symbol,
side: trade.side.toUpperCase(),
type: 'MARKET',
quantity: trade.quantity.toString(),
timestamp: Date.now().toString()
});
// In production, you'd sign this request with HMAC-SHA256
const response = await fetch(`${this.config.baseUrl}/api/v3/order/test`, {
method: 'POST',
headers: {
'X-MBX-APIKEY': this.config.apiKey,
'Content-Type': 'application/x-www-form-urlencoded'
},
body: orderParams.toString()
});
if (!response.ok) {
throw new Error(`Trade execution failed: ${response.status}`);
}
return {
...trade,
id: tradeId,
timestamp: Date.now(),
status: 'filled'
};
} catch (error) {
console.error('Failed to place trade:', error);
return {
...trade,
id: tradeId,
timestamp: Date.now(),
status: 'cancelled'
};
}
}
async getAccountBalance(): Promise<number> {
try {
const response = await fetch(`${this.config.baseUrl}/api/v3/account`, {
headers: {
'X-MBX-APIKEY': this.config.apiKey
}
});
if (!response.ok) {
throw new Error(`Account API error: ${response.status}`);
}
const data = await response.json();
const usdtBalance = data.balances.find((b: any) => b.asset === 'USDT');
return parseFloat(usdtBalance?.free || '0');
} catch (error) {
console.error('Failed to fetch account balance:', error);
return 0;
}
}
}
5. src/services/TradingStrategy.ts
import { MarketData, Trade, BotState } from '../types';
export class SimpleMovingAverageStrategy {
private priceHistory: number[] = [];
private readonly shortPeriod: number;
private readonly longPeriod: number;
private readonly tradeAmount: number;
constructor(shortPeriod = 5, longPeriod = 20, tradeAmount = 100) {
this.shortPeriod = shortPeriod;
this.longPeriod = longPeriod;
this.tradeAmount = tradeAmount;
}
addPrice(price: number): void {
this.priceHistory.push(price);
if (this.priceHistory.length > this.longPeriod) {
this.priceHistory.shift();
}
}
private calculateSMA(period: number): number | null {
if (this.priceHistory.length < period) return null;
const slice = this.priceHistory.slice(-period);
return slice.reduce((sum, price) => sum + price, 0) / period;
}
shouldTrade(marketData: MarketData, botState: BotState): Trade | null {
this.addPrice(marketData.price);
const shortSMA = this.calculateSMA(this.shortPeriod);
const longSMA = this.calculateSMA(this.longPeriod);
if (!shortSMA || !longSMA) {
console.log('Not enough data for SMA calculation');
return null;
}
const currentPosition = botState.positions[marketData.symbol] || 0;
const lastTrade = botState.lastTrade;
const timeSinceLastTrade = lastTrade ? Date.now() - lastTrade.timestamp : Infinity;
// Avoid rapid trading (minimum 5 minutes between trades)
if (timeSinceLastTrade < 5 * 60 * 1000) {
return null;
}
// Buy signal: short SMA crosses above long SMA
if (shortSMA > longSMA && currentPosition <= 0) {
return {
symbol: marketData.symbol,
side: 'buy',
quantity: this.tradeAmount / marketData.price,
price: marketData.price
} as Omit<Trade, 'id' | 'timestamp' | 'status'>;
}
// Sell signal: short SMA crosses below long SMA
if (shortSMA < longSMA && currentPosition > 0) {
return {
symbol: marketData.symbol,
side: 'sell',
quantity: Math.abs(currentPosition),
price: marketData.price
} as Omit<Trade, 'id' | 'timestamp' | 'status'>;
}
return null;
}
}
6. src/durable-objects/TradingBot.ts
import { ExchangeService } from '../services/ExchangeService';
import { SimpleMovingAverageStrategy } from '../services/TradingStrategy';
import { BotState, Env, MarketData, Trade } from '../types';
export class TradingBot {
private state: DurableObjectState;
private env: Env;
private exchangeService?: ExchangeService;
private strategy: SimpleMovingAverageStrategy;
constructor(state: DurableObjectState, env: Env) {
this.state = state;
this.env = env;
this.strategy = new SimpleMovingAverageStrategy();
}
async fetch(request: Request): Promise<Response> {
const url = new URL(request.url);
const path = url.pathname;
try {
switch (path) {
case '/trade':
return await this.executeTradingCycle();
case '/status':
return await this.getStatus();
case '/config':
return await this.updateConfig(request);
default:
return new Response('Not found', { status: 404 });
}
} catch (error) {
console.error('TradingBot error:', error);
return new Response(`Error: ${error.message}`, { status: 500 });
}
}
private async initializeExchangeService(): Promise<void> {
if (this.exchangeService) return;
const apiKey = await this.env.SECRETS.get('BINANCE_API_KEY');
const apiSecret = await this.env.SECRETS.get('BINANCE_API_SECRET');
if (!apiKey || !apiSecret) {
throw new Error('Exchange API credentials not found');
}
this.exchangeService = new ExchangeService({
apiKey,
apiSecret,
baseUrl: 'https://testnet.binance.vision', // Use testnet for safety
testnet: true
});
}
private async getBotState(): Promise<BotState> {
const stored = await this.state.storage.get('botState');
return stored as BotState || {
balance: 1000, // Starting balance
positions: {},
isActive: true,
strategy: {
name: 'SimpleMovingAverage',
parameters: { shortPeriod: 5, longPeriod: 20 }
}
};
}
private async saveBotState(botState: BotState): Promise<void> {
await this.state.storage.put('botState', botState);
}
private async executeTradingCycle(): Promise<Response> {
await this.initializeExchangeService();
const botState = await this.getBotState();
if (!botState.isActive) {
return new Response(JSON.stringify({ message: 'Bot is inactive' }));
}
try {
// Get market data for BTCUSDT
const marketData = await this.exchangeService!.getMarketData('BTCUSDT');
// Check if strategy suggests a trade
const suggestedTrade = this.strategy.shouldTrade(marketData, botState);
if (suggestedTrade) {
console.log('Executing trade:', suggestedTrade);
// Execute the trade
const executedTrade = await this.exchangeService!.placeTrade(suggestedTrade);
// Update bot state
if (executedTrade.status === 'filled') {
botState.lastTrade = executedTrade;
// Update positions
const currentPosition = botState.positions[executedTrade.symbol] || 0;
if (executedTrade.side === 'buy') {
botState.positions[executedTrade.symbol] = currentPosition + executedTrade.quantity;
botState.balance -= executedTrade.quantity * executedTrade.price;
} else {
botState.positions[executedTrade.symbol] = currentPosition - executedTrade.quantity;
botState.balance += executedTrade.quantity * executedTrade.price;
}
}
await this.saveBotState(botState);
return new Response(JSON.stringify({
message: 'Trade executed',
trade: executedTrade,
marketData,
botState
}));
}
return new Response(JSON.stringify({
message: 'No trade signal',
marketData,
botState
}));
} catch (error) {
console.error('Trading cycle error:', error);
return new Response(JSON.stringify({
error: error.message,
timestamp: new Date().toISOString()
}), { status: 500 });
}
}
private async getStatus(): Promise<Response> {
const botState = await this.getBotState();
if (this.exchangeService) {
try {
const balance = await this.exchangeService.getAccountBalance();
botState.balance = balance;
} catch (error) {
console.error('Failed to fetch live balance:', error);
}
}
return new Response(JSON.stringify({
botState,
timestamp: new Date().toISOString()
}));
}
private async updateConfig(request: Request): Promise<Response> {
if (request.method !== 'POST') {
return new Response('Method not allowed', { status: 405 });
}
const config = await request.json();
const botState = await this.getBotState();
if (config.isActive !== undefined) {
botState.isActive = config.isActive;
}
await this.saveBotState(botState);
return new Response(JSON.stringify({
message: 'Configuration updated',
botState
}));
}
}
7. src/index.ts
import { TradingBot } from './durable-objects/TradingBot';
import { Env } from './types';
export { TradingBot };
export default {
async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext): Promise<void> {
console.log('Scheduled trading cycle triggered');
try {
// Get the Durable Object instance
const id = env.TRADING_BOT.idFromName('main-trading-bot');
const stub = env.TRADING_BOT.get(id);
// Execute trading cycle
const response = await stub.fetch('https://dummy.com/trade');
const result = await response.text();
console.log('Trading cycle result:', result);
} catch (error) {
console.error('Scheduled task error:', error);
}
},
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
// Route to Durable Object for manual testing/monitoring
if (url.pathname.startsWith('/bot/')) {
const id = env.TRADING_BOT.i