sa1646 commited on
Commit
f044fd7
Β·
verified Β·
1 Parent(s): 7f14694

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +244 -0
app.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import subprocess
3
+ import time
4
+ import sys
5
+ import os
6
+
7
+ def run_main():
8
+ while True:
9
+ try:
10
+ result = subprocess.run([sys.executable, "monitor/web_dashboard.py"], cwd=os.getcwd())
11
+ if result.returncode != 0:
12
+ print("⚠️ Dashboard exited. Restarting in 10s...")
13
+ except KeyboardInterrupt:
14
+ break
15
+ except Exception as e:
16
+ print(f"⚠️ Crash detected: {e}. Restarting in 10s...")
17
+ time.sleep(10)
18
+
19
+ if __name__ == "__main__":
20
+ print("πŸ›‘οΈ Pegasus Guardian: Auto-recovery enabled")
21
+ run_main()
22
+ import random
23
+ from deap import base, creator, tools
24
+ class StrategyMesh:
25
+ def __init__(self, n_agents=100):
26
+ self.n_agents = n_agents
27
+ self.agents = self._init_agents()
28
+
29
+ def _init_agents(self):
30
+ agents = []
31
+ for _ in range(self.n_agents):
32
+ agent = {
33
+ "features": random.sample(["rsi", "volume", "funding", "volatility"], k=2),
34
+ "params": {
35
+ "rsi_threshold": random.uniform(30, 70),
36
+ "volume_mult": random.uniform(1.2, 3.0)
37
+ },
38
+ "fitness": 0.0
39
+ }
40
+ agents.append(agent)
41
+ return agents
42
+
43
+ def evolve(self, performance_data):
44
+ sorted_agents = sorted(self.agents, key=lambda x: x["fitness"], reverse=True)
45
+ top_20 = sorted_agents[:int(0.2 * len(sorted_agents))]
46
+ new_agents = [self._mutate(a) for a in top_20]
47
+ for _ in range(int(0.3 * self.n_agents)):
48
+ new_agents.append(self._random_agent())
49
+ self.agents = top_20 + new_agents
50
+
51
+ def _mutate(self, agent):
52
+ new_agent = agent.copy()
53
+ if "rsi_threshold" in new_agent["params"]:
54
+ new_agent["params"]["rsi_threshold"] = max(20, min(80, new_agent["params"]["rsi_threshold"] + random.uniform(-5, 5)))
55
+ return new_agent
56
+
57
+ def _random_agent(self):
58
+ return {
59
+ "features": random.sample(["rsi", "volume", "funding", "volatility"], k=2),
60
+ "params": {
61
+ "rsi_threshold": random.uniform(30, 70),
62
+ "volume_mult": random.uniform(1.2, 3.0)
63
+ },
64
+ "fitness": 0.0
65
+ }
66
+ class RiskController:
67
+ def __init__(self, config):
68
+ self.config = config["risk"]
69
+ self.daily_loss = 0.0
70
+
71
+ def should_hedge(self, volatility):
72
+ return self.config["hedge_on_volatility"] and volatility > 0.02
73
+
74
+ def can_trade(self, account_balance, current_drawdown):
75
+ if current_drawdown > self.config["max_daily_loss"]:
76
+ return False, "MAX DAILY LOSS HIT"
77
+ return True, "OK"
78
+ class Vault:
79
+ def __init__(self, config):
80
+ self.reserve = 0.0
81
+ self.ratio = config["vault"]["profit_reserve_ratio"]
82
+ self.threshold = config["vault"]["drawdown_threshold"]
83
+ self.inject_ratio = config["vault"]["inject_ratio"]
84
+
85
+ def add_profit(self, profit):
86
+ reserve_add = profit * self.ratio
87
+ self.reserve += reserve_add
88
+ return reserve_add
89
+
90
+ def inject_on_drawdown(self, drawdown):
91
+ if drawdown > self.threshold and self.reserve > 0:
92
+ inject = self.reserve * self.inject_ratio
93
+ self.reserve -= inject
94
+ return inject
95
+ return 0.0
96
+ import json
97
+ import random
98
+ import ccxt
99
+
100
+ class MarketFeed:
101
+ def __init__(self, config_path="config/settings.json"):
102
+ with open(config_path) as f:
103
+ self.config = json.load(f)
104
+ self.mode = self.config["mode"]
105
+
106
+ if self.mode == "live":
107
+ self.exchange = ccxt.binance({
108
+ 'apiKey': self.config["api"]["key"],
109
+ 'secret': self.config["api"]["secret"],
110
+ 'enableRateLimit': True,
111
+ })
112
+
113
+ def get_ticker(self, symbol="BTC/USDT"):
114
+ if self.mode == "paper":
115
+ base = 60000
116
+ return {
117
+ "symbol": symbol,
118
+ "price": round(base + random.uniform(-100, 100), 2),
119
+ "volume": random.uniform(50, 200)
120
+ }
121
+ else:
122
+ ticker = self.exchange.fetch_ticker(symbol)
123
+ return {
124
+ "symbol": symbol,
125
+ "price": ticker["last"],
126
+ "volume": ticker["baseVolume"]
127
+ }
128
+ class PaperTrader:
129
+ def __init__(self):
130
+ self.balance = 1000.0
131
+ self.trades = []
132
+
133
+ def execute_trade(self, symbol, side, price):
134
+ amount = 5.0 / price # $5 trade
135
+ cost = amount * price
136
+ if side == "buy":
137
+ self.balance -= cost
138
+ self.trades.append({"symbol": symbol, "side": "buy", "price": price, "amount": amount})
139
+ else:
140
+ self.balance += cost
141
+ self.trades.append({"symbol": symbol, "side": "sell", "price": price, "amount": amount})
142
+ print(f"πŸ“ PAPER TRADE: {side} {amount:.4f} {symbol} at ${price}")
143
+ return {"status": "filled"}
144
+ import ccxt
145
+ import json
146
+
147
+ class LiveTrader:
148
+ def __init__(self, config_path="config/settings.json"):
149
+ with open(config_path) as f:
150
+ config = json.load(f)
151
+ self.exchange = ccxt.binance({
152
+ 'apiKey': config["api"]["key"],
153
+ 'secret': config["api"]["secret"],
154
+ })
155
+ self.risk = config["risk"]
156
+
157
+ def execute_trade(self, symbol, side, price):
158
+ amount = self.risk["position_size_usd"] / price if "position_size_usd" in self.risk else 5.0 / price
159
+ try:
160
+ if side == "buy":
161
+ order = self.exchange.create_limit_buy_order(symbol, amount, price)
162
+ else:
163
+ order = self.exchange.create_limit_sell_order(symbol, amount, price)
164
+ print(f"βœ… LIVE TRADE: {side} {amount:.4f} {symbol} at ${price}")
165
+ return order
166
+ except Exception as e:
167
+ print(f"❌ Trade failed: {str(e)}")
168
+ return None
169
+ import requests
170
+ import json
171
+
172
+ class TelegramBot:
173
+ def __init__(self, config_path="config/settings.json"):
174
+ with open(config_path) as f:
175
+ config = json.load(f)
176
+ self.enabled = config["telegram"]["enabled"]
177
+ self.token = config["telegram"]["bot_token"]
178
+ self.chat_id = config["telegram"]["chat_id"]
179
+
180
+ def send_alert(self, message):
181
+ if not self.enabled:
182
+ return
183
+ url = f"https://api.telegram.org/bot{self.token}/sendMessage"
184
+ payload = {
185
+ "chat_id": self.chat_id,
186
+ "text": f"πŸ¦… Pegasus Ultra\n{message}",
187
+ "parse_mode": "Markdown"
188
+ }
189
+ try:
190
+ requests.post(url, json=payload)
191
+ except:
192
+ pass
193
+ import gradio as gr
194
+ import threading
195
+ import json
196
+ from data.market_feed import MarketFeed
197
+ from execution.paper_trader import PaperTrader
198
+ from execution.live_trader import LiveTrader
199
+ from core.vault import Vault
200
+
201
+ class PegasusEngine:
202
+ def __init__(self):
203
+ with open("config/settings.json") as f:
204
+ self.config = json.load(f)
205
+ self.mode = self.config["mode"]
206
+ self.feed = MarketFeed()
207
+ self.vault = Vault(self.config)
208
+ self.trades = []
209
+ if self.mode == "live":
210
+ self.trader = LiveTrader()
211
+ else:
212
+ self.trader = PaperTrader()
213
+
214
+ def run(self):
215
+ for i in range(100): # Replace with while True for 24/7
216
+ tick = self.feed.get_ticker()
217
+ self.trader.execute_trade("BTC/USDT", "buy", tick["price"])
218
+ self.trades.append(tick)
219
+
220
+ engine = None
221
+
222
+ def start_engine():
223
+ global engine
224
+ if engine is None:
225
+ engine = PegasusEngine()
226
+ threading.Thread(target=engine.run, daemon=True).start()
227
+ return "βœ… Engine started in " + engine.mode + " mode!"
228
+
229
+ def get_status():
230
+ if engine:
231
+ return f"Mode: {engine.mode}\nTrades: {len(engine.trades)}\nVault: ${engine.vault.reserve:.2f}"
232
+ return "Engine not running"
233
+
234
+ with gr.Blocks() as demo:
235
+ gr.Markdown("# πŸ¦… Pegasus Ultra – Advanced Trading")
236
+ with gr.Row():
237
+ start_btn = gr.Button("Start Engine")
238
+ status = gr.Textbox(label="Status", interactive=False)
239
+ start_btn.click(start_engine, outputs=status)
240
+ demo.load(get_status, every=5, outputs=status)
241
+
242
+ if __name__ == "__main__":
243
+ demo.launch(server_port=7860)
244
+