Repository navigation
Expand file tree
/
Copy pathsend.py
More file actions
62 lines (55 loc) · 1.95 KB
/
Copy pathsend.py
File metadata and controls
62 lines (55 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import requests
import time
# ----- Step 1: Fetch latest ETH price from Coinbase -----
def get_latest_price():
url = "https://api.coinbase.com/v2/prices/ETH-USD/spot"
try:
data = requests.get(url, timeout=5).json()
if "data" not in data or "amount" not in data["data"]:
print(f"Error fetching price: {data}")
return None
return float(data["data"]["amount"])
except Exception as e:
print(f"Exception: {e}")
return None
# ----- Step 2: Update price history -----
price_history = []
def update_price_history(max_len=50):
price = get_latest_price()
if price is None:
return price_history
price_history.append(price)
if len(price_history) > max_len:
price_history.pop(0)
return price_history
# ----- Step 3: Compute simple moving average -----
def compute_sma(prices):
if len(prices) == 0:
return None
return sum(prices) / len(prices)
# ----- Step 4: Simulate trading -----
balance = 1000 # USD
crypto = 0
def check_trade(prices):
global balance, crypto
sma = compute_sma(prices)
if sma is None or len(prices) < 5:
return
price = prices[-1]
# Buy if price is 2% below SMA
if price < sma * 0.98 and balance > 0:
crypto += balance / price
balance = 0
print(f"BUY at ${price:.2f} | Crypto: {crypto:.6f}")
# Sell if price is 2% above SMA
elif price > sma * 1.02 and crypto > 0:
balance += crypto * price
crypto = 0
print(f"SELL at ${price:.2f} | Balance: ${balance:.2f}")
print(f"Current Price: ${price:.2f} | SMA: ${sma:.2f} | Balance: ${balance:.2f} | Crypto: {crypto:.6f}")
# ----- Step 5: Run the bot every few seconds -----
print("Starting ETH real-time trading simulation using Coinbase API...")
while True:
update_price_history()
check_trade(price_history)
time.sleep(5) # checks every 5 seconds