Get Customized Crypto Updates on Telegram Using Python and EODHD

Step by step guide using python websockets and EODHD

Pranjal Saxena
Coinmonks
Published in
8 min readJun 11, 2024

--

Photo by Anna Tarazevich

Cryptocurrencies have surged in popularity over the past decade. As digital assets, their prices can fluctuate wildly. This volatility makes real-time updates crucial for traders and investors. Knowing the exact moment when a price jumps or drops can be the difference between profit and loss.

EODHD, a financial data API offers a robust solution for accessing financial data. Their WebSocket API provides live updates, enabling users to stay ahead of market movements. Unlike traditional APIs that require repeated requests for data, WebSockets maintain a persistent connection. This means you receive data as soon as it’s available, without the need for constant polling.

In today’s fast-paced trading environment, timely information is everything. Whether you’re trading Bitcoin, Ethereum, or other cryptocurrencies, having instant access to market data can enhance your decision-making process. Real-time notifications allow you to react quickly, capturing opportunities as they arise and mitigating risks before they escalate.

Telegram is a powerful platform for instant communication. By integrating EODHD with Telegram, you can set up a personalized notification system. This system will alert you to significant market changes, right on your mobile device or desktop. It’s like having a personal assistant watching the markets for you, 24/7.

Setting up this system involves several steps. First, you’ll need to create a Telegram bot. This bot will be your messenger, delivering updates directly to your chat. Next, you’ll connect to the EODHD WebSocket API to start receiving live data. Finally, you’ll write a script that processes this data and sends alerts based on predefined conditions.

This article will guide you through each step in detail. We’ll start by creating a Telegram bot using BotFather. Then, we’ll retrieve your chat ID to ensure the bot knows where to send messages. After that, we’ll set up a customized WebSocket client to connect to EODHD. This client will monitor cryptocurrency prices and volumes in real-time.

By the end of this guide, you’ll have a fully functional system for receiving real-time cryptocurrency updates on Telegram. This setup not only saves time but also ensures you never miss critical market movements. So, let’s dive in and set up your personalized crypto notification system using Python, EODHD, and Telegram.

EODHD WebSocket

EODHD offers real-time data access via their WebSocket API. This API provides immediate, continuous data streams for cryptocurrencies, stocks, and forex markets. Unlike traditional APIs, which require repeated requests, WebSocket maintains a persistent connection. This allows data to flow seamlessly, ensuring you receive updates as soon as they occur.

EODHD’s WebSocket API supports various market data endpoints:

For example, to subscribe to cryptocurrency data, you can use:

{"action": "subscribe", "symbols": "BTC-USD,ETH-USD"}

This will start streaming real-time updates for Bitcoin and Ethereum. The data received includes fields such as:
- **s**: Ticker code (e.g., BTC-USD)
- **p**: Last traded price
- **q**: Quantity of the trade
- **t**: Timestamp in milliseconds

This API is available within EODHD’s All-In-One and Intraday packages, offering updates with a delay of less than 50 milliseconds. This is crucial for high-frequency trading where milliseconds matter.

For more details and to start using the EODHD WebSocket API, you can visit their official documentation.

Setting Up Telegram Bot

To receive real-time crypto updates, we need to set up a Telegram bot. Follow these simple steps:

1. Create a Telegram Bot

  • Open Telegram and Start a Chat with BotFather:
    — Open the Telegram app on your phone or desktop.
    — Search for BotFather in the search bar.
    — Start a chat with BotFather by clicking on its name.
  • Create a New Bot:
    — Type /start and send the message to initiate the conversation with BotFather.
    — Type /newbot and send the message to create a new bot.
    — BotFather will ask for a name for your bot. Enter a name, for example, PranjalCryptoAlertBot.
    — Next, choose a username for your bot. It must end in `bot` (e.g., PranjalCryptoAlertBot).
  • Receive the API Token:
    — After selecting the username, BotFather will generate and provide an API token.
    — This token will look something like 123456789:ABC-DEF1234ghIkl-zyx57W2v1u123ew11.
    — Save this token securely as it is needed to connect to the Telegram Bot API.

2. Get Your Chat ID

  • Send a Message to Your Bot:
    — Open Telegram and search for your new bot by its username.
    — Start a chat with the bot and send a message, like “Hi There!”.
  • Retrieve the Chat ID:
    — Use the Telegram Bot API to get updates and retrieve the chat ID.
    — Run the following Python script to get the chat ID:
import requests

url = f"https://api.telegram.org/bot{bot_token}/getUpdates"

response = requests.get(url)
data = response.json()

if data['ok']:
if len(data['result']) > 0:
for update in data['result']:
chat_id = update['message']['chat']['id']
print(f"Chat ID: {chat_id}")
else:
print("No new updates found.")
else:
print("Failed to get updates. Error:", data)

- Replace your_api_key with bot_token, the actual API token you received from BotFather.
— Run this script to get the chat ID from the updates.

By following these steps, you will have a Telegram bot set up and ready to receive messages. The next section will guide you through creating a customized WebSocket client to get real-time updates and send them to your Telegram bot.

Creating Customized WebSocket Client

To receive real-time cryptocurrency updates and send them to your Telegram bot, we need to create a customized WebSocket client. This client will connect to the EODHD WebSocket API, process the data, and send updates to your Telegram chat based on specific conditions.

1. Install Required Libraries

Before we start, ensure you have the necessary Python libraries installed. You need `websocket-client` and `requests` libraries:

pip install websocket-client requests

2. Create the WebSocket Client

Here’s a step-by-step guide to creating the WebSocket client:

  • Initialize the WebSocket Client:
    — Create a class that will handle the WebSocket connection, message processing, and Telegram notifications.
  • Handle Incoming Messages:
    — Process incoming data from EODHD and check for significant changes (e.g., price and volume).
  • Send Telegram Messages:
    — Use the Telegram Bot API to send messages to your chat.
  • Start the WebSocket Client:
    — Connect to the EODHD WebSocket API and start receiving data.

Python Implementation

Here’s a complete python code of a customized WebSocket client:

import websocket
import json
import threading
import time
import requests
from datetime import datetime

class EODHDWebSocketClient:
def __init__(self, api_key, endpoint, symbols, telegram_token, chat_id):
self.api_key = api_key
self.endpoint = endpoint
self.symbols = symbols
self.ws_url = f"wss://ws.eodhistoricaldata.com/ws/{endpoint}?api_token={api_key}"
self.ws = None
self.thread = None
self.telegram_token = telegram_token
self.chat_id = chat_id
self.data = {}

def on_message(self, ws, message):
data = json.loads(message)
symbol = data.get('s')
price = data.get('p')
volume = data.get('q')
timestamp = data.get('t')

if symbol and price and volume and timestamp:
try:
# Ensure the timestamp is a valid integer and in milliseconds
timestamp = int(timestamp) / 1000
data_time = datetime.utcfromtimestamp(timestamp)

if symbol not in self.data:
self.data[symbol] = []

self.data[symbol].append({
"price": float(price), # Convert price to float
"volume": float(volume), # Convert volume to float
"timestamp": data_time
})

# Send message for every update received to verify
self.send_telegram_message(f"Received update for {symbol}: Price={price}, Volume={volume}, Time={data_time}")
except Exception as e:
print(f"Error processing message: {e}")

def send_telegram_message(self, message):
url = f"https://api.telegram.org/bot{self.telegram_token}/sendMessage"
payload = {
"chat_id": self.chat_id,
"text": message
}
response = requests.post(url, data=payload)
print(response.json()) # Print response to verify message sending

def on_error(self, ws, error):
print(error)

def on_close(self, ws, close_status_code, close_msg):
print("WebSocket closed")

def on_open(self, ws):
subscribe_message = json.dumps({"action": "subscribe", "symbols": ",".join(self.symbols)})
ws.send(subscribe_message)

def start(self):
self.ws = websocket.WebSocketApp(self.ws_url,
on_open=self.on_open,
on_message=self.on_message,
on_error=self.on_error,
on_close=self.on_close)
self.thread = threading.Thread(target=self.ws.run_forever)
self.thread.start()

def stop(self):
if self.ws:
self.ws.close()
if self.thread:
self.thread.join()

Code Explanation

  1. Initialization:
    — The class EODHDWebSocketClient initializes with parameters for the API key, endpoint, symbols, Telegram token, and chat ID.
  2. Handling Messages:
    — The on_message method processes incoming messages, extracts relevant data, and stores it.
  3. Sending Messages:
    — The send_telegram_message method sends alerts to the specified Telegram chat.
  4. WebSocket Connection:
    — The start method connects to the EODHD WebSocket API and begins data streaming.

With this WebSocket client, you can receive real-time cryptocurrency updates and send customized alerts to your Telegram bot. The next section will cover processing live updates and sending alerts based on specific conditions.

Getting Live Updates

Now that we have our WebSocket client and Telegram bot set up, we can start receiving real-time cryptocurrency updates and sending them to Telegram. The code snippet below demonstrates how to integrate these components to get live updates and send notifications based on specific conditions.

1. Initialize WebSocket Client

First, set up your EODHD WebSocket client with the appropriate parameters, including your API key, the endpoint for cryptocurrency data, and the symbols you want to track.

api_key = "EODHD_API_KEY"
endpoint = "crypto"
symbols = ["SOL-USD"]

telegram_token = "bot_token"
chat_id = "chatID"

client = EODHDWebSocketClient(api_key, endpoint, symbols, telegram_token, chat_id)
client.start()

# Keep the notebook cell running to maintain the connection
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
client.stop()
Live Telegram Updates

2. Customizing Update Conditions

In the EODHDWebSocketClient class, the check_conditions method is where you can define the specific conditions for sending updates. For example, if you want to send an update when the price increases by 2% with increased volume within the last 5 minutes, you can customize this method accordingly.

def check_conditions(self, symbol):
data_points = self.data[symbol]
if len(data_points) < 2:
return

latest = data_points[-1]
oldest = data_points[0]

price_change = ((latest["price"] - oldest["price"]) / oldest["price"]) * 100
volume_change = latest["volume"] - oldest["volume"]

if price_change >= 2 and volume_change > 0:
message = f"Symbol: {symbol}\nPrice increased by {price_change:.2f}% with volume change {volume_change} in the last 5 minutes."
self.send_telegram_message(message)

With the above setup, your customized WebSocket client will continuously monitor real-time cryptocurrency data from EODHD and send notifications to your Telegram bot based on specified conditions. This integration allows you to stay updated on significant market movements instantly, helping you make informed decisions in your trading activities.

Conclusion

Integrating EODHD WebSocket API with Telegram allows you to receive real-time cryptocurrency updates instantly. This setup is invaluable for traders and investors who need to stay ahead of market movements.

We started by setting up a Telegram bot using BotFather. This bot serves as the messenger for delivering updates directly to your chat. We then retrieved the chat ID, ensuring our bot knows where to send the messages.

Next, we created a customized WebSocket client in Python. This client connects to the EODHD WebSocket API, which provides real-time data for cryptocurrencies. We used this client to monitor specific conditions, such as a 2% price increase within five minutes. When these conditions are met, the client sends an alert to the Telegram chat.

By following this guide, you now have a fully functional system that provides timely cryptocurrency updates. This system can save you time and ensure you never miss critical market movements. With EODHD’s robust data and Telegram’s instant messaging, you can make more informed trading decisions and stay ahead of the competition.

Feel free to customize the conditions and expand this setup to monitor multiple cryptocurrencies. This integration demonstrates the power of combining real-time data with instant notifications, enhancing your trading strategy and market awareness.

--

--