-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflask_code.py
More file actions
381 lines (332 loc) · 12.6 KB
/
flask_code.py
File metadata and controls
381 lines (332 loc) · 12.6 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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# Copy this code into the nano editor in your EC2
import io
import json
import sqlite3
from pathlib import Path
from flask import Flask, request, jsonify, send_file, render_template_string
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
app = Flask(__name__)
DB_PATH = Path(__file__).resolve().parent / "data.db"
def get_db():
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
return conn
def init_db():
conn = get_db()
conn.executescript("""
CREATE TABLE IF NOT EXISTS instructions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
instruction TEXT NOT NULL,
asset TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS weights_data (
id INTEGER PRIMARY KEY AUTOINCREMENT,
asset TEXT NOT NULL,
features_json TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS portfolio (
id INTEGER PRIMARY KEY AUTOINCREMENT,
balance REAL NOT NULL,
accuracy REAL NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS matrix (
id INTEGER PRIMARY KEY AUTOINCREMENT,
asset TEXT NOT NULL,
features_json TEXT NOT NULL,
weights_json TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
conn.commit()
conn.close()
@app.route("/weights", methods=["GET"])
def get_weights():
asset = request.args.get("asset")
conn = get_db()
if asset:
row = conn.execute(
"SELECT asset, features_json FROM weights_data WHERE asset = ? ORDER BY id DESC LIMIT 1",
(asset,),
).fetchone()
else:
row = conn.execute(
"SELECT asset, features_json FROM weights_data ORDER BY id DESC LIMIT 1"
).fetchone()
conn.close()
if row is None:
return jsonify({"asset": "BTC", "features": []}), 200
return jsonify({
"asset": row["asset"],
"features": json.loads(row["features_json"]),
}), 200
@app.route("/weights", methods=["POST"])
def post_weights():
data = request.get_json(force=True, silent=True) or {}
asset = (data.get("asset") or "BTC").strip().upper()
features = data.get("features", [])
if asset not in ("BTC", "ETH"):
asset = "BTC"
if not features or not isinstance(features, list):
return jsonify({"error": "features list required (13 strings)"}), 400
conn = get_db()
conn.execute(
"INSERT INTO weights_data (asset, features_json) VALUES (?, ?)",
(asset, json.dumps(features)),
)
conn.commit()
conn.close()
return jsonify({"ok": True, "asset": asset, "features": features}), 200
@app.route("/store_instruction", methods=["POST"])
def store_instruction():
data = request.get_json(force=True, silent=True) or {}
instruction = (data.get("instruction") or "").strip()
if not instruction:
return jsonify({"error": "instruction required"}), 400
asset = "ETH" if "ETHEREUM" in instruction.upper() or "ETH" in instruction.upper() else "BTC"
conn = get_db()
conn.execute(
"INSERT INTO instructions (instruction, asset) VALUES (?, ?)",
(instruction, asset),
)
conn.commit()
conn.close()
return jsonify({"ok": True, "instruction": instruction, "asset": asset}), 200
@app.route("/instruction", methods=["GET"])
def get_instruction():
conn = get_db()
row = conn.execute(
"SELECT instruction, asset, created_at FROM instructions ORDER BY id DESC LIMIT 1"
).fetchone()
conn.close()
if row is None:
return jsonify({"instruction": None, "asset": "BTC"}), 200
return jsonify({
"instruction": row["instruction"],
"asset": row["asset"],
"created_at": row["created_at"],
}), 200
@app.route("/portfolio", methods=["POST"])
def post_portfolio():
data = request.get_json(force=True, silent=True) or {}
balance = data.get("balance")
accuracy = data.get("accuracy")
if balance is None or accuracy is None:
return jsonify({"error": "balance and accuracy required"}), 400
conn = get_db()
conn.execute(
"INSERT INTO portfolio (balance, accuracy) VALUES (?, ?)",
(float(balance), float(accuracy)),
)
conn.commit()
row = conn.execute(
"SELECT balance, accuracy FROM portfolio ORDER BY id DESC LIMIT 1"
).fetchone()
conn.close()
return jsonify({"balance": row["balance"], "accuracy": row["accuracy"]}), 200
@app.route("/portfolio", methods=["GET"])
def get_portfolio():
conn = get_db()
row = conn.execute(
"SELECT balance, accuracy FROM portfolio ORDER BY id DESC LIMIT 1"
).fetchone()
conn.close()
if row is None:
return jsonify({"balance": 0.0, "accuracy": 0.0}), 200
return jsonify({"balance": row["balance"], "accuracy": row["accuracy"]}), 200
@app.route("/graph", methods=["GET"])
def get_graph():
conn = get_db()
rows = conn.execute("SELECT balance, accuracy FROM portfolio ORDER BY id").fetchall()
conn.close()
if not rows:
return jsonify({"error": "no data yet"}), 404
balances = [r["balance"] for r in rows]
accuracies = [r["accuracy"] for r in rows]
trade_nums = list(range(1, len(rows) + 1))
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8), sharex=True)
ax1.plot(trade_nums, balances, color="tab:blue")
ax1.set_ylabel("Balance")
ax1.set_title("Portfolio Balance Over Trades")
ax1.grid(True, alpha=0.3)
ax2.plot(trade_nums, accuracies, color="tab:orange")
ax2.set_ylabel("Accuracy")
ax2.set_xlabel("Trade #")
ax2.set_title("Accuracy Over Trades")
ax2.grid(True, alpha=0.3)
fig.tight_layout()
buf = io.BytesIO()
fig.savefig(buf, format="png")
plt.close(fig)
buf.seek(0)
response = send_file(buf, mimetype="image/png")
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
return response
@app.route("/dashboard")
def dashboard():
return render_template_string("""
<!doctype html>
<html>
<head>
<title>Live Graph</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
img { max-width: 100%; height: auto; border: 1px solid #ddd; }
table { border-collapse: collapse; margin-top: 10px; }
th, td { border: 1px solid #ddd; padding: 6px 12px; text-align: right; }
th { background: #f5f5f5; }
button { padding: 8px 20px; font-size: 16px; margin: 10px 0; cursor: pointer; }
#status { color: green; margin-left: 10px; }
</style>
</head>
<body>
<h1>Live Portfolio Graph</h1>
<button id="flushBtn" onclick="flushData()">Flush All Data</button>
<span id="status"></span>
<h2>Active Model</h2>
<div id="matrix-asset" style="font-size:18px; font-weight:bold; margin:8px 0;">Asset: --</div>
<div id="matrix-equation" style="font-family:monospace; font-size:14px; background:#f9f9f9; padding:10px; border:1px solid #ddd; border-radius:4px; overflow-x:auto; white-space:nowrap;">No matrix data yet</div>
<div id="matrix-time" style="font-size:12px; color:#888; margin-top:4px;"></div>
<br>
<img id="graph" src="/graph" alt="Portfolio graph">
<h2>Portfolio History</h2>
<table>
<thead><tr><th>#</th><th>Balance</th><th>Accuracy</th></tr></thead>
<tbody id="ptable"></tbody>
</table>
<script>
const graph = document.getElementById("graph");
const ptable = document.getElementById("ptable");
const status = document.getElementById("status");
const matrixAsset = document.getElementById("matrix-asset");
const matrixEq = document.getElementById("matrix-equation");
const matrixTime = document.getElementById("matrix-time");
function refreshGraph() {
fetch("/graph?t=" + Date.now())
.then(resp => {
if (!resp.ok) {
graph.style.display = "none";
return null;
}
return resp.blob();
})
.then(blob => {
if (blob) {
graph.src = URL.createObjectURL(blob);
graph.style.display = "block";
}
});
}
function refreshPortfolio() {
fetch("/portfolio?t=" + Date.now())
.then(r => r.json())
.then(data => {
if (!data.length) {
ptable.innerHTML = "<tr><td colspan='3'>No data</td></tr>";
return;
}
ptable.innerHTML = data.map((row, i) =>
"<tr><td>" + (i+1) + "</td><td>" + row.balance.toFixed(2) + "</td><td>" + row.accuracy.toFixed(4) + "</td></tr>"
).join("");
});
}
function flushData() {
fetch("/flush", { method: "POST" })
.then(r => r.json())
.then(() => {
status.textContent = "Flushed!";
refreshGraph();
refreshPortfolio();
setTimeout(() => status.textContent = "", 2000);
});
}
function refreshMatrix() {
Promise.all([
fetch("/matrix?t=" + Date.now()).then(r => r.json()),
fetch("/weights?t=" + Date.now()).then(r => r.json())
]).then(([matrixData, weightsData]) => {
if (!matrixData.weights || matrixData.weights.length === 0) {
matrixAsset.textContent = "Asset: --";
matrixEq.textContent = "No matrix data yet";
matrixTime.textContent = "";
return;
}
// use feature names from /weights, numerical weights from /matrix
const features = weightsData.features && weightsData.features.length === matrixData.weights.length
? weightsData.features
: matrixData.features;
matrixAsset.textContent = "Asset: " + matrixData.asset;
const terms = features.map((f, i) => {
const w = matrixData.weights[i];
const wStr = (Math.abs(w) < 0.001 && w !== 0) ? w.toExponential(3) : w.toFixed(4);
return wStr + " x " + f;
});
matrixEq.textContent = "y = " + terms.join(" + ");
matrixTime.textContent = matrixData.created_at ? "Updated: " + matrixData.created_at : "";
});
}
setInterval(() => { refreshGraph(); refreshPortfolio(); refreshMatrix(); }, 2000);
refreshPortfolio();
refreshMatrix();
</script>
</body>
</html>
""")
@app.route("/matrix", methods=["POST"])
def post_matrix():
data = request.get_json(force=True, silent=True) or {}
asset = (data.get("asset") or "BTC").strip().upper()
features = data.get("features", [])
weights = data.get("weights", [])
if not features or not isinstance(features, list):
return jsonify({"error": "features list required"}), 400
if not weights or not isinstance(weights, list):
return jsonify({"error": "weights list required"}), 400
if len(features) != len(weights):
return jsonify({"error": "features and weights must be the same length"}), 400
conn = get_db()
conn.execute(
"INSERT INTO matrix (asset, features_json, weights_json) VALUES (?, ?, ?)",
(asset, json.dumps(features), json.dumps(weights)),
)
conn.commit()
conn.close()
return jsonify({"ok": True, "asset": asset, "features": features, "weights": weights}), 200
@app.route("/matrix", methods=["GET"])
def get_matrix():
conn = get_db()
row = conn.execute(
"SELECT asset, features_json, weights_json, created_at FROM matrix ORDER BY id DESC LIMIT 1"
).fetchone()
conn.close()
if row is None:
return jsonify({"asset": "BTC", "features": [], "weights": []}), 200
return jsonify({
"asset": row["asset"],
"features": json.loads(row["features_json"]),
"weights": json.loads(row["weights_json"]),
"created_at": row["created_at"],
}), 200
@app.route("/flush", methods=["POST"])
def flush_portfolio():
conn = get_db()
conn.execute("DELETE FROM portfolio")
conn.commit()
conn.close()
return jsonify({"ok": True}), 200
_db_initialized = False
@app.before_request
def ensure_db():
global _db_initialized
if not _db_initialized:
init_db()
_db_initialized = True
if __name__ == "__main__":
init_db()
app.run(host="0.0.0.0", port=5000, debug=False)