Skip to content

Instantly share code, notes, and snippets.

@rollendxavier
Last active January 2, 2025 04:36
Show Gist options
  • Save rollendxavier/b2e334d87f35bb899c5e4aa081b2445d to your computer and use it in GitHub Desktop.
Save rollendxavier/b2e334d87f35bb899c5e4aa081b2445d to your computer and use it in GitHub Desktop.
Leveraging CoinGecko API with Azure Functions for Serverless Crypto Solutions
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Net;
using System.Net.Mail;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace CoinGecko.CryptoAlerts
{
public static class CheckCryptoPrices
{
private static readonly HttpClient client = new HttpClient();
[FunctionName("CheckCryptoPrices")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string apiKey = Environment.GetEnvironmentVariable("COINGECKO_API_KEY");
string gmailPassword = Environment.GetEnvironmentVariable("GMAIL_PASSWORD");
string alertEmail = Environment.GetEnvironmentVariable("ALERT_EMAIL");
string responseString = await client.GetStringAsync($"https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum&vs_currencies=usd&x_cg_pro_api_key={apiKey}");
var prices = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, decimal>>>(responseString);
decimal bitcoinPrice = prices["bitcoin"]["usd"];
decimal ethereumPrice = prices["ethereum"]["usd"];
if (bitcoinPrice < 30000)
{
// Send alert email
var fromAddress = new MailAddress(alertEmail, "Crypto Alert");
var toAddress = new MailAddress(alertEmail, "Crypto Alert Recipient");
const string subject = "Bitcoin Price Alert";
string body = $"Bitcoin price dropped below $30,000! Current price: ${bitcoinPrice}\nEthereum price: ${ethereumPrice}";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, gmailPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
log.LogInformation("Bitcoin price dropped below $30,000! Email alert sent.");
}
return new OkObjectResult(prices);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment