PROSTLE commited on
Commit
7a3dfcd
·
unverified ·
1 Parent(s): 7015924

Update trader.py

Browse files
Files changed (1) hide show
  1. trader.py +101 -0
trader.py CHANGED
@@ -59,6 +59,93 @@ def toggle_bot() -> dict:
59
  return {"bot_active": state["bot_active"]}
60
 
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  def compute_dynamic_levels(
63
  current_price: float,
64
  atr: float,
@@ -210,6 +297,13 @@ def execute_buy(
210
  state["positions"][ticker] = position
211
  _save_state(state)
212
 
 
 
 
 
 
 
 
213
  return {
214
  "status": "bought",
215
  "ticker": ticker,
@@ -257,6 +351,13 @@ def execute_sell(ticker: str, current_price: float, reason: str) -> dict:
257
  del state["positions"][ticker]
258
  _save_state(state)
259
 
 
 
 
 
 
 
 
260
  return {
261
  "status": "sold",
262
  "ticker": ticker,
 
59
  return {"bot_active": state["bot_active"]}
60
 
61
 
62
+ def add_to_balance(amount: float, payment_id: str = "") -> dict:
63
+ """Add funds to the portfolio balance (wallet top-up)."""
64
+ with _lock:
65
+ state = _load_state()
66
+ state["balance"] += amount
67
+ state["balance"] = round(state["balance"], 2)
68
+ # Also bump initial_balance so reset reflects deposits
69
+ state["initial_balance"] = round(state.get("initial_balance", INITIAL_BALANCE) + amount, 2)
70
+ # Record transaction
71
+ txn = {
72
+ "type": "credit",
73
+ "amount": amount,
74
+ "payment_id": payment_id,
75
+ "timestamp": datetime.now().isoformat(),
76
+ "status": "success",
77
+ }
78
+ state.setdefault("wallet_transactions", []).append(txn)
79
+ _save_state(state)
80
+ return {"status": "success", "new_balance": state["balance"], "transaction": txn}
81
+
82
+
83
+ def withdraw_from_balance(amount: float) -> dict:
84
+ """Withdraw funds from the portfolio balance."""
85
+ with _lock:
86
+ state = _load_state()
87
+ if amount > state["balance"]:
88
+ return {"status": "error", "message": "Insufficient balance"}
89
+ state["balance"] -= amount
90
+ state["balance"] = round(state["balance"], 2)
91
+ state["initial_balance"] = round(state.get("initial_balance", INITIAL_BALANCE) - amount, 2)
92
+ txn = {
93
+ "type": "debit",
94
+ "amount": amount,
95
+ "timestamp": datetime.now().isoformat(),
96
+ "status": "success",
97
+ }
98
+ state.setdefault("wallet_transactions", []).append(txn)
99
+ _save_state(state)
100
+ return {"status": "success", "new_balance": state["balance"], "transaction": txn}
101
+
102
+
103
+ def get_wallet_transactions() -> list:
104
+ """Return wallet transaction history."""
105
+ with _lock:
106
+ state = _load_state()
107
+ return state.get("wallet_transactions", [])
108
+
109
+
110
+ def record_portfolio_snapshot(total_value: float):
111
+ """Record a portfolio value snapshot for the account value chart."""
112
+ with _lock:
113
+ state = _load_state()
114
+ snapshots = state.setdefault("value_history", [])
115
+ snapshots.append({
116
+ "timestamp": datetime.now().isoformat(),
117
+ "value": round(total_value, 2),
118
+ })
119
+ # Keep at most 500 snapshots
120
+ if len(snapshots) > 500:
121
+ snapshots[:] = snapshots[-500:]
122
+ _save_state(state)
123
+
124
+
125
+ def get_value_history() -> list:
126
+ """Return portfolio value snapshots for the account value chart."""
127
+ with _lock:
128
+ state = _load_state()
129
+
130
+ snapshots = list(state.get("value_history", []))
131
+
132
+ # If no snapshots yet, synthesize from trade history
133
+ if not snapshots:
134
+ initial = state.get("initial_balance", INITIAL_BALANCE)
135
+ created = state.get("created_at", datetime.now().isoformat())
136
+ snapshots.append({"timestamp": created, "value": initial})
137
+
138
+ running = initial
139
+ for t in state.get("trade_history", []):
140
+ running += t.get("profit", 0)
141
+ snapshots.append({
142
+ "timestamp": t.get("sell_time", t.get("buy_time", "")),
143
+ "value": round(running, 2),
144
+ })
145
+
146
+ return snapshots
147
+
148
+
149
  def compute_dynamic_levels(
150
  current_price: float,
151
  atr: float,
 
297
  state["positions"][ticker] = position
298
  _save_state(state)
299
 
300
+ # Record portfolio value snapshot
301
+ try:
302
+ pos_value = sum(p["shares"] * p["buy_price"] for p in state["positions"].values())
303
+ record_portfolio_snapshot(state["balance"] + pos_value)
304
+ except Exception:
305
+ pass
306
+
307
  return {
308
  "status": "bought",
309
  "ticker": ticker,
 
351
  del state["positions"][ticker]
352
  _save_state(state)
353
 
354
+ # Record portfolio value snapshot
355
+ try:
356
+ pos_value = sum(p["shares"] * p["buy_price"] for p in state["positions"].values())
357
+ record_portfolio_snapshot(state["balance"] + pos_value)
358
+ except Exception:
359
+ pass
360
+
361
  return {
362
  "status": "sold",
363
  "ticker": ticker,