How to Use ChatGPT API to Build a Crypto Market Analysis Agent
Learn how to use the ChatGPT API (GPT-4o) to build an automated crypto market analysis agent that fetches live data, generates trading insights, and sends daily reports to your phone.
Builder of AI agents, crypto trading bots, and open-source automation tools. Sharing practical guides on how to build, deploy, and profit from AI and DeFi technology.
What We're Building
A fully automated market analysis agent that:
- Fetches live price, volume, and technical data for BTC, ETH, and SOL
- Sends this data to GPT-4o with a structured analysis prompt
- Generates a professional market analysis report
- Sends the report to your Telegram daily at 8 AM
Total cost: ~$0.02 per report using GPT-4o-mini.
Setting Up
pip install openai ccxt python-telegram-bot schedule requests pandas
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ.get('OPENAI_API_KEY'))
# Test connection
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Say 'API connected successfully'"}]
)
print(response.choices[0].message.content)
Step 1: Gather Market Data
import ccxt
import pandas as pd
import numpy as np
def calculate_rsi(prices: list, period: int = 14) -> float:
if len(prices) < period + 1:
return 50.0
prices_arr = np.array(prices)
deltas = np.diff(prices_arr)
gains = np.where(deltas > 0, deltas, 0)
losses = np.where(deltas < 0, -deltas, 0)
avg_gain = np.mean(gains[-period:])
avg_loss = np.mean(losses[-period:])
if avg_loss == 0:
return 100.0
rs = avg_gain / avg_loss
return 100 - (100 / (1 + rs))
def get_market_data(symbol: str, exchange=None) -> dict:
"""Fetch comprehensive market data for a symbol"""
if exchange is None:
exchange = ccxt.binance()
# Fetch OHLCV data (4h candles, last 100)
ohlcv_4h = exchange.fetch_ohlcv(symbol, '4h', limit=100)
df_4h = pd.DataFrame(ohlcv_4h, columns=['ts', 'open', 'high', 'low', 'close', 'volume'])
# Daily data for longer context
ohlcv_1d = exchange.fetch_ohlcv(symbol, '1d', limit=30)
df_1d = pd.DataFrame(ohlcv_1d, columns=['ts', 'open', 'high', 'low', 'close', 'volume'])
# Current ticker
ticker = exchange.fetch_ticker(symbol)
# Calculate key metrics
closes_4h = df_4h['close'].tolist()
closes_1d = df_1d['close'].tolist()
current_price = ticker['last']
ma_20 = df_4h['close'].rolling(20).mean().iloc[-1]
ma_50 = df_1d['close'].rolling(20).mean().iloc[-1]
rsi_4h = calculate_rsi(closes_4h)
# Volume analysis
avg_volume = df_4h['volume'].rolling(20).mean().iloc[-1]
current_volume = df_4h['volume'].iloc[-1]
volume_ratio = current_volume / avg_volume
# Price change metrics
change_24h = ticker.get('percentage', 0)
change_7d = (current_price - df_1d['close'].iloc[-7]) / df_1d['close'].iloc[-7] * 100
change_30d = (current_price - df_1d['close'].iloc[0]) / df_1d['close'].iloc[0] * 100
return {
'symbol': symbol,
'current_price': current_price,
'change_24h': change_24h,
'change_7d': change_7d,
'change_30d': change_30d,
'volume_24h_usd': ticker.get('quoteVolume', 0),
'volume_ratio': volume_ratio, # > 1.5 = unusually high volume
'rsi_4h': rsi_4h,
'ma_20_4h': ma_20,
'ma_50_daily': ma_50,
'above_ma20': current_price > ma_20,
'above_ma50': current_price > ma_50,
'high_24h': ticker['high'],
'low_24h': ticker['low'],
}
Step 2: Generate AI Analysis
def generate_market_analysis(market_data: list[dict]) -> str:
"""Send market data to GPT-4o for analysis"""
# Format data as a clear summary for the model
data_summary = ""
for asset in market_data:
symbol = asset['symbol'].split('/')[0]
trend = "๐ BULLISH" if asset['above_ma20'] and asset['rsi_4h'] > 50 else \
"๐ BEARISH" if not asset['above_ma20'] and asset['rsi_4h'] < 50 else \
"โ๏ธ NEUTRAL"
data_summary += f"""
{symbol} ({trend}):
- Price: ${asset['current_price']:,.2f}
- 24h Change: {asset['change_24h']:+.2f}%
- 7d Change: {asset['change_7d']:+.2f}%
- 30d Change: {asset['change_30d']:+.2f}%
- RSI (4h): {asset['rsi_4h']:.1f}
- Volume vs Avg: {asset['volume_ratio']:.1f}x
- Above 20 MA: {'Yes' if asset['above_ma20'] else 'No'}
- Above 50 MA: {'Yes' if asset['above_ma50'] else 'No'}
"""
prompt = f"""You are a professional crypto market analyst. Analyze the following market data and provide a concise daily briefing.
CURRENT MARKET DATA:
{data_summary}
Please provide:
1. **Overall Market Sentiment** (1-2 sentences)
2. **BTC Analysis**: Key levels, trend, and 24h outlook
3. **ETH Analysis**: Key levels, trend, and 24h outlook
4. **SOL Analysis**: Key levels, trend, and 24h outlook
5. **Top 3 Watch Points**: What to watch for in the next 24 hours
6. **Risk Level**: Low / Medium / High with reasoning
Keep the total response under 400 words. Be specific with price levels. No hype, just analysis."""
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "system",
"content": "You are a professional cryptocurrency market analyst. Provide factual, data-driven analysis without hype or price predictions as certainties. Always mention both bullish and bearish cases."
},
{
"role": "user",
"content": prompt
}
],
max_tokens=600,
temperature=0.3, # Lower = more consistent, less creative
)
return response.choices[0].message.content
Step 3: Send to Telegram
import telegram
import asyncio
async def send_daily_report():
bot = telegram.Bot(token=os.environ['TELEGRAM_TOKEN'])
exchange = ccxt.binance()
symbols = ['BTC/USDT', 'ETH/USDT', 'SOL/USDT']
# Gather market data
print("Fetching market data...")
market_data = [get_market_data(sym, exchange) for sym in symbols]
# Generate analysis
print("Generating AI analysis...")
analysis = generate_market_analysis(market_data)
# Format message
from datetime import datetime
date_str = datetime.now().strftime("%B %d, %Y")
message = f"""๐ **Daily Crypto Report โ {date_str}**
{analysis}
---
_Powered by AI Agents Hub | Data: Binance_"""
await bot.send_message(
chat_id=os.environ['TELEGRAM_CHAT_ID'],
text=message,
parse_mode='Markdown'
)
print("โ
Report sent!")
# Schedule daily at 8 AM UTC
import schedule
schedule.every().day.at("08:00").do(lambda: asyncio.run(send_daily_report()))
print("๐ Market analysis bot started. Report scheduled for 08:00 UTC daily.")
while True:
schedule.run_pending()
time.sleep(60)
Upgrading to GPT-4o for Deeper Analysis
For more sophisticated analysis, upgrade to gpt-4o:
def deep_analysis(symbol: str, full_ohlcv: list) -> str:
"""Generate deep technical analysis for a single asset"""
# Convert OHLCV to readable format
price_history = "\n".join([
f"Date {i}: O={bar[1]:.0f} H={bar[2]:.0f} L={bar[3]:.0f} C={bar[4]:.0f} V={bar[5]:.0f}"
for i, bar in enumerate(full_ohlcv[-14:]) # Last 14 candles
])
response = client.chat.completions.create(
model="gpt-4o", # Full model for deeper analysis
messages=[{
"role": "user",
"content": f"""Analyze this {symbol} price data (daily candles):
{price_history}
Identify:
1. The primary trend (up/down/sideways) with supporting evidence
2. Key support and resistance levels
3. Any significant technical patterns (head & shoulders, triangles, etc.)
4. A specific entry and exit level for a trade, with stop loss
5. Confidence level: 1-10
Be precise and cite specific price levels."""
}],
max_tokens=400,
temperature=0.2,
)
return response.choices[0].message.content
Cost Analysis
Running this bot 24/7 with daily reports on 3 assets:
- GPT-4o-mini: ~500 tokens per report ร 30 days = ~$0.15/month
- GPT-4o for deep analysis: ~$2/month
- Server (Railway free tier): $0
Total: Under $2.50/month for a fully automated AI market analysis system.
This is the kind of value that AI makes possible โ professional-grade market analysis, personalized to your portfolio, delivered daily, for the price of a coffee.
Tagged in
Related Articles
Grok AI for Crypto Trading: How Elon's AI Gives an Edge in 2026
4 min read
AI AgentsHow to Build a Crypto Twitter (X) Bot That Goes Viral in 2026
5 min read
AI AgentsAgentic AI Frameworks Compared: LangGraph vs CrewAI vs AutoGen in 2026
6 min read
AI AgentsBest AI Coding Tools for Building Crypto Bots in 2026: Cursor vs Copilot vs Devin
5 min read