Bitcoin Price Tracking Bot
Build a comprehensive Bitcoin price monitoring system that tracks prices, analyzes market sentiment, sends alerts, and provides predictive insights using Venym Search APIs.
What You'll Build
Real-time Tracking
Monitor Bitcoin prices from multiple sources with automatic updates
Sentiment Analysis
Analyze market sentiment from news articles and social media
Smart Alerts
Price threshold alerts and sentiment change notifications
Historical Data
Store and analyze price history with trend analysis
Setup & Installation
Install Dependencies
Environment Configuration
# .env
VENYM_SEARCH_API_KEY=sk_live_64_HEX_CHARS_key_here
# Monitoring Settings
CHECK_INTERVAL_MINUTES=30
PRICE_THRESHOLD_HIGH=150000
PRICE_THRESHOLD_LOW=80000
# Email Alerts (optional)
EMAIL_ALERTS=true
EMAIL_FROM=your_email@gmail.com
EMAIL_TO=alerts@yourcompany.com
EMAIL_PASSWORD=your_app_password
SMTP_SERVER=smtp.gmail.com
SMTP_PORT=587Configuration Module
Create a configuration module to manage all settings, thresholds, and data sources.
# config.py
import os
from dotenv import load_dotenv
load_dotenv()
class Config:
# API Keys
VENYM_SEARCH_API_KEY = os.getenv('VENYM_SEARCH_API_KEY')
# Monitoring settings
CHECK_INTERVAL_MINUTES = int(os.getenv('CHECK_INTERVAL_MINUTES', 30))
PRICE_THRESHOLD_HIGH = float(os.getenv('PRICE_THRESHOLD_HIGH', 150000))
PRICE_THRESHOLD_LOW = float(os.getenv('PRICE_THRESHOLD_LOW', 80000))
# Data sources to monitor
SOURCES = [
'coinmarketcap.com/currencies/bitcoin',
'coingecko.com/en/coins/bitcoin',
'bloomberg.com/quote/XBTUSD:CUR',
'cnn.com/business/bitcoin',
'reuters.com/technology/bitcoin'
]
# Alert settings
EMAIL_ALERTS = os.getenv('EMAIL_ALERTS', 'False').lower() == 'true'
EMAIL_FROM = os.getenv('EMAIL_FROM')
EMAIL_TO = os.getenv('EMAIL_TO')
SMTP_SERVER = os.getenv('SMTP_SERVER', 'smtp.gmail.com')
SMTP_PORT = int(os.getenv('SMTP_PORT', 587))
EMAIL_PASSWORD = os.getenv('EMAIL_PASSWORD')
# Storage
DATA_FILE = 'bitcoin_data.csv'
LOG_FILE = 'bitcoin_tracker.log'Bitcoin Tracker Implementation
The core tracker class that handles data collection, analysis, and alerting using Venym Search APIs.
# bitcoin_tracker.py
import requests
import pandas as pd
import json
import re
import schedule
import time
import smtplib
from email.mime.text import MimeText
from email.mime.multipart import MimeMultipart
from datetime import datetime
import logging
from config import Config
class BitcoinTracker:
def __init__(self):
self.api_key = Config.VENYM_SEARCH_API_KEY
self.setup_logging()
self.data_history = self.load_existing_data()
def setup_logging(self):
logging.basicConfig(
filename=Config.LOG_FILE,
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
self.logger = logging.getLogger(__name__)
def load_existing_data(self):
try:
return pd.read_csv(Config.DATA_FILE)
except FileNotFoundError:
return pd.DataFrame(columns=[
'timestamp', 'current_price', 'market_cap',
'volume_24h', 'price_change_24h', 'sentiment_score',
'news_count', 'prediction_avg', 'source'
])
def search_bitcoin_info(self, query="Bitcoin price current market analysis"):
try:
response = requests.post(
"https://www.search.venym.io/api/v1/search",
headers={
"Authorization": "Bearer " + self.api_key,
"Content-Type": "application/json"
},
json={
"query": query,
"max_results": 10,
"auto_scrape_top": 5
}
)
response.raise_for_status()
return response.json()
except Exception as e:
self.logger.error(f"Search failed: {e}")
return None
def scrape_specific_source(self, url):
try:
response = requests.post(
"https://www.search.venym.io/api/v1/scrape",
headers={
"Authorization": "Bearer " + self.api_key,
"Content-Type": "application/json"
},
json={
"url": url,
"extract_options": ["title", "text", "metadata"]
}
)
response.raise_for_status()
return response.json()
except Exception as e:
self.logger.error(f"Scraping {url} failed: {e}")
return None
def extract_price_from_text(self, text):
patterns = [
r'\$([0-9]{1,3}(?:,[0-9]{3})*(?:\.[0-9]{2})?)',
r'([0-9]{1,3}(?:,[0-9]{3})*(?:\.[0-9]{2})?)\s*USD',
r'BTC[:\s]*\$?([0-9]{1,3}(?:,[0-9]{3})*(?:\.[0-9]{2})?)',
]
for pattern in patterns:
matches = re.findall(pattern, text, re.IGNORECASE)
if matches:
price_str = matches[0].replace(',', '')
try:
price = float(price_str)
if 1000 <= price <= 1000000:
return price
except ValueError:
continue
return None
def collect_data(self):
self.logger.info("Starting Bitcoin data collection...")
search_data = self.search_bitcoin_info()
if not search_data:
return None
current_price = None
for content in search_data.get('scraped_content', []):
if content.get('text'):
price = self.extract_price_from_text(content['text'])
if price:
current_price = price
break
if not current_price:
return None
data_record = {
'timestamp': datetime.now().isoformat(),
'current_price': current_price,
'news_count': len(search_data.get('search_results', [])),
}
new_row = pd.DataFrame([data_record])
self.data_history = pd.concat([self.data_history, new_row], ignore_index=True)
self.data_history.to_csv(Config.DATA_FILE, index=False)
return data_record
def start_monitoring(self):
print("Starting Bitcoin Price Tracker...")
schedule.every(Config.CHECK_INTERVAL_MINUTES).minutes.do(self.collect_data)
self.collect_data()
while True:
schedule.run_pending()
time.sleep(60)- Falls back to Scrape for specific sources if needed
- Extracts prices using regex patterns
- Analyzes sentiment from scraped content
- Sends email alerts for threshold breaches
- Stores historical data in CSV format
Main Script
Create a main script with command-line options for different modes of operation.
# main.py
from bitcoin_tracker import BitcoinTracker
import argparse
def main():
parser = argparse.ArgumentParser(description='Bitcoin Price Tracker')
parser.add_argument('--collect', action='store_true', help='Run one-time data collection')
parser.add_argument('--report', action='store_true', help='Show summary report')
parser.add_argument('--monitor', action='store_true', help='Start continuous monitoring')
args = parser.parse_args()
tracker = BitcoinTracker()
if args.collect:
data = tracker.collect_data()
if data:
print(f"Data collected: BTC ${data['current_price']:,.2f}")
elif args.monitor:
tracker.start_monitoring()
if __name__ == "__main__":
main()Usage & Testing
# Run one-time data collection
python main.py --collect
# Show current summary report
python main.py --report
# Start continuous monitoring (runs until stopped)
python main.py --monitorRun a one-time data collection to test everything is working:
python main.py --collectStart continuous monitoring (runs until stopped):
python main.py --monitorExpected Output
Starting Bitcoin Price Tracker...
Checking every 30 minutes
Alert thresholds: $80,000 - $150,000
INFO - Collected data: BTC $118,450.23, Sentiment: 2.3
INFO - Collected data: BTC $119,123.45, Sentiment: 1.8
INFO - Collected data: BTC $120,890.12, Sentiment: 3.1
SENTIMENT ALERT: POSITIVE shift detected (Change: 1.3)
Data collected: BTC $120,890.12
Email alert sent successfully
Bitcoin Tracker Summary Report
================================
Current Status:
- Latest Price: $120,890.12
- 24-Record Average: $119,456.78
- Change: +$2,890.12 (+2.45%)
- Average Sentiment: 2.4
Data Points: 48
Last Updated: 2025-07-22T15:30:42.123456Enhancement Ideas
Technical Analysis
Add moving averages, RSI, and other indicators
Social Media Monitoring
Track Twitter sentiment and Reddit discussions
Machine Learning Predictions
Train models on historical data for price forecasting
Webhook Notifications
Send alerts to Slack, Discord, or custom endpoints
Database Storage
Replace CSV with PostgreSQL or MongoDB
Web Dashboard
Build a Flask/FastAPI dashboard with charts
Troubleshooting
Price extraction fails
Check the regex patterns in extract_price_from_text(). Websites may change their format. Add debugging prints to see the scraped text.
High credit usage
Reduce auto_scrape_top value or increase CHECK_INTERVAL_MINUTES. Each scraped page costs 3 credits.
Email alerts not working
Check your email credentials and make sure you're using an app password for Gmail. Enable 2FA and generate an app-specific password.
Learn how to deploy this bot to AWS, Google Cloud, or a VPS for 24/7 monitoring.
Deployment GuideExplore other real-world applications like e-commerce monitoring and lead generation.