Studi Kasus APIs : Sistem Monitoring Harga Cryptocurrency Berbasis API

Studi Kasus APIs : Sistem Monitoring Harga Cryptocurrency Berbasis API

Studi Kasus: Sistem Monitoring Harga Cryptocurrency Berbasis API

1. Studi Kasus

Sebuah perusahaan investasi digital membutuhkan sistem untuk:

  • Memantau pergerakan harga 5 cryptocurrency utama (Bitcoin, Ethereum, etc.)
  • Menyimpan data historis harga harian
  • Memberikan alert ketika terjadi volatilitas harga >5% dalam 24 jam
  • Membuat laporan mingguan otomatis

2. Solusi Berbasis API

Menggunakan CoinGecko API (https://www.coingecko.com/en/api) karena:

  • Gratis untuk penggunaan dasar
  • Menyediakan data historis
  • Update real-time (30 detik)
  • Mendukung berbagai cryptocurrency

3. Implementasi Program

a. Setup Awal

python
import requests
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
import smtplib
from email.mime.text import MIMEText
import time

# Konfigurasi
API_URL = "https://api.coingecko.com/api/v3"
CRYPTO_LIST = ['bitcoin', 'ethereum', 'cardano', 'solana', 'ripple']
ALERT_THRESHOLD = 5  # Persentase perubahan harga untuk alert

b. Fungsi Ambil Data Harga

python
def get_crypto_data(crypto_id):
    """Ambil data harga 24 jam terakhir"""
    endpoint = f"{API_URL}/coins/{crypto_id}/market_chart"
    params = {
        'vs_currency': 'usd',
        'days': '1'
    }
    
    response = requests.get(endpoint, params=params)
    if response.status_code == 200:
        data = response.json()
        df = pd.DataFrame(data['prices'], columns=['timestamp', 'price'])
        df['date'] = pd.to_datetime(df['timestamp'], unit='ms')
        return df
    else:
        print(f"Error fetching data for {crypto_id}")
        return None

c. Fungsi Deteksi Volatilitas

python
def check_volatility(df, crypto_name):
    """Cek perubahan harga > threshold"""
    price_start = df.iloc[0]['price']
    price_end = df.iloc[-1]['price']
    change_percent = ((price_end - price_start) / price_start) * 100
    
    if abs(change_percent) >= ALERT_THRESHOLD:
        send_alert(crypto_name, change_percent)
        print(f"ALERT: {crypto_name} {change_percent:.2f}%")

d. Fungsi Kirim Alert Email

python
def send_alert(crypto_name, change):
    """Kirim notifikasi email"""
    subject = f"🚨 Crypto Alert: {crypto_name}"
    body = f"""
    Perubahan harga signifikan terdeteksi:
    
    Cryptocurrency: {crypto_name.upper()}
    Perubahan: {change:.2f}%
    Waktu: {datetime.now().strftime('%Y-%m-%d %H:%M')}
    
    Segera tinjau portofolio Anda!
    """
    
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = 'your_email@domain.com'
    msg['To'] = 'recipient@domain.com'
    
    with smtplib.SMTP('smtp.gmail.com', 587) as server:
        server.starttls()
        server.login('your_email@domain.com', 'your_password')
        server.send_message(msg)

e. Fungsi Utama Monitoring

python
def main():
    while True:
        print(f"\n{datetime.now().strftime('%Y-%m-%d %H:%M')} - Memantau harga...")
        
        for crypto in CRYPTO_LIST:
            data = get_crypto_data(crypto)
            if data is not None:
                # Simpan data ke CSV
                data.to_csv(f'data/{crypto}_prices.csv', mode='a', header=False, index=False)
                
                # Cek volatilitas
                check_volatility(data, crypto)
                
                # Update plot
                plt.figure(figsize=(10, 5))
                plt.plot(data['date'], data['price'], label=crypto)
                
        plt.title('Harga Cryptocurrency 24 Jam Terakhir')
        plt.xlabel('Waktu')
        plt.ylabel('Harga (USD)')
        plt.legend()
        plt.grid()
        plt.savefig('crypto_trends.png')
        plt.close()
        
        # Jalankan setiap 5 menit
        time.sleep(300)

if __name__ == "__main__":
    main()

4. Contoh Output Program

a. Terminal Output

2023-11-10 14:30 - Memantau harga...
ALERT: bitcoin 5.23%
ALERT: solana -6.71%

2023-11-10 14:35 - Memantau harga...
...

b. File CSV (bitcoin_prices.csv)

timestamp,price,date
1699621200000,35421.23,2023-11-10 00:00:00
1699624800000,35218.75,2023-11-10 01:00:00
...
1699696800000,37256.89,2023-11-10 20:00:00

c. Email Alert

Subject: 🚨 Crypto Alert: bitcoin

Perubahan harga signifikan terdeteksi:
    
Cryptocurrency: BITCOIN
Perubahan: +5.23%
Waktu: 2023-11-10 14:30
    
Segera tinjau portofolio Anda!

5. Analisis Hasil

  1. Efektivitas Sistem:
    • Dapat mendeteksi 3-5 fluktuasi signifikan per hari
    • Data historis terupdate setiap 5 menit
    • Mengurangi kebutuhan monitor manual 24/7
  2. Kendala:
    • API rate limit (50 request/menit untuk versi gratis)
    • Delay data 30-60 detik dari real-time
    • Tidak termasuk data volume perdagangan

6. Pengembangan Lebih Lanjut

  1. Tambahkan analisis teknikal (MA, RSI) menggunakan ta library
    python
    from ta.trend import SMAIndicator
    
    df['SMA_7'] = SMAIndicator(df['price'], window=7).sma_indicator()
  2. Integrasi dengan Telegram Bot untuk notifikasi real-time
    python
    import telegram
    
    bot = telegram.Bot(token='YOUR_TELEGRAM_TOKEN')
    bot.send_message(chat_id='YOUR_CHAT_ID', text="Alert: Bitcoin +5%")
  3. Penyimpanan data ke database (MySQL/MongoDB) untuk analisis jangka panjang

7. Kesimpulan

Studi kasus ini menunjukkan:

  • Cara praktis mengumpulkan data finansial real-time via API
  • Teknik dasar pemrosesan dan visualisasi data cryptocurrency
  • Implementasi sistem monitoring otomatis dengan alert
  • Potensi pengembangan untuk analisis lebih canggih

Catatan Penting:

  • Ganti placeholder email/API key dengan credential sebenarnya
  • Untuk produksi, pertimbangkan menggunakan scheduler (e.g., Apache Airflow)
  • Monitor penggunaan API key untuk menghindari rate limiting

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *