-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
216 lines (174 loc) · 6.11 KB
/
agent.py
File metadata and controls
216 lines (174 loc) · 6.11 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
"""
Asset Alpha Trading Agent - Final Strategy
Backtest results across 107 competition-length windows:
avg=-4.36% best=+6.66% worst=-22.58%
UP markets: avg=+2.85%
DOWN markets: avg=-8.70%
"""
import os
import time
import requests
import numpy as np
from collections import deque
# ============================
# CONFIG
# ============================
API_URL = os.getenv("API_URL", "https://algotrading.sanyamchhabra.in")
API_KEY = os.getenv("TEAM_API_KEY", "ak_792c7f0c8632e2c645a0597919f438cd")
HEADERS = {"X-API-Key": API_KEY}
TICK_SLEEP = 8
POS_PCT = 0.55
STOP_LOSS = 0.02
# ============================
# STATE
# ============================
prices = deque(maxlen=500)
entry_price = None
tick_count = 0
# ============================
# API HELPERS
# ============================
def api_get(endpoint, retries=3):
for attempt in range(retries):
try:
url = API_URL.rstrip("/") + endpoint
r = requests.get(url, headers=HEADERS, timeout=5)
print(f" [DEBUG] GET {url} → status={r.status_code} body={r.text[:80]}")
if r.status_code == 200 and r.text.strip():
return r.json()
except Exception as e:
print(f" [DEBUG] GET attempt {attempt+1} error: {e}")
time.sleep(1)
return None
def api_post(endpoint, body, retries=3):
for attempt in range(retries):
try:
url = API_URL.rstrip("/") + endpoint
r = requests.post(url, json=body, headers=HEADERS, timeout=5)
print(f" [DEBUG] POST {url} → status={r.status_code} body={r.text[:80]}")
if r.status_code == 200 and r.text.strip():
return r.json()
except Exception as e:
print(f" [DEBUG] POST attempt {attempt+1} error: {e}")
time.sleep(1)
return None
def get_price(): return api_get("/api/price")
def get_portfolio(): return api_get("/api/portfolio")
def buy(qty): return api_post("/api/buy", {"quantity": qty})
def sell(qty): return api_post("/api/sell", {"quantity": qty})
# ============================
# WARM START
# ============================
print(f"API_URL = {API_URL}")
print(f"API_KEY = {API_KEY[:8]}...")
print("Loading history...")
hist = api_get("/api/history")
if hist:
for bar in hist[-300:]:
prices.append(float(bar["close"]))
print(f"History loaded: {len(prices)} bars")
# ============================
# SIGNAL
# ============================
def compute_signal(p_arr, is_first_tick):
"""
Final strategy:
- Buy immediately on first tick
- Only sell on strong confirmed downtrend
- Re-enter immediately when quiet/recovering
"""
if is_first_tick:
return "BUY", "FIRST_TICK"
n = len(p_arr)
if n < 52:
return "BUY", "WARMING_BUY"
p = p_arr
w30 = p[-30:]
mean_30 = w30.mean()
std_30 = w30.std() + 1e-9
z = (p[-1] - mean_30) / std_30
vol_5 = np.std(p[-5:])
vol_30 = np.std(w30) + 1e-9
vol_ratio = vol_5 / vol_30
slope_10 = (p[-1] - p[-11]) / p[-11]
slope_30 = (p[-1] - p[-31]) / p[-31]
slope_50 = (p[-1] - p[-51]) / p[-51]
# SELL signals
if vol_ratio > 4.0 and slope_10 < 0:
return "SELL", f"VOL_SPIKE vol={vol_ratio:.1f}x slope10={slope_10:.4f}"
if slope_10 < -0.004 and slope_30 < -0.003 and slope_50 < -0.003:
return "SELL", f"DOWNTREND s10={slope_10:.4f} s30={slope_30:.4f} s50={slope_50:.4f}"
if z > 2.0 and slope_10 < 0:
return "SELL", f"OVERBOUGHT z={z:.2f}"
# BUY signals
if vol_ratio < 2.5 and z < 1.5 and slope_10 >= 0:
return "BUY", f"QUIET_UP vol={vol_ratio:.1f}x z={z:.2f}"
if z < -1.5:
return "BUY", f"OVERSOLD z={z:.2f}"
return "HOLD", f"z={z:.2f} vol={vol_ratio:.1f}x s10={slope_10:.4f}"
# ============================
# MAIN LOOP
# ============================
print("Agent running. Ctrl+C to stop.\n")
while True:
try:
tick = get_price()
port = get_portfolio()
if not tick or not port:
print(f" [WARN] No data received. tick={tick} port={port}. Retrying...")
time.sleep(TICK_SLEEP)
continue
price = float(tick["close"])
tick_num = tick.get("tick_number", "?")
phase = tick.get("phase", "")
if phase == "closed":
print("Market closed. Exiting.")
break
prices.append(price)
tick_count += 1
shares = int(port["shares"])
cash = float(port["cash"])
net = float(port["net_worth"])
pnl_pct = float(port["pnl_pct"])
if shares > 0 and entry_price is None:
entry_price = price
is_first = (tick_count == 1)
arr_p = np.array(prices)
# Stop loss check
stop_triggered = False
if shares > 0 and entry_price:
if (price - entry_price) / entry_price < -STOP_LOSS:
stop_triggered = True
if stop_triggered:
signal, reason = "SELL", f"STOP_LOSS entry={entry_price:.4f}"
else:
signal, reason = compute_signal(arr_p, is_first)
# Guard against invalid state
if signal == "BUY" and shares > 0:
signal = "HOLD"
if signal == "SELL" and shares == 0:
signal = "HOLD"
print(
f"TICK={tick_num:>5} | {signal:<4} | "
f"P={price:.4f} | SH={shares} | "
f"NW=${net:,.0f} | PNL={pnl_pct:+.2f}% | {reason}"
)
# Execute BUY
if signal == "BUY":
qty = int((net * POS_PCT) / price)
if qty > 0:
result = buy(qty)
entry_price = price
print(f" → BUY {qty} @ {price:.4f}")
# Execute SELL
elif signal == "SELL":
result = sell(shares)
trade_pnl = ((price - entry_price) / entry_price * 100) if entry_price else 0
print(f" → SELL {shares} @ {price:.4f} | trade={trade_pnl:+.2f}%")
entry_price = None
except KeyboardInterrupt:
print("\nStopped.")
break
except Exception as e:
print(f"ERROR: {e}")
time.sleep(TICK_SLEEP)