Building a Real-Time Forex Price Alert System with Python and Telegram

Introduction

In today’s fast-moving Forex market, timing is everything. Missing a price movement by even a few minutes can mean the difference between profit and loss. That’s why having a real-time price alert system is crucial for serious Forex traders. In this tutorial, we’ll build a powerful price monitoring system using Python and Telegram that runs on Alibaba Cloud’s serverless infrastructure, ensuring 24/7 uptime without the hassle of managing servers.

Why Build a Real-Time Forex Alert System?

Manual price monitoring is exhausting and inefficient. A good alert system provides:

Instant notifications when your target prices are reached
24/7 monitoring without human intervention
Multi-currency tracking for your entire portfolio
Cost-effective operation using serverless computing
Scalability to handle multiple currency pairs simultaneously

Architecture Overview: Leveraging Alibaba Cloud

Our system uses three key Alibaba Cloud services:

1. Function Compute – Serverless computing platform that runs our Python code without managing servers
2. TSDB (Time Series Database) – Optimized for storing and querying time-stamped Forex price data
3. CloudMonitor – Provides monitoring and alerting capabilities

This serverless architecture means you only pay for actual execution time, making it extremely cost-effective for retail traders.

Prerequisites

Before we begin, you’ll need:

• Python 3.8 or higher installed
• Alibaba Cloud account (free tier available)
• Telegram account and bot token
• Basic understanding of Python and APIs

Step 1: Setting Up Your Telegram Bot

First, let’s create a Telegram bot that will send us price alerts:

1. Open Telegram and search for @BotFather
2. Send /newbot command
3. Follow the prompts to name your bot
4. Save the API token provided

Here’s a Python script to test your Telegram bot:

import requests

def send_telegram_message(bot_token, chat_id, message):
    """
    Send a message via Telegram Bot API
    """
    url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
    
    payload = {
        'chat_id': chat_id,
        'text': message,
        'parse_mode': 'HTML'
    }
    
    try:
        response = requests.post(url, json=payload)
        return response.json()
    except Exception as e:
        print(f"Error sending message: {e}")
        return None

# Test your bot
BOT_TOKEN = 'your_bot_token_here'
CHAT_ID = 'your_chat_id_here'

send_telegram_message(
    BOT_TOKEN, 
    CHAT_ID, 
    "<b>Alert System Test</b>\n\nYour Forex alert bot is ready!"
)

Step 2: Fetching Real-Time Forex Data

We’ll use a Forex API to get real-time exchange rates. Here’s our price monitoring function:

import requests
import json
from datetime import datetime

class ForexMonitor:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://www.alphavantage.co/query"
    
    def get_exchange_rate(self, from_currency, to_currency):
        """
        Fetch current exchange rate for a currency pair
        """
        params = {
            'function': 'CURRENCY_EXCHANGE_RATE',
            'from_currency': from_currency,
            'to_currency': to_currency,
            'apikey': self.api_key
        }
        
        try:
            response = requests.get(self.base_url, params=params)
            data = response.json()
            
            rate_data = data['Realtime Currency Exchange Rate']
            
            return {
                'pair': f"{from_currency}/{to_currency}",
                'rate': float(rate_data['5. Exchange Rate']),
                'timestamp': rate_data['6. Last Refreshed'],
                'bid': float(rate_data['8. Bid Price']),
                'ask': float(rate_data['9. Ask Price'])
            }
        except Exception as e:
            print(f"Error fetching data: {e}")
            return None
    
    def check_price_threshold(self, current_rate, target_price, alert_type):
        """
        Check if price has crossed threshold
        alert_type: 'above' or 'below'
        """
        if alert_type == 'above':
            return current_rate >= target_price
        elif alert_type == 'below':
            return current_rate <= target_price
        return False

# Example usage
monitor = ForexMonitor('YOUR_API_KEY')
data = monitor.get_exchange_rate('EUR', 'USD')
print(f"EUR/USD: {data['rate']}")

Step 3: Deploying to Alibaba Cloud Function Compute

Alibaba Cloud Function Compute allows us to run our monitoring code serverlessly. Here’s our complete alert function:

import json
import requests
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest

def handler(event, context):
    """
    Main function handler for Alibaba Cloud Function Compute
    This function runs every 5 minutes via scheduled trigger
    """
    # Configuration
    BOT_TOKEN = context.credentials.access_key_id  # Store in environment
    CHAT_ID = context.credentials.access_key_secret
    
    # Define watchlist with target prices
    watchlist = [
        {'pair': 'EUR/USD', 'target': 1.0850, 'type': 'above'},
        {'pair': 'GBP/USD', 'target': 1.2600, 'type': 'below'},
        {'pair': 'USD/JPY', 'target': 149.50, 'type': 'above'}
    ]
    
    # Check each currency pair
    for watch in watchlist:
        from_curr, to_curr = watch['pair'].split('/')
        
        # Fetch current rate
        monitor = ForexMonitor('YOUR_API_KEY')
        data = monitor.get_exchange_rate(from_curr, to_curr)
        
        if data:
            # Check threshold
            triggered = monitor.check_price_threshold(
                data['rate'], 
                watch['target'], 
                watch['type']
            )
            
            if triggered:
                # Send alert
                message = f"""
<b>🚨 FOREX PRICE ALERT</b>

Pair: {data['pair']}
Current Rate: {data['rate']}
Target: {watch['target']}
Alert Type: {watch['type'].upper()}

Bid: {data['bid']}
Ask: {data['ask']}
Time: {data['timestamp']}
"""
                send_telegram_message(BOT_TOKEN, CHAT_ID, message)
                
                # Store in TSDB for historical analysis
                store_to_tsdb(data)
    
    return {
        'statusCode': 200,
        'body': json.dumps('Monitoring completed')
    }

def send_telegram_message(bot_token, chat_id, message):
    """Send alert via Telegram"""
    url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
    requests.post(url, json={'chat_id': chat_id, 'text': message, 'parse_mode': 'HTML'})

def store_to_tsdb(data):
    """Store price data in Alibaba Cloud TSDB for trend analysis"""
    # Implementation for TSDB connection
    pass

Step 4: Storing Data in Alibaba Cloud TSDB

Time Series Database (TSDB) is perfect for Forex data. Here’s how to integrate it:

from aliyun.log import LogClient
import time

class TSDBHandler:
    def __init__(self, endpoint, access_key_id, access_key_secret):
        self.endpoint = endpoint
        self.access_key_id = access_key_id
        self.access_key_secret = access_key_secret
    
    def write_forex_data(self, currency_pair, rate, timestamp):
        """
        Write Forex price to TSDB
        """
        metric_data = {
            'metric': 'forex.exchange.rate',
            'timestamp': int(time.time()),
            'value': rate,
            'tags': {
                'pair': currency_pair,
                'source': 'alphavantage'
            }
        }
        
        # Write to TSDB
        # Implementation depends on TSDB SDK
        print(f"Stored: {currency_pair} @ {rate}")
        return True
    
    def query_historical_data(self, currency_pair, start_time, end_time):
        """
        Query historical price data for analysis
        """
        # Query TSDB for trends
        pass

Step 5: Setting Up Scheduled Monitoring

Configure Function Compute to run every 5 minutes:

1. Log into Alibaba Cloud Console
2. Navigate to Function Compute
3. Create a new function with Python 3.9 runtime
4. Upload your code as a ZIP file
5. Add a Time Trigger: cron expression `0 */5 * * * *`
6. Configure environment variables for API keys

Advanced Features to Add

Once your basic system is running, consider these enhancements:

Multiple Alert Conditions: Support percentage changes, not just absolute prices
Historical Charts: Use TSDB data to generate price charts sent via Telegram
Risk Management: Calculate position sizes and stop-loss levels
Backtesting: Test your alert strategies against historical data
Multi-User Support: Allow multiple traders to subscribe to alerts

Cost Optimization on Alibaba Cloud

The serverless approach is extremely cost-effective:

• Function Compute: Free tier includes 1 million invocations/month
• TSDB: Pay only for storage and queries
• CloudMonitor: Basic monitoring is free
• Estimated monthly cost: $5-15 for moderate usage

Conclusion

You’ve now built a professional-grade real-time Forex price alert system that runs reliably on Alibaba Cloud’s serverless infrastructure. This system monitors currency pairs 24/7, sends instant Telegram notifications when price thresholds are met, and stores historical data for analysis – all without managing any servers.

The combination of Python’s simplicity, Telegram’s instant messaging, and Alibaba Cloud’s powerful serverless platform creates a robust solution that scales with your trading needs. Start with a few currency pairs, refine your thresholds, and gradually expand your monitoring capabilities.

Remember to implement proper error handling, secure your API keys, and regularly test your alerts to ensure they’re working correctly. Happy trading!