DEV Community

2x lazymac
2x lazymac

Posted on

Building a Crypto Trading Signal API With Real-Time Binance Data

Binance provides one of the best free market data APIs available. Here's how to build a crypto trading signal API on top of it using Cloudflare Workers.

The Data Source

Binance REST API (no auth required for public market data):

# Current price
curl "https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT"

# 1-hour candlestick data
curl "https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1h&limit=100"

# Order book depth
curl "https://api.binance.com/api/v3/depth?symbol=BTCUSDT&limit=20"
Enter fullscreen mode Exit fullscreen mode

Signal Logic (Simplified)

function generateSignal(candles) {
  const closes = candles.map(c => parseFloat(c[4]));

  // Simple moving averages
  const sma20 = closes.slice(-20).reduce((a, b) => a + b) / 20;
  const sma50 = closes.slice(-50).reduce((a, b) => a + b) / 50;
  const current = closes[closes.length - 1];

  // RSI (simplified)
  const gains = [], losses = [];
  for (let i = 1; i < closes.length; i++) {
    const diff = closes[i] - closes[i-1];
    diff > 0 ? gains.push(diff) : losses.push(Math.abs(diff));
  }
  const rsi = 100 - (100 / (1 + (gains.slice(-14).reduce((a,b)=>a+b,0)/14) /
                                 (losses.slice(-14).reduce((a,b)=>a+b,0)/14)));

  if (sma20 > sma50 && rsi < 70 && current > sma20) return 'BUY';
  if (sma20 < sma50 && rsi > 30 && current < sma20) return 'SELL';
  return 'HOLD';
}
Enter fullscreen mode Exit fullscreen mode

Wrapping it as an API

// Cloudflare Worker
export default {
  async fetch(request) {
    const url = new URL(request.url);
    const symbol = url.searchParams.get('symbol') || 'BTCUSDT';
    const interval = url.searchParams.get('interval') || '1h';

    const klines = await fetch(
      `https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=${interval}&limit=100`
    ).then(r => r.json());

    const signal = generateSignal(klines);
    const price = parseFloat(klines[klines.length-1][4]);

    return Response.json({ symbol, signal, price, interval, timestamp: Date.now() });
  }
};
Enter fullscreen mode Exit fullscreen mode

Disclaimer: This is for educational purposes. Automated trading carries significant financial risk.

Crypto Signal API | Full API store

Top comments (0)