Your crypto portfolio just lost 15% while you slept. Again.
The cryptocurrency market never sleeps, but you do. This creates a problem: manual trading means missing opportunities and watching losses pile up during off-hours. The solution? An Ollama Llama 3.3 trading bot that works around the clock, making data-driven investment decisions while you focus on other things.
This guide shows you how to build a complete automated cryptocurrency trading system using Ollama's Llama 3.3 model. You'll learn to create intelligent trading strategies, implement risk management, and deploy a bot that handles your crypto investments 24/7.
What Makes Ollama Llama 3.3 Perfect for Cryptocurrency Trading
Ollama Llama 3.3 brings several advantages to automated cryptocurrency trading that traditional bots lack:
Advanced Pattern Recognition: Llama 3.3 analyzes market data beyond simple technical indicators. It identifies complex patterns in price movements, social sentiment, and trading volume that human traders often miss.
Natural Language Processing: The model processes news articles, social media sentiment, and market reports to incorporate fundamental analysis into trading decisions. This gives your bot a competitive edge over purely technical trading systems.
Adaptive Learning: Unlike static trading algorithms, Llama 3.3 adjusts its strategies based on market conditions. It learns from successful trades and adapts to changing market dynamics.
Multi-Asset Analysis: The model simultaneously analyzes multiple cryptocurrencies, identifying correlation patterns and portfolio optimization opportunities across different digital assets.
Prerequisites for Building Your Ollama Trading Bot
Before diving into the code, ensure you have these components ready:
System Requirements:
- Python 3.8 or higher
- 8GB RAM minimum (16GB recommended)
- GPU support (optional but recommended for faster processing)
Required API Access:
- Cryptocurrency exchange API (Binance, Coinbase Pro, or Kraken)
- News API for sentiment analysis
- Historical price data source
Python Libraries:
pip install ollama pandas numpy ccxt requests python-dotenv schedule
Setting Up Your Ollama Llama 3.3 Trading Environment
Installing and Configuring Ollama
First, install Ollama on your system:
# Download and install Ollama
curl -fsSL https://ollama.ai/install.sh | sh
# Pull the Llama 3.3 model
ollama pull llama3.3
Creating the Trading Bot Foundation
Create the main trading bot structure:
# trading_bot.py
import ollama
import pandas as pd
import numpy as np
import ccxt
import time
import json
from datetime import datetime, timedelta
from typing import Dict, List, Tuple
import logging
class OllamaLlama33TradingBot:
def __init__(self, exchange_name: str, api_key: str, api_secret: str):
"""
Initialize the Ollama Llama 3.3 trading bot
Args:
exchange_name: Name of the cryptocurrency exchange
api_key: Exchange API key
api_secret: Exchange API secret
"""
self.exchange = getattr(ccxt, exchange_name)({
'apiKey': api_key,
'secret': api_secret,
'sandbox': False, # Set to True for testing
'enableRateLimit': True,
})
# Initialize Ollama client
self.ollama_client = ollama.Client()
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('trading_bot.log'),
logging.StreamHandler()
]
)
self.logger = logging.getLogger(__name__)
# Trading parameters
self.risk_percentage = 0.02 # Risk 2% per trade
self.max_positions = 5 # Maximum concurrent positions
self.min_confidence = 0.7 # Minimum confidence for trades
def get_market_data(self, symbol: str, timeframe: str = '1h', limit: int = 100) -> pd.DataFrame:
"""
Fetch market data from the exchange
Args:
symbol: Trading pair symbol (e.g., 'BTC/USDT')
timeframe: Candlestick timeframe
limit: Number of candlesticks to fetch
Returns:
DataFrame with OHLCV data
"""
try:
ohlcv = self.exchange.fetch_ohlcv(symbol, timeframe, limit=limit)
df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
return df
except Exception as e:
self.logger.error(f"Error fetching market data: {e}")
return pd.DataFrame()
Building the AI-Powered Trading Analysis System
Market Data Analysis with Llama 3.3
Create the core analysis function that leverages Llama 3.3's capabilities:
def analyze_market_with_llama(self, symbol: str, market_data: pd.DataFrame,
news_sentiment: str = "") -> Dict:
"""
Use Llama 3.3 to analyze market conditions and generate trading signals
Args:
symbol: Trading pair symbol
market_data: Historical price data
news_sentiment: Recent news sentiment analysis
Returns:
Dictionary containing trading analysis and recommendations
"""
# Prepare market data summary
latest_price = market_data['close'].iloc[-1]
price_change_24h = ((latest_price - market_data['close'].iloc[-24]) /
market_data['close'].iloc[-24] * 100)
# Calculate technical indicators
sma_20 = market_data['close'].rolling(window=20).mean().iloc[-1]
sma_50 = market_data['close'].rolling(window=50).mean().iloc[-1]
rsi = self.calculate_rsi(market_data['close'])
# Create analysis prompt for Llama 3.3
prompt = f"""
Analyze this cryptocurrency trading opportunity for {symbol}:
MARKET DATA:
- Current Price: ${latest_price:.2f}
- 24h Change: {price_change_24h:.2f}%
- 20-day SMA: ${sma_20:.2f}
- 50-day SMA: ${sma_50:.2f}
- RSI: {rsi:.2f}
- Volume Trend: {self.analyze_volume_trend(market_data)}
NEWS SENTIMENT: {news_sentiment}
TRADING CONTEXT:
- Risk tolerance: Conservative (2% per trade)
- Time horizon: Short to medium term (1-7 days)
- Current market conditions: {self.assess_market_conditions()}
Provide a trading recommendation with:
1. Action (BUY/SELL/HOLD)
2. Confidence level (0-100%)
3. Entry price range
4. Target profit level
5. Stop loss level
6. Risk assessment
7. Reasoning behind the decision
Format response as JSON.
"""
try:
response = self.ollama_client.chat(
model='llama3.3',
messages=[
{
'role': 'system',
'content': 'You are an expert cryptocurrency trading analyst. Provide precise, actionable trading advice based on technical analysis and market sentiment.'
},
{
'role': 'user',
'content': prompt
}
]
)
# Parse the response
analysis = json.loads(response['message']['content'])
self.logger.info(f"Llama 3.3 analysis for {symbol}: {analysis}")
return analysis
except Exception as e:
self.logger.error(f"Error in Llama 3.3 analysis: {e}")
return {"action": "HOLD", "confidence": 0, "reasoning": "Analysis failed"}
Technical Indicators Helper Functions
Add essential technical analysis functions:
def calculate_rsi(self, prices: pd.Series, period: int = 14) -> float:
"""
Calculate Relative Strength Index
Args:
prices: Series of closing prices
period: RSI calculation period
Returns:
Current RSI value
"""
delta = prices.diff()
gain = delta.where(delta > 0, 0).rolling(window=period).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
rs = gain / loss
rsi = 100 - (100 / (1 + rs))
return rsi.iloc[-1]
def analyze_volume_trend(self, market_data: pd.DataFrame) -> str:
"""
Analyze volume trend over recent periods
Args:
market_data: DataFrame with volume data
Returns:
Volume trend description
"""
recent_volume = market_data['volume'].iloc[-5:].mean()
historical_volume = market_data['volume'].iloc[-20:-5].mean()
if recent_volume > historical_volume * 1.5:
return "High volume surge"
elif recent_volume > historical_volume * 1.2:
return "Increasing volume"
elif recent_volume < historical_volume * 0.8:
return "Declining volume"
else:
return "Normal volume"
def assess_market_conditions(self) -> str:
"""
Assess overall market conditions
Returns:
Market condition description
"""
# This would typically analyze major cryptocurrencies
# For simplicity, we'll return a placeholder
return "Mixed signals with moderate volatility"
Implementing Risk Management and Position Sizing
Dynamic Position Sizing
Create a sophisticated position sizing algorithm:
def calculate_position_size(self, account_balance: float, confidence: float,
entry_price: float, stop_loss: float) -> float:
"""
Calculate optimal position size based on risk management rules
Args:
account_balance: Available trading balance
confidence: AI confidence level (0-100)
entry_price: Planned entry price
stop_loss: Stop loss price
Returns:
Position size in base currency
"""
# Calculate risk per trade based on confidence
risk_multiplier = min(confidence / 100, 1.0)
adjusted_risk = self.risk_percentage * risk_multiplier
# Calculate maximum loss per trade
max_loss = account_balance * adjusted_risk
# Calculate position size based on stop loss distance
price_risk = abs(entry_price - stop_loss) / entry_price
position_size = max_loss / price_risk
# Ensure position doesn't exceed account limits
max_position = account_balance * 0.2 # Maximum 20% per position
position_size = min(position_size, max_position)
self.logger.info(f"Calculated position size: {position_size:.2f} "
f"(Risk: {adjusted_risk:.1%}, Confidence: {confidence:.1f}%)")
return position_size
Risk Management Framework
Implement comprehensive risk controls:
def check_risk_limits(self, symbol: str, action: str, position_size: float) -> bool:
"""
Check if trade passes risk management criteria
Args:
symbol: Trading pair symbol
action: Intended action (BUY/SELL)
position_size: Proposed position size
Returns:
True if trade passes risk checks
"""
# Check maximum positions limit
open_positions = self.get_open_positions()
if len(open_positions) >= self.max_positions and action == 'BUY':
self.logger.warning("Maximum positions limit reached")
return False
# Check daily loss limit
daily_pnl = self.calculate_daily_pnl()
if daily_pnl < -self.get_account_balance() * 0.05: # 5% daily loss limit
self.logger.warning("Daily loss limit exceeded")
return False
# Check symbol exposure
symbol_exposure = self.get_symbol_exposure(symbol)
if symbol_exposure > self.get_account_balance() * 0.3: # 30% per symbol limit
self.logger.warning(f"Symbol exposure limit exceeded for {symbol}")
return False
return True
def get_open_positions(self) -> List[Dict]:
"""Get current open positions"""
try:
positions = self.exchange.fetch_positions()
return [pos for pos in positions if pos['contracts'] > 0]
except Exception as e:
self.logger.error(f"Error fetching positions: {e}")
return []
Creating the 24/7 Trading Loop
Main Trading Execution Engine
Build the core trading loop that operates continuously:
def run_trading_loop(self, symbols: List[str], check_interval: int = 300):
"""
Main trading loop that runs 24/7
Args:
symbols: List of trading pairs to monitor
check_interval: Seconds between market checks
"""
self.logger.info("Starting 24/7 trading loop...")
while True:
try:
for symbol in symbols:
self.logger.info(f"Analyzing {symbol}...")
# Fetch market data
market_data = self.get_market_data(symbol)
if market_data.empty:
continue
# Get news sentiment (placeholder implementation)
news_sentiment = self.get_news_sentiment(symbol)
# Analyze with Llama 3.3
analysis = self.analyze_market_with_llama(
symbol, market_data, news_sentiment
)
# Execute trading decision
if analysis['confidence'] >= self.min_confidence:
self.execute_trading_decision(symbol, analysis)
# Brief pause between symbols
time.sleep(10)
# Wait before next market check
self.logger.info(f"Waiting {check_interval} seconds before next check...")
time.sleep(check_interval)
except KeyboardInterrupt:
self.logger.info("Trading loop stopped by user")
break
except Exception as e:
self.logger.error(f"Error in trading loop: {e}")
time.sleep(60) # Wait 1 minute before retrying
def execute_trading_decision(self, symbol: str, analysis: Dict):
"""
Execute trading decision based on Llama 3.3 analysis
Args:
symbol: Trading pair symbol
analysis: Trading analysis from Llama 3.3
"""
action = analysis.get('action', 'HOLD')
confidence = analysis.get('confidence', 0)
if action == 'HOLD':
return
# Calculate position size
account_balance = self.get_account_balance()
entry_price = analysis.get('entry_price', 0)
stop_loss = analysis.get('stop_loss', 0)
position_size = self.calculate_position_size(
account_balance, confidence, entry_price, stop_loss
)
# Check risk limits
if not self.check_risk_limits(symbol, action, position_size):
return
# Execute trade
try:
if action == 'BUY':
order = self.exchange.create_market_buy_order(
symbol, position_size / entry_price
)
self.logger.info(f"Executed BUY order for {symbol}: {order}")
# Set stop loss and take profit
self.set_stop_loss_take_profit(symbol, order, analysis)
elif action == 'SELL':
# Implementation for sell orders
pass
except Exception as e:
self.logger.error(f"Error executing trade: {e}")
Advanced Features and Monitoring
Performance Tracking and Analytics
Add comprehensive performance monitoring:
def track_performance(self):
"""
Track and log trading performance metrics
"""
# Calculate key metrics
total_trades = self.get_total_trades()
win_rate = self.calculate_win_rate()
avg_return = self.calculate_average_return()
sharpe_ratio = self.calculate_sharpe_ratio()
max_drawdown = self.calculate_max_drawdown()
performance_data = {
'timestamp': datetime.now(),
'total_trades': total_trades,
'win_rate': win_rate,
'avg_return': avg_return,
'sharpe_ratio': sharpe_ratio,
'max_drawdown': max_drawdown,
'account_balance': self.get_account_balance()
}
self.logger.info(f"Performance Update: {performance_data}")
# Save to performance log
self.save_performance_data(performance_data)
News Sentiment Integration
Implement news sentiment analysis:
def get_news_sentiment(self, symbol: str) -> str:
"""
Analyze news sentiment for the given cryptocurrency
Args:
symbol: Trading pair symbol
Returns:
Sentiment analysis summary
"""
# Extract base currency from symbol
base_currency = symbol.split('/')[0]
# Fetch recent news (placeholder implementation)
news_headlines = self.fetch_crypto_news(base_currency)
if not news_headlines:
return "No recent news available"
# Analyze sentiment with Llama 3.3
sentiment_prompt = f"""
Analyze the sentiment of these cryptocurrency news headlines for {base_currency}:
{chr(10).join(news_headlines)}
Provide a brief sentiment summary focusing on:
1. Overall sentiment (Positive/Negative/Neutral)
2. Key themes or concerns
3. Potential market impact
Keep the response concise (2-3 sentences).
"""
try:
response = self.ollama_client.chat(
model='llama3.3',
messages=[
{
'role': 'system',
'content': 'You are a financial news sentiment analyst. Provide concise, objective sentiment analysis.'
},
{
'role': 'user',
'content': sentiment_prompt
}
]
)
return response['message']['content']
except Exception as e:
self.logger.error(f"Error in sentiment analysis: {e}")
return "Sentiment analysis unavailable"
Deployment and Production Setup
Docker Configuration
Create a production-ready Docker setup:
# Dockerfile
FROM python:3.9-slim
# Install system dependencies
RUN apt-get update && apt-get install -y \
curl \
&& rm -rf /var/lib/apt/lists/*
# Install Ollama
RUN curl -fsSL https://ollama.ai/install.sh | sh
# Set working directory
WORKDIR /app
# Copy requirements and install Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY . .
# Create volume for logs and data
VOLUME ["/app/logs", "/app/data"]
# Expose port for monitoring
EXPOSE 8000
# Start script
CMD ["python", "main.py"]
Environment Configuration
Create a secure environment configuration:
# config.py
import os
from dotenv import load_dotenv
load_dotenv()
class Config:
# Exchange API credentials
EXCHANGE_NAME = os.getenv('EXCHANGE_NAME', 'binance')
API_KEY = os.getenv('API_KEY')
API_SECRET = os.getenv('API_SECRET')
# Trading parameters
RISK_PERCENTAGE = float(os.getenv('RISK_PERCENTAGE', '0.02'))
MIN_CONFIDENCE = float(os.getenv('MIN_CONFIDENCE', '0.7'))
MAX_POSITIONS = int(os.getenv('MAX_POSITIONS', '5'))
# Monitoring
CHECK_INTERVAL = int(os.getenv('CHECK_INTERVAL', '300'))
LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO')
# Symbols to trade
TRADING_SYMBOLS = os.getenv('TRADING_SYMBOLS', 'BTC/USDT,ETH/USDT,ADA/USDT').split(',')
Main Application Runner
Create the main application entry point:
# main.py
from trading_bot import OllamaLlama33TradingBot
from config import Config
import logging
def main():
"""
Main application entry point
"""
# Configure logging
logging.basicConfig(
level=getattr(logging, Config.LOG_LEVEL),
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# Initialize trading bot
bot = OllamaLlama33TradingBot(
exchange_name=Config.EXCHANGE_NAME,
api_key=Config.API_KEY,
api_secret=Config.API_SECRET
)
# Set trading parameters
bot.risk_percentage = Config.RISK_PERCENTAGE
bot.min_confidence = Config.MIN_CONFIDENCE
bot.max_positions = Config.MAX_POSITIONS
# Start trading loop
bot.run_trading_loop(
symbols=Config.TRADING_SYMBOLS,
check_interval=Config.CHECK_INTERVAL
)
if __name__ == "__main__":
main()
Performance Optimization and Scaling
Parallel Processing for Multiple Assets
Implement concurrent analysis for better performance:
import asyncio
import aiohttp
from concurrent.futures import ThreadPoolExecutor
class OptimizedTradingBot(OllamaLlama33TradingBot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.executor = ThreadPoolExecutor(max_workers=4)
async def analyze_symbols_parallel(self, symbols: List[str]):
"""
Analyze multiple symbols in parallel for better performance
Args:
symbols: List of trading pairs to analyze
"""
tasks = []
for symbol in symbols:
task = asyncio.create_task(self.analyze_symbol_async(symbol))
tasks.append(task)
results = await asyncio.gather(*tasks, return_exceptions=True)
for symbol, result in zip(symbols, results):
if isinstance(result, Exception):
self.logger.error(f"Error analyzing {symbol}: {result}")
else:
self.process_analysis_result(symbol, result)
async def analyze_symbol_async(self, symbol: str):
"""
Asynchronous symbol analysis
Args:
symbol: Trading pair symbol
Returns:
Analysis result
"""
loop = asyncio.get_event_loop()
# Fetch market data in thread pool
market_data = await loop.run_in_executor(
self.executor, self.get_market_data, symbol
)
# Fetch news sentiment in thread pool
news_sentiment = await loop.run_in_executor(
self.executor, self.get_news_sentiment, symbol
)
# Analyze with Llama 3.3
analysis = await loop.run_in_executor(
self.executor, self.analyze_market_with_llama,
symbol, market_data, news_sentiment
)
return analysis
Monitoring and Alerting System
Real-time Monitoring Dashboard
Create a web-based monitoring interface:
# monitoring.py
from flask import Flask, render_template, jsonify
import json
from datetime import datetime
app = Flask(__name__)
class TradingMonitor:
def __init__(self, trading_bot):
self.bot = trading_bot
self.performance_data = []
self.alerts = []
def add_performance_data(self, data):
"""Add performance data point"""
self.performance_data.append(data)
# Keep only last 1000 data points
if len(self.performance_data) > 1000:
self.performance_data.pop(0)
def add_alert(self, alert_type, message):
"""Add system alert"""
alert = {
'timestamp': datetime.now().isoformat(),
'type': alert_type,
'message': message
}
self.alerts.append(alert)
# Keep only last 100 alerts
if len(self.alerts) > 100:
self.alerts.pop(0)
@app.route('/')
def dashboard():
"""Main dashboard page"""
return render_template('dashboard.html')
@app.route('/api/status')
def api_status():
"""API endpoint for bot status"""
return jsonify({
'status': 'running',
'uptime': '24h 15m',
'active_positions': len(monitor.bot.get_open_positions()),
'account_balance': monitor.bot.get_account_balance(),
'daily_pnl': monitor.bot.calculate_daily_pnl()
})
@app.route('/api/performance')
def api_performance():
"""API endpoint for performance data"""
return jsonify(monitor.performance_data)
@app.route('/api/alerts')
def api_alerts():
"""API endpoint for system alerts"""
return jsonify(monitor.alerts)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000, debug=False)
Security Best Practices
API Security Implementation
Implement robust security measures:
# security.py
import hashlib
import hmac
import time
from cryptography.fernet import Fernet
class SecurityManager:
def __init__(self):
self.encryption_key = Fernet.generate_key()
self.cipher = Fernet(self.encryption_key)
def encrypt_credentials(self, credentials: str) -> str:
"""
Encrypt sensitive credentials
Args:
credentials: Raw credentials string
Returns:
Encrypted credentials
"""
return self.cipher.encrypt(credentials.encode()).decode()
def decrypt_credentials(self, encrypted_credentials: str) -> str:
"""
Decrypt sensitive credentials
Args:
encrypted_credentials: Encrypted credentials
Returns:
Decrypted credentials
"""
return self.cipher.decrypt(encrypted_credentials.encode()).decode()
def validate_api_signature(self, payload: str, signature: str, secret: str) -> bool:
"""
Validate API webhook signatures
Args:
payload: Request payload
signature: Provided signature
secret: Secret key
Returns:
True if signature is valid
"""
expected_signature = hmac.new(
secret.encode(),
payload.encode(),
hashlib.sha256
).hexdigest()
return hmac.compare_digest(signature, expected_signature)
Troubleshooting Common Issues
Connection and API Problems
Common issues and solutions:
Exchange API Rate Limits:
def handle_rate_limit(self, retry_after: int = 60):
"""
Handle exchange API rate limiting
Args:
retry_after: Seconds to wait before retry
"""
self.logger.warning(f"Rate limit hit, waiting {retry_after} seconds")
time.sleep(retry_after)
Ollama Connection Issues:
def ensure_ollama_connection(self):
"""
Ensure Ollama service is running and responsive
"""
try:
# Test connection with simple prompt
response = self.ollama_client.chat(
model='llama3.3',
messages=[{'role': 'user', 'content': 'Hello'}]
)
return True
except Exception as e:
self.logger.error(f"Ollama connection failed: {e}")
return False
Market Data Gaps:
def handle_data_gaps(self, market_data: pd.DataFrame) -> pd.DataFrame:
"""
Handle missing data in market feeds
Args:
market_data: DataFrame with potential gaps
Returns:
Cleaned DataFrame
"""
# Forward fill missing values
market_data = market_data.fillna(method='ffill')
# Drop rows with insufficient data
market_data = market_data.dropna()
return market_data
Advanced Trading Strategies
Multi-Timeframe Analysis
Implement sophisticated multi-timeframe analysis:
def multi_timeframe_analysis(self, symbol: str) -> Dict:
"""
Analyze symbol across multiple timeframes
Args:
symbol: Trading pair symbol
Returns:
Combined analysis across timeframes
"""
timeframes = ['1h', '4h', '1d']
analyses = {}
for timeframe in timeframes:
market_data = self.get_market_data(symbol, timeframe)
if not market_data.empty:
analyses[timeframe] = self.analyze_market_with_llama(
symbol, market_data
)
# Combine analyses with Llama 3.3
combined_prompt = f"""
Analyze these multi-timeframe signals for {symbol}:
1-Hour Analysis: {analyses.get('1h', 'No data')}
4-Hour Analysis: {analyses.get('4h', 'No data')}
Daily Analysis: {analyses.get('1d', 'No data')}
Provide a unified trading recommendation that considers all timeframes.
Weight longer timeframes more heavily for trend direction.
"""
try:
response = self.ollama_client.chat(
model='llama3.3',
messages=[
{
'role': 'system',
'content': 'You are an expert at multi-timeframe analysis. Provide unified trading recommendations.'
},
{
'role': 'user',
'content': combined_prompt
}
]
)
return json.loads(response['message']['content'])
except Exception as e:
self.logger.error(f"Error in multi-timeframe analysis: {e}")
return {"action": "HOLD", "confidence": 0}
Portfolio Rebalancing Strategy
Implement intelligent portfolio rebalancing:
def portfolio_rebalancing(self, target_allocations: Dict[str, float]):
"""
Rebalance portfolio based on target allocations
Args:
target_allocations: Dictionary of symbol -> target percentage
"""
current_portfolio = self.get_current_portfolio()
total_value = sum(current_portfolio.values())
rebalance_actions = []
for symbol, target_pct in target_allocations.items():
current_value = current_portfolio.get(symbol, 0)
current_pct = current_value / total_value if total_value > 0 else 0
target_value = total_value * target_pct
difference = target_value - current_value
if abs(difference) > total_value * 0.05: # 5% threshold
action = "BUY" if difference > 0 else "SELL"
rebalance_actions.append({
'symbol': symbol,
'action': action,
'amount': abs(difference),
'current_pct': current_pct,
'target_pct': target_pct
})
# Execute rebalancing with Llama 3.3 validation
for action in rebalance_actions:
self.execute_rebalance_action(action)
def execute_rebalance_action(self, action: Dict):
"""
Execute portfolio rebalancing action
Args:
action: Rebalancing action dictionary
"""
# Validate rebalancing with Llama 3.3
validation_prompt = f"""
Validate this portfolio rebalancing action:
Symbol: {action['symbol']}
Action: {action['action']}
Amount: ${action['amount']:.2f}
Current Allocation: {action['current_pct']:.1%}
Target Allocation: {action['target_pct']:.1%}
Current Market Conditions: {self.assess_market_conditions()}
Should this rebalancing action be executed now?
Consider market timing and volatility.
Response format: {"execute": true/false, "reasoning": "explanation"}
"""
try:
response = self.ollama_client.chat(
model='llama3.3',
messages=[
{
'role': 'system',
'content': 'You are a portfolio management expert. Validate rebalancing decisions.'
},
{
'role': 'user',
'content': validation_prompt
}
]
)
validation = json.loads(response['message']['content'])
if validation.get('execute', False):
self.logger.info(f"Executing rebalancing: {action}")
# Execute the actual trade
self.execute_rebalance_trade(action)
else:
self.logger.info(f"Skipping rebalancing: {validation.get('reasoning', 'No reason given')}")
except Exception as e:
self.logger.error(f"Error in rebalancing validation: {e}")
Testing and Backtesting Framework
Backtesting Engine
Create a comprehensive backtesting system:
# backtesting.py
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
class BacktestEngine:
def __init__(self, trading_bot, start_date: str, end_date: str, initial_balance: float = 10000):
"""
Initialize backtesting engine
Args:
trading_bot: Trading bot instance
start_date: Backtest start date (YYYY-MM-DD)
end_date: Backtest end date (YYYY-MM-DD)
initial_balance: Starting balance for backtest
"""
self.bot = trading_bot
self.start_date = datetime.strptime(start_date, '%Y-%m-%d')
self.end_date = datetime.strptime(end_date, '%Y-%m-%d')
self.initial_balance = initial_balance
self.current_balance = initial_balance
self.positions = {}
self.trade_history = []
self.performance_metrics = {}
def run_backtest(self, symbols: List[str]) -> Dict:
"""
Run complete backtest simulation
Args:
symbols: List of trading pairs to backtest
Returns:
Backtest results and performance metrics
"""
self.logger.info(f"Starting backtest from {self.start_date} to {self.end_date}")
current_date = self.start_date
while current_date <= self.end_date:
# Simulate trading for each symbol
for symbol in symbols:
self.simulate_trading_day(symbol, current_date)
# Move to next day
current_date += timedelta(days=1)
# Log progress
if current_date.day == 1: # Monthly progress
self.logger.info(f"Backtest progress: {current_date.strftime('%Y-%m')}")
# Calculate final performance metrics
self.calculate_performance_metrics()
return {
'initial_balance': self.initial_balance,
'final_balance': self.current_balance,
'total_return': (self.current_balance - self.initial_balance) / self.initial_balance,
'total_trades': len(self.trade_history),
'performance_metrics': self.performance_metrics,
'trade_history': self.trade_history
}
def simulate_trading_day(self, symbol: str, date: datetime):
"""
Simulate trading for one day
Args:
symbol: Trading pair symbol
date: Date to simulate
"""
# Fetch historical data for this date
market_data = self.get_historical_data(symbol, date)
if market_data.empty:
return
# Analyze with Llama 3.3 (using historical context)
analysis = self.bot.analyze_market_with_llama(symbol, market_data)
# Execute trading decision in simulation
if analysis['confidence'] >= self.bot.min_confidence:
self.execute_simulated_trade(symbol, analysis, date)
def execute_simulated_trade(self, symbol: str, analysis: Dict, date: datetime):
"""
Execute trade in simulation environment
Args:
symbol: Trading pair symbol
analysis: Trading analysis
date: Trade date
"""
action = analysis.get('action', 'HOLD')
if action == 'HOLD':
return
entry_price = analysis.get('entry_price', 0)
stop_loss = analysis.get('stop_loss', 0)
take_profit = analysis.get('take_profit', 0)
# Calculate position size
position_size = self.bot.calculate_position_size(
self.current_balance, analysis['confidence'], entry_price, stop_loss
)
# Record trade
trade = {
'date': date,
'symbol': symbol,
'action': action,
'entry_price': entry_price,
'position_size': position_size,
'stop_loss': stop_loss,
'take_profit': take_profit,
'confidence': analysis['confidence']
}
self.trade_history.append(trade)
# Update simulated balance
if action == 'BUY':
self.current_balance -= position_size
self.positions[symbol] = trade
elif action == 'SELL' and symbol in self.positions:
# Calculate profit/loss
buy_trade = self.positions[symbol]
profit = (entry_price - buy_trade['entry_price']) * (position_size / entry_price)
self.current_balance += position_size + profit
del self.positions[symbol]
def calculate_performance_metrics(self):
"""
Calculate comprehensive performance metrics
"""
if not self.trade_history:
return
# Convert trades to DataFrame for analysis
trades_df = pd.DataFrame(self.trade_history)
# Calculate win rate
profitable_trades = len([t for t in self.trade_history if self.calculate_trade_profit(t) > 0])
total_trades = len(self.trade_history)
win_rate = profitable_trades / total_trades if total_trades > 0 else 0
# Calculate average return
returns = [self.calculate_trade_return(t) for t in self.trade_history]
avg_return = np.mean(returns) if returns else 0
# Calculate Sharpe ratio
if len(returns) > 1:
sharpe_ratio = np.mean(returns) / np.std(returns) * np.sqrt(252) # Annualized
else:
sharpe_ratio = 0
# Calculate maximum drawdown
balance_history = self.calculate_balance_history()
max_drawdown = self.calculate_max_drawdown(balance_history)
self.performance_metrics = {
'win_rate': win_rate,
'avg_return': avg_return,
'sharpe_ratio': sharpe_ratio,
'max_drawdown': max_drawdown,
'total_trades': total_trades,
'profitable_trades': profitable_trades
}
def generate_backtest_report(self, results: Dict) -> str:
"""
Generate comprehensive backtest report
Args:
results: Backtest results dictionary
Returns:
Formatted report string
"""
report = f"""
# Ollama Llama 3.3 Trading Bot Backtest Report
## Test Period
Start Date: {self.start_date.strftime('%Y-%m-%d')}
End Date: {self.end_date.strftime('%Y-%m-%d')}
Duration: {(self.end_date - self.start_date).days} days
## Financial Performance
Initial Balance: ${self.initial_balance:,.2f}
Final Balance: ${results['final_balance']:,.2f}
Total Return: {results['total_return']:.2%}
Total Trades: {results['total_trades']}
## Performance Metrics
Win Rate: {self.performance_metrics['win_rate']:.2%}
Average Return per Trade: {self.performance_metrics['avg_return']:.2%}
Sharpe Ratio: {self.performance_metrics['sharpe_ratio']:.2f}
Maximum Drawdown: {self.performance_metrics['max_drawdown']:.2%}
## Trade Analysis
Profitable Trades: {self.performance_metrics['profitable_trades']}
Losing Trades: {self.performance_metrics['total_trades'] - self.performance_metrics['profitable_trades']}
## Risk Assessment
Risk-Adjusted Return: {results['total_return'] / max(self.performance_metrics['max_drawdown'], 0.01):.2f}
"""
return report
Live Trading Validation
Implement paper trading validation:
class PaperTradingValidator:
def __init__(self, trading_bot):
"""
Initialize paper trading validator
Args:
trading_bot: Trading bot instance
"""
self.bot = trading_bot
self.paper_balance = 10000 # Starting paper balance
self.paper_positions = {}
self.paper_trades = []
self.validation_active = True
def validate_strategy(self, duration_days: int = 30):
"""
Run paper trading validation for specified duration
Args:
duration_days: Number of days to run validation
"""
self.logger.info(f"Starting {duration_days}-day paper trading validation")
start_time = datetime.now()
end_time = start_time + timedelta(days=duration_days)
while datetime.now() < end_time and self.validation_active:
# Run paper trading simulation
self.simulate_paper_trading()
# Wait for next check
time.sleep(300) # Check every 5 minutes
# Generate validation report
validation_results = self.generate_validation_report()
self.logger.info(f"Paper trading validation completed: {validation_results}")
return validation_results
def simulate_paper_trading(self):
"""
Simulate paper trading with current market conditions
"""
symbols = ['BTC/USDT', 'ETH/USDT', 'ADA/USDT'] # Example symbols
for symbol in symbols:
# Get real-time market data
market_data = self.bot.get_market_data(symbol)
if market_data.empty:
continue
# Analyze with Llama 3.3
analysis = self.bot.analyze_market_with_llama(symbol, market_data)
# Execute paper trade
if analysis['confidence'] >= self.bot.min_confidence:
self.execute_paper_trade(symbol, analysis)
def execute_paper_trade(self, symbol: str, analysis: Dict):
"""
Execute paper trade
Args:
symbol: Trading pair symbol
analysis: Trading analysis
"""
action = analysis.get('action', 'HOLD')
if action == 'HOLD':
return
current_price = self.bot.get_current_price(symbol)
position_size = self.bot.calculate_position_size(
self.paper_balance, analysis['confidence'],
current_price, analysis.get('stop_loss', 0)
)
paper_trade = {
'timestamp': datetime.now(),
'symbol': symbol,
'action': action,
'price': current_price,
'position_size': position_size,
'confidence': analysis['confidence'],
'analysis': analysis
}
self.paper_trades.append(paper_trade)
# Update paper balance
if action == 'BUY':
self.paper_balance -= position_size
self.paper_positions[symbol] = paper_trade
elif action == 'SELL' and symbol in self.paper_positions:
buy_trade = self.paper_positions[symbol]
profit = (current_price - buy_trade['price']) * (position_size / current_price)
self.paper_balance += position_size + profit
del self.paper_positions[symbol]
Production Deployment Guide
Cloud Deployment Configuration
Deploy your trading bot to the cloud:
# docker-compose.yml
version: '3.8'
services:
trading-bot:
build: .
environment:
- EXCHANGE_NAME=${EXCHANGE_NAME}
- API_KEY=${API_KEY}
- API_SECRET=${API_SECRET}
- RISK_PERCENTAGE=${RISK_PERCENTAGE}
- MIN_CONFIDENCE=${MIN_CONFIDENCE}
volumes:
- ./logs:/app/logs
- ./data:/app/data
restart: unless-stopped
networks:
- trading-network
depends_on:
- redis
- prometheus
redis:
image: redis:7-alpine
volumes:
- redis-data:/data
networks:
- trading-network
prometheus:
image: prom/prometheus:latest
ports:
- "9090:9090"
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
networks:
- trading-network
grafana:
image: grafana/grafana:latest
ports:
- "3000:3000"
environment:
- GF_SECURITY_ADMIN_PASSWORD=admin
volumes:
- grafana-data:/var/lib/grafana
networks:
- trading-network
volumes:
redis-data:
grafana-data:
networks:
trading-network:
driver: bridge
Monitoring and Alerting Setup
Configure comprehensive monitoring:
# alerts.py
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import requests
import json
class AlertManager:
def __init__(self, config):
"""
Initialize alert manager
Args:
config: Alert configuration dictionary
"""
self.email_config = config.get('email', {})
self.slack_config = config.get('slack', {})
self.telegram_config = config.get('telegram', {})
self.alert_thresholds = config.get('thresholds', {})
def send_email_alert(self, subject: str, message: str):
"""
Send email alert
Args:
subject: Email subject
message: Alert message
"""
try:
msg = MIMEMultipart()
msg['From'] = self.email_config['from']
msg['To'] = self.email_config['to']
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
server = smtplib.SMTP(self.email_config['smtp_server'], self.email_config['smtp_port'])
server.starttls()
server.login(self.email_config['username'], self.email_config['password'])
server.send_message(msg)
server.quit()
except Exception as e:
print(f"Error sending email alert: {e}")
def send_slack_alert(self, message: str):
"""
Send Slack alert
Args:
message: Alert message
"""
try:
payload = {
'text': message,
'channel': self.slack_config['channel'],
'username': 'Trading Bot'
}
response = requests.post(
self.slack_config['webhook_url'],
json=payload
)
if response.status_code != 200:
print(f"Slack alert failed: {response.status_code}")
except Exception as e:
print(f"Error sending Slack alert: {e}")
def check_alert_conditions(self, trading_bot):
"""
Check if any alert conditions are met
Args:
trading_bot: Trading bot instance
"""
# Check account balance
balance = trading_bot.get_account_balance()
if balance < self.alert_thresholds.get('min_balance', 1000):
self.send_critical_alert(f"Low account balance: ${balance:.2f}")
# Check daily P&L
daily_pnl = trading_bot.calculate_daily_pnl()
if daily_pnl < self.alert_thresholds.get('max_daily_loss', -500):
self.send_critical_alert(f"Daily loss limit exceeded: ${daily_pnl:.2f}")
# Check bot health
if not trading_bot.is_healthy():
self.send_critical_alert("Trading bot health check failed")
def send_critical_alert(self, message: str):
"""
Send critical alert via all channels
Args:
message: Critical alert message
"""
subject = "CRITICAL: Trading Bot Alert"
full_message = f"CRITICAL ALERT: {message}\n\nTime: {datetime.now()}"
# Send via all configured channels
if self.email_config:
self.send_email_alert(subject, full_message)
if self.slack_config:
self.send_slack_alert(full_message)
if self.telegram_config:
self.send_telegram_alert(full_message)
Advanced Risk Management
Dynamic Risk Adjustment
Implement adaptive risk management:
class DynamicRiskManager:
def __init__(self, trading_bot):
"""
Initialize dynamic risk manager
Args:
trading_bot: Trading bot instance
"""
self.bot = trading_bot
self.risk_history = []
self.performance_history = []
self.volatility_factor = 1.0
self.confidence_factor = 1.0
def adjust_risk_parameters(self):
"""
Dynamically adjust risk parameters based on performance
"""
# Calculate recent performance metrics
recent_performance = self.calculate_recent_performance()
market_volatility = self.calculate_market_volatility()
# Adjust risk based on performance
if recent_performance['win_rate'] > 0.6:
# Increase risk when performing well
self.confidence_factor = min(self.confidence_factor * 1.1, 1.5)
elif recent_performance['win_rate'] < 0.4:
# Decrease risk when performing poorly
self.confidence_factor = max(self.confidence_factor * 0.9, 0.5)
# Adjust risk based on volatility
if market_volatility > 0.05: # High volatility
self.volatility_factor = 0.7
elif market_volatility < 0.02: # Low volatility
self.volatility_factor = 1.2
else:
self.volatility_factor = 1.0
# Update bot risk parameters
base_risk = 0.02 # 2% base risk
adjusted_risk = base_risk * self.confidence_factor * self.volatility_factor
self.bot.risk_percentage = max(min(adjusted_risk, 0.05), 0.005) # Cap between 0.5% and 5%
self.bot.logger.info(f"Risk adjusted to {self.bot.risk_percentage:.3f} "
f"(Confidence: {self.confidence_factor:.2f}, "
f"Volatility: {self.volatility_factor:.2f})")
def calculate_recent_performance(self) -> Dict:
"""
Calculate recent performance metrics
Returns:
Dictionary with performance metrics
"""
recent_trades = self.bot.get_recent_trades(days=7)
if not recent_trades:
return {'win_rate': 0.5, 'avg_return': 0}
profitable_trades = sum(1 for trade in recent_trades if trade['profit'] > 0)
win_rate = profitable_trades / len(recent_trades)
avg_return = sum(trade['return'] for trade in recent_trades) / len(recent_trades)
return {
'win_rate': win_rate,
'avg_return': avg_return,
'total_trades': len(recent_trades)
}
def calculate_market_volatility(self) -> float:
"""
Calculate current market volatility
Returns:
Market volatility measure
"""
# Calculate volatility across major pairs
symbols = ['BTC/USDT', 'ETH/USDT']
volatilities = []
for symbol in symbols:
market_data = self.bot.get_market_data(symbol, '1h', 24)
if not market_data.empty:
returns = market_data['close'].pct_change().dropna()
volatility = returns.std()
volatilities.append(volatility)
return np.mean(volatilities) if volatilities else 0.03
Conclusion: Your 24/7 Cryptocurrency Trading Assistant
Building an Ollama Llama 3.3 trading bot transforms your cryptocurrency investment strategy from reactive to proactive. This comprehensive system operates continuously, making intelligent decisions based on market data, news sentiment, and advanced AI analysis.
The bot's key advantages include:
Continuous Operation: Never miss market opportunities due to sleep or other commitments. Your bot analyzes markets and executes trades around the clock.
AI-Powered Analysis: Llama 3.3's advanced reasoning capabilities identify patterns and opportunities that traditional trading algorithms miss.
Risk Management: Sophisticated risk controls protect your capital while maximizing profit potential through dynamic position sizing and stop-loss management.
Adaptive Learning: The system continuously improves its trading strategies based on market performance and changing conditions.
Comprehensive Monitoring: Real-time alerts and performance tracking keep you informed of your bot's activities and results.
Remember to start with paper trading or small amounts to validate your strategy before scaling up. The cryptocurrency market's volatility requires careful risk management, and this bot provides the tools to trade intelligently while protecting your investment capital.
Your automated cryptocurrency investment strategy is now ready to work 24/7, freeing you from constant market monitoring while potentially improving your trading results through consistent, data-driven decision making.
Disclaimer: Cryptocurrency trading involves significant risk. This bot is for educational purposes. Always test thoroughly and never invest more than you can afford to lose. Past performance does not guarantee future results.