Hey Coders, welcome to my blog. Today, I’m excited to share a project I’ve been working on: the Cryptocurrency Notifications Alert System. This project leverages AWS services, Terraform, and Docker to fetch cryptocurrency data from an external API and send notifications via Amazon SNS.
Check my code at: https://github.com/Rene-Mayhrem/Crypto-Notifications
Follow me in LinkedIn if you want to connect: https://www.linkedin.com/in/renecruz-1202r/
Project Overview
The Cryptocurrency Notifications Alert System is designed to keep you updated on the latest cryptocurrency prices and market data. It fetches data from the CoinGecko API and sends notifications about the cryptocurrencies' status, prices, and other details via Amazon SNS.
Architecture Diagram
Here’s an overview of the system architecture:
Docker Containers: Used to run Terraform commands and package the Lambda function.
Terraform: Provisions AWS resources such as IAM roles, SNS topics, and Lambda functions.
AWS Services: Includes IAM, SNS, and Lambda to handle notifications and function execution.
Instructions
- Clone the repository:
git clone https://github.com/Rene-Mayhrem/Crypto-Notifications.git
cd Crypto-Notifications
- Create a zip ofthe Lambda function.
- lambda_function.py: Contains the lambda implementatino code.
- coins.txt: Contains a list of all rthe currencies to be analized
cd src
zip lambda_function.zip lambda_function.py coins.txt
- Create Environment variables: Create a
.env
file in the root directory with the following content:
API_KEY=your_api_key
AWS_ACCESS_KEY_ID=your_aws_access_key_id
AWS_SECRET_ACCESS_KEY=your_aws_secret_access_key
AWS_ACCOUNT_ID=your_aws_account_id
AWS_REGION=your_aws_region
AWS_TOPIC=crypto_notifications
- Create
terraform.tfvars
for variables: Create aterraform.tfvars
file in the root directory with the following content:
region = "your_aws_region"
account_id = "your_aws_account_id"
topic = "crypto_notifications"
- Add your email to the resource at
main.tf
line 49, where the email_subscription is created, in the endpoint part:
resource "aws_sns_topic_subscription" "email_subscription" {
topic_arn = aws_sns_topic.crypto_notifications.arn
protocol = "email"
endpoint = "your-email"
}
Project Structure:
The prioject direcotry is as follows:
.
├── .env
├── docker-compose.yml
├── policies
│ └── gd_notifications.json
├── src
│ ├── coins.txt
│ ├── lambda_function.py
│ └── lambda_function.zip
├── main.tf
├── terraform.tfvars
└── README.md
Terraform configuration
The Terraform configuration is used to provision the necessary AWS resources. Here’s a brief overview of the key resources:
IAM Role: Allows the Lambda function to publish messages to the SNS topic.
SNS Topic: Receives notifications about cryptocurrency updates.
Lambda Function: Executes the code to fetch cryptocurrency data and send notifications.
Lambda Function
The Lambda function fetches cryptocurrency data from the CoinGecko API and sends notifications via Amazon SNS. Here’s the code:
import os
import json
import urllib.request
import boto3
def format_crypto_data(crypto):
# Extract cryptocurrency details from the API response
name = crypto.get("name", "Unknown")
symbol = crypto.get("symbol", "Unknown")
current_price = crypto.get("market_data", {}).get("current_price", {}).get("usd", "Unknown")
market_cap = crypto.get("market_data", {}).get("market_cap", {}).get("usd", "Unknown")
total_volume = crypto.get("market_data", {}).get("total_volume", {}).get("usd", "Unknown")
# Format the extracted data into a readable message
return (
f"Cryptocurrency Update for {name} ({symbol}):\n"
f"Current Price: ${current_price}\n"
f"Market Cap: ${market_cap}\n"
f"Total Volume: ${total_volume}\n"
)
def lambda_handler(event, context):
# Get the SNS topic ARN from environment variables
sns_topic_arn = os.getenv("SNS_TOPIC_ARN")
# Initialize the SNS client
sns_client = boto3.client("sns")
# Path to the file containing cryptocurrency IDs
coins_file_path = "./coins.txt"
# Read the cryptocurrency IDs from the file
with open(coins_file_path, "r") as file:
crypto_ids = [line.strip() for line in file.readlines()]
# List to store formatted messages
messages = []
# Fetch data for each cryptocurrency ID
for crypto_id in crypto_ids:
api_url = f"https://api.coingecko.com/api/v3/coins/{crypto_id}"
try:
# Make a request to the CoinGecko API
with urllib.request.urlopen(api_url) as response:
# Parse the JSON response
data = json.loads(response.read().decode())
# Format the data into a readable message
message = format_crypto_data(data)
# Add the message to the list
messages.append(message)
except Exception as e:
# Print an error message if the API request fails
print(f"Error fetching data for {crypto_id}: {e}")
# Publish each message to the SNS topic
for message in messages:
try:
sns_client.publish(
TopicArn=sns_topic_arn,
Message=message,
Subject="Cryptocurrency Update"
)
except Exception as e:
# Print an error message if publishing to SNS fails
print(f"Error publishing message to SNS: {e}")
# Return a success response
return {
"statusCode": 200,
"body": json.dumps("Data processed and sent to SNS")
}
Running the prioject
- Initialize Terraform:
docker-compose run terraform_container init
- Apply the Terraform configuration:
docker-compose run terraform_container apply -auto-approve
- Deploy and test your lambda
- Go to AWS Lambda
- Open your created Lambda
- Create a test
- Check your email
- Destroy the Terraform-managed infrastructure (if needed):
docker-compose run terraform_container destroy -auto-approve
Conclusion
The Cryptocurrency Notifications Alert System is a powerful tool to stay updated on the latest cryptocurrency prices and market data. By leveraging AWS services, Terraform, and Docker, this project provides a scalable and efficient solution for real-time notifications. Future improvements could include adding more cryptocurrencies, enhancing the notification format, and integrating with other messaging platforms.
I hope you found this blog post helpful. Feel free to reach out with any questions or feedback!
Top comments (0)