import time
import requests
import numpy as np
from binance.spot import Spot
# ---------------------------
# 1) Binance API Keys
# ---------------------------
API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
client = Spot(key=API_KEY, secret=API_SECRET)
# ---------------------------
# 2) RSI Calculation Function
# ---------------------------
def calculate_rsi(prices, period=14):
prices = np.array(prices)
delta = np.diff(prices)
gain = delta.clip(min=0)
loss = -delta.clip(max=0)
avg_gain = np.mean(gain[:period])
avg_loss = np.mean(loss[:period])
rs = avg_gain / (avg_loss if avg_loss != 0 else 1)
rsi = 100 - (100 / (1 + rs))
return rsi
# ---------------------------
# 3) Main Trading Loop
# ---------------------------
symbol = "BTCUSDT"
qty = 0.001 # buy/sell amount
while True:
# Get last 100 prices (1-minute)
url = f"https://api.binance.com/api/v3/klines?symbol={symbol}&interval=1m&limit=100"
data = requests.get(url).json()
closes = [float(x[4]) for x in data]
rsi = calculate_rsi(closes)
last_price = closes[-1]
print(f"Price: {last_price} | RSI: {rsi}")
# ---------------------------
# BUY Signal (RSI oversold)
# ---------------------------
if rsi < 30:
print("BUY SIGNAL TRIGGERED")
try:
order = client.new_order(
symbol=symbol,
side="BUY",
type="MARKET",
quantity=qty
)
print("Bought:", order)
except Exception as e:
print("Buy Error:", e)
# ---------------------------
# SELL Signal (RSI overbought)
# ---------------------------
if rsi > 70:
print("SELL SIGNAL TRIGGERED")
try:
order = client.new_order(
symbol=symbol,
side="SELL",
type="MARKET",
quantity=qty
)
print("Sold:", order)
except Exception as e:
print("Sell Error:", e)
time.sleep(15)
