How to Build an AI Crypto Trading Bot: A Simple Vibe Coding Guide
With Alchemy and Copy Paste Coders
We took the main article and core ideas and rewrote them for builders who don’t want complexity — they want execution.
This isn’t about reading theory or becoming a traditional developer. It’s about using AI, copy-paste code, and automation-first platforms to build real products, services, and revenue systems fast.
Modern development has changed.
You no longer need to master everything manually.
With the right platforms, APIs, and AI tools, you can:
- Build production-ready apps without deep coding backgrounds
- Create automated services and workflows
- Launch AI-powered products faster than traditional teams
- Monitor data, trigger actions, and scale systems automatically
This channel focuses on vibe coding — understanding what to build, letting AI handle how it’s built, and using automation to keep it running.
Whether it’s Web3, AI agents, fintech tools, or backend automations, the goal is the same:
speed, leverage, and ownership.
If you can copy, paste, connect tools, and think logically — you can build.
AI trading bots use machine learning to analyze markets and execute trades automatically. While 58% of retail investors now use AI tools, only 10–30% achieve consistent profitability. Success requires reliable infrastructure, sound risk management, and realistic expectations.
This guide shows you how to build a sentiment-enhanced trend prediction bot for Ethereum using Alchemy’s blockchain infrastructure.
What Makes Trading Bots Succeed
Infrastructure is critical. Most bots fail not from bad predictions, but from stale data, API downtime, or slow execution. Three requirements separate profitable bots from failures:
- Data accuracy: AI models need real-time, accurate data. Stale prices lead to bad trades.
- Low latency: Speed determines who profits. The fastest bot captures arbitrage opportunities first.
- Reliability: Downtime during volatility means missed stop-losses and liquidated positions.
Alchemy provides real-time blockchain data across 100+ chains with the low-latency performance trading demands.
Your Tech Stack
Core Python Libraries:
- Pandas (data manipulation)
- NumPy (numerical computations)
- scikit-learn (machine learning)
- PyTorch/TensorFlow (deep learning)
Blockchain Infrastructure:
- Alchemy SDK (real-time blockchain data)
- Web3.py (Ethereum interactions)
- CCXT (unified exchange API)
AI Enhancement:
- LLM APIs (sentiment analysis, anomaly detection)
- Agent frameworks like ElizaOS (autonomous execution)
Building Your Bot: Step-by-Step
Prerequisites
bash
pip install alchemy-sdk pandas numpy scikit-learn requests web3 python-dotenv
Create a .env file:
ALCHEMY_API_KEY=your_api_key_here
Step 1: Fetch Blockchain Data
python
import os
from dotenv import load_dotenv
from alchemy import Alchemy, Network
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import time
load_dotenv()alchemy = Alchemy(
api_key=os.getenv('ALCHEMY_API_KEY'),
network=Network.ETH_MAINNET
)def fetch_historical_data(hours=168):
"""Fetch on-chain metrics: gas usage and transaction counts"""
current_block = alchemy.core.get_block_number()
blocks_per_hour = 300
blocks_to_fetch = hours * blocks_per_hour
data = []
for i in range(current_block - blocks_to_fetch, current_block, blocks_per_hour):
try:
block = alchemy.core.get_block(i)
data.append({
'block_number': i,
'timestamp': block.timestamp,
'gas_used': block.gas_used,
'transaction_count': len(block.transactions)
})
except Exception as e:
print(f"Error fetching block {i}: {e}")
continue
return pd.DataFrame(data)df = fetch_historical_data(hours=168)
Step 2: Fetch ETH Prices
python
import requests
def fetch_eth_prices_alchemy(hours=168):
"""Fetch historical ETH prices using Alchemy's Prices API"""
url = f"https://eth-mainnet.g.alchemy.com/prices/v1/{os.getenv('ALCHEMY_API_KEY')}/tokens/by-symbol"
end_time = datetime.now()
start_time = end_time - timedelta(hours=hours)
params = {
'symbols': 'ETH',
'startTime': int(start_time.timestamp()),
'endTime': int(end_time.timestamp()),
'interval': '1h'
}
response = requests.get(url, params=params, headers={'Accept': 'application/json'})
if response.status_code == 200:
data = response.json()
prices = data['data'][0]['prices']
price_data = []
for price_point in prices:
price_data.append({
'timestamp': datetime.fromtimestamp(price_point['timestamp']),
'price': price_point['value']
})
return pd.DataFrame(price_data)
else:
raise Exception(f"Failed to fetch prices: {response.status_code}")price_df = fetch_eth_prices_alchemy(hours=168)# Merge blockchain and price data
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='s')
df = pd.merge_asof(
df.sort_values('timestamp'),
price_df.sort_values('timestamp'),
on='timestamp',
direction='nearest'
)
Step 3: Engineer Features
python
def engineer_features(df):
"""Transform raw data into predictive features"""
# Price-based features
df['price_change'] = df['price'].pct_change()
df['price_ma_12'] = df['price'].rolling(window=12).mean()
df['price_ma_24'] = df['price'].rolling(window=24).mean()
df['volatility'] = df['price_change'].rolling(window=12).std()
# On-chain sentiment features
df['gas_trend'] = df['gas_used'].pct_change()
df['tx_trend'] = df['transaction_count'].pct_change()
# Momentum
df['momentum'] = df['price'] - df['price'].shift(6)
# Target: will price go up next hour?
df['target'] = (df['price'].shift(-1) > df['price']).astype(int)
return df.dropna()
df = engineer_features(df)
Step 4: Train the Model
python
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
feature_columns = [
'price_change', 'price_ma_12', 'price_ma_24', 'volatility',
'gas_trend', 'tx_trend', 'momentum'
]X = df[feature_columns]
y = df['target']# Split without shuffling (preserve time order)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, shuffle=False
)model = RandomForestClassifier(
n_estimators=100,
max_depth=10,
random_state=42,
class_weight='balanced'
)model.fit(X_train, y_train)y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)print(f"Accuracy: {accuracy:.2%}")
print(classification_report(y_test, y_pred, target_names=['Down', 'Up']))
Good results: 55–60% accuracy is solid for trading. If you see 90%+, check for overfitting or data leakage.
Step 5: Real-Time Trading Logic
python
def fetch_current_data():
"""Fetch latest data for prediction"""
current_block = alchemy.core.get_block_number()
block = alchemy.core.get_block(current_block)
price_url = f"https://eth-mainnet.g.alchemy.com/prices/v1/{os.getenv('ALCHEMY_API_KEY')}/tokens/by-symbol"
price_response = requests.get(
price_url,
params={'symbols': 'ETH'},
headers={'Accept': 'application/json'}
)
current_price = price_response.json()['data'][0]['prices'][0]['value']
return {
'block_number': current_block,
'timestamp': datetime.now(),
'gas_used': block.gas_used,
'transaction_count': len(block.transactions),
'price': current_price
}
def prepare_features_for_prediction(current_data, historical_df):
"""Engineer features from current data"""
temp_df = pd.concat([historical_df, pd.DataFrame([current_data])], ignore_index=True)
temp_df = engineer_features(temp_df)
return temp_df[feature_columns].iloc[-1:].valuesdef execute_trade(action, amount, current_price):
"""Execute trade (simulated - replace with real execution)"""
print(f"\n{'='*50}")
print(f"TRADE SIGNAL: {action.upper()}")
print(f"Amount: {amount} ETH @ ${current_price:,.2f}")
print(f"{'='*50}\n")def run_trading_bot(model, historical_df, interval_seconds=300):
"""Main bot loop"""
print("AI TRADING BOT STARTED")
position = None
entry_price = 0
confidence_threshold = 0.6
while True:
try:
current_data = fetch_current_data()
current_price = current_data['price']
features = prepare_features_for_prediction(current_data, historical_df)
prediction = model.predict(features)[0]
prediction_proba = model.predict_proba(features)[0]
print(f"[{datetime.now().strftime('%H:%M:%S')}] Price: ${current_price:,.2f} | "
f"Prediction: {'UP' if prediction == 1 else 'DOWN'} "
f"({prediction_proba[prediction]:.1%}) | Position: {position or 'None'}")
# BUY signal
if prediction == 1 and prediction_proba[1] > confidence_threshold:
if position != 'long':
execute_trade('BUY', 0.1, current_price)
position = 'long'
entry_price = current_price
# SELL signal
elif prediction == 0 and prediction_proba[0] > confidence_threshold:
if position == 'long':
profit_pct = ((current_price - entry_price) / entry_price) * 100
print(f"Closing position. Profit: {profit_pct:+.2f}%")
execute_trade('SELL', 0.1, current_price)
position = None
# Update rolling data window
historical_df = pd.concat([
historical_df,
pd.DataFrame([current_data])
], ignore_index=True).tail(168)
time.sleep(interval_seconds)
except KeyboardInterrupt:
print("\nBOT STOPPED")
break
except Exception as e:
print(f"ERROR: {e}")
time.sleep(60)run_trading_bot(model, df, interval_seconds=300)
Step 6: Add Whale Monitoring
python
def monitor_whale_activity():
"""Monitor large ETH transfers as sentiment signals"""
WHALE_THRESHOLD = 100 # 100 ETH
EXCHANGE_ADDRESSES = {
'0x3f5ce5fbfe3e9af3971dd833d26ba9b5c936f0be': 'Binance',
'0x001866ae5b3de6caa5a51543fd9fb64f524f5478': 'Coinbase',
# ... add more exchanges
}
def handle_transfer(event):
try:
value_eth = int(event['value'], 16) / 1e18
if value_eth >= WHALE_THRESHOLD:
from_addr = event['from'].lower()
to_addr = event['to'].lower()
from_exchange = EXCHANGE_ADDRESSES.get(from_addr)
to_exchange = EXCHANGE_ADDRESSES.get(to_addr)
alert = f"\n🐋 WHALE ALERT: {value_eth:.2f} ETH"
if from_exchange and not to_exchange:
alert += f"\n📤 From {from_exchange} → BULLISH"
elif not from_exchange and to_exchange:
alert += f"\n📥 To {to_exchange} → BEARISH"
print(alert)
except Exception as e:
print(f"Error: {e}")
filter_params = {
'topics': [alchemy.core.utils.keccak(text="Transfer(address,address,uint256)").hex()]
}
alchemy.ws.on(filter_params, handle_transfer)
# Run in background thread
import threading
whale_thread = threading.Thread(target=monitor_whale_activity, daemon=True)
whale_thread.start()
Step 7: Risk Management
python
class RiskManager:
"""Comprehensive risk management"""
def __init__(self, initial_capital=10000, max_position_size=1.0,
max_drawdown=0.15, stop_loss=0.05, take_profit=0.10):
self.initial_capital = initial_capital
self.portfolio_value = initial_capital
self.peak_value = initial_capital
self.max_position_size = max_position_size
self.max_drawdown = max_drawdown
self.stop_loss = stop_loss
self.take_profit = take_profit
self.trades = []
self.trading_paused = False
def check_drawdown(self):
"""Pause if drawdown exceeds threshold"""
current_drawdown = (self.peak_value - self.portfolio_value) / self.peak_value
if current_drawdown >= self.max_drawdown:
self.trading_paused = True
print(f"⚠️ MAX DRAWDOWN REACHED: {current_drawdown:.2%}")
return False
return True
def calculate_position_size(self, confidence, current_price):
"""Size positions based on confidence"""
base_size = self.max_position_size * confidence
portfolio_scale = self.portfolio_value / self.initial_capital
adjusted_size = base_size * portfolio_scale
return min(adjusted_size, self.max_position_size)
def check_stop_loss(self, entry_price, current_price, position_type):
"""Check if stop loss triggered"""
if position_type == 'long':
loss = (entry_price - current_price) / entry_price
if loss >= self.stop_loss:
print(f"🛑 STOP LOSS TRIGGERED: {loss:.2%}")
return True
return False
def check_take_profit(self, entry_price, current_price, position_type):
"""Check if take profit reached"""
if position_type == 'long':
profit = (current_price - entry_price) / entry_price
if profit >= self.take_profit:
print(f"🎯 TAKE PROFIT: {profit:.2%}")
return True
return False
risk_manager = RiskManager(
initial_capital=10000,
max_position_size=0.5,
max_drawdown=0.15,
stop_loss=0.03,
take_profit=0.06
)
Step 8: Backtest Your Strategy
python
def backtest_strategy(model, df, risk_manager, initial_capital=10000):
"""Simulate strategy on historical data"""
capital = initial_capital
position = None
trades = []
FEE_RATE = 0.001 # 0.1% per trade
SLIPPAGE = 0.0005 # 0.05% slippage
for i in range(24, len(df)):
current_price = df['price'].iloc[i]
features = df[feature_columns].iloc[i:i+1].values
prediction = model.predict(features)[0]
prediction_proba = model.predict_proba(features)[0]
confidence = prediction_proba[prediction]
# Check stop loss/take profit
if position == 'long':
pnl_pct = (current_price - entry_price) / entry_price
if pnl_pct <= -risk_manager.stop_loss or pnl_pct >= risk_manager.take_profit:
sell_price = current_price * (1 - SLIPPAGE)
pnl = (sell_price - entry_price) * position_size
fees = sell_price * position_size * FEE_RATE
capital += (position_size * sell_price) - fees
position = None
continue
# Trading logic
if prediction == 1 and confidence > 0.6 and position != 'long':
buy_price = current_price * (1 + SLIPPAGE)
position_size = min(0.5, (capital * 0.95) / buy_price)
cost = position_size * buy_price
fees = cost * FEE_RATE
capital -= (cost + fees)
entry_price = buy_price
position = 'long'
elif prediction == 0 and confidence > 0.6 and position == 'long':
sell_price = current_price * (1 - SLIPPAGE)
pnl = (sell_price - entry_price) * position_size
fees = sell_price * position_size * FEE_RATE
capital += (position_size * sell_price) - fees
position = None
total_return = ((capital - initial_capital) / initial_capital) * 100
print(f"\nBacktest Results:")
print(f"Initial: ${initial_capital:,.2f}")
print(f"Final: ${capital:,.2f}")
print(f"Return: {total_return:+.2f}%")
return capital
final_capital = backtest_strategy(model, df, risk_manager)
Critical Warnings
Before going live:
- Paper trade first: Simulate for at least a month
- Start small: Use 10–20% of intended capital initially
- Monitor constantly: Watch for bugs and unexpected behavior
- Use kill switches: Automate emergency shutdowns
- Include fees: Gas costs and trading fees compound quickly
- Understand regulations: Know your jurisdiction’s rules
- Secure your keys: Never hardcode API keys, use environment variables
- Expect worse results: Real trading performs 20–30% worse than backtests
What You’ve Built
A functional AI trading bot that:
- Fetches real-time blockchain data via Alchemy
- Combines price, on-chain metrics, and whale activity
- Uses ML to predict price movements
- Manages risk with stop losses and position sizing
- Can be backtested before going live
This is your foundation. Real profitability requires continuous iteration, market adaptation, and robust infrastructure.
Key Takeaways
- Infrastructure matters more than algorithms: Reliable data beats sophisticated models with stale inputs
- Risk management is mandatory: The best model fails without proper stops and position sizing
- Start simple, iterate: A working simple bot beats a broken complex one
- Backtest realistically: Include fees, slippage, and conservative estimates
- Markets are hard: 55–60% accuracy is genuinely good; expect losses alongside wins
Trading bots are powerful tools, not magic. Success comes from discipline, continuous learning, and respecting the market’s unpredictability.
About the Author and Platform
Usman Asim is a developer advocate and technical writer at Alchemy, a leading blockchain development platform that provides the infrastructure powering some of the world’s largest Web3 applications.
Alchemy offers developers reliable, real-time blockchain data access across over 100 blockchains, along with enhanced APIs, WebSocket connections, and tools specifically designed for building production-ready crypto applications. Their platform handles billions of requests daily and is trusted by major projects in the DeFi, NFT, and Web3 gaming spaces.
This comprehensive guide on building AI trading bots showcases how Alchemy’s infrastructure can be leveraged for algorithmic trading applications, demonstrating practical implementations of their APIs for fetching blockchain data, monitoring whale activity, and executing trades with low latency — critical requirements for competitive crypto trading systems.
🔗 Tools & Resources I Use
DisputeAI (AI Credit Dispute Tool)
👉 https://disputeai.xyz
Credit Repair Planner (eBook)
👉 https://buymeacoffee.com/coinvest/e/469931
AVA Finance
AVA is a credit-building platform that focuses on on-time payment reporting, not interest-heavy debt.
👉 https://meetava.sjv.io/anDyvY
Rent Reporting (RentReporters)
Helps renters build credit by reporting on-time rent payments to major credit bureaus — useful for thin or rebuilding files.
👉 https://prf.hn/click/camref:1101l3G9fN
Bright Data (Data Infrastructure)
👉 https://get.brightdata.com/xafa5cizt3zw
n8n Automation (Workflows & Agents)
👉 https://n8n.partnerlinks.io/pxw8nlb4iwfh
ElevenLabs (AI Voice & Audio)
👉 https://try.elevenlabs.io/2dh4kqbqw25i
AI Shorts & Content Creation:
👉 Veed — AI video editing made simple