File size: 5,932 Bytes
be62102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import asyncio
import os
import json
from contextlib import asynccontextmanager
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, JSONResponse, Response
from fastapi.middleware.cors import CORSMiddleware
from python_engine.engine import bot_engine
from python_engine.exchange_manager import exchange_mgr

@asynccontextmanager
async def lifespan(app: FastAPI):
    task = asyncio.create_task(bot_engine.run())
    yield
    bot_engine.is_running = False
    task.cancel()

app = FastAPI(title="NEXUS QUANT PRO | Multi-Exchange Takashi Kotegawa Terminal", lifespan=lifespan)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/favicon.ico", include_in_schema=False)
async def favicon():
    return Response(status_code=204)

@app.get("/api/state")
async def get_state():
    return {
        "status": "online",
        "state": bot_engine.get_full_state(),
        "supported_exchanges": exchange_mgr.get_supported_exchanges(),
        "configured_exchanges": exchange_mgr.get_configured_exchanges(),
        "strategies": ["BNF_TAKASHI", "SMC_ICT", "GRID"]
    }

@app.post("/api/bot/control")
async def bot_control(payload: dict):
    action = payload.get("action")
    if action == "start":
        bot_engine.is_running = True
        return {"success": True, "message": "Python Quant Engine Started"}
    elif action == "stop":
        bot_engine.is_running = False
        return {"success": True, "message": "Python Quant Engine Paused"}
    elif action == "close_single":
        pos_id = payload.get("pos_id")
        target_pos = next((p for p in bot_engine.positions if p.get("id") == pos_id), None)
        if target_pos:
            bot_engine.close_position(target_pos, "MANUAL_SINGLE_CLOSE")
            return {"success": True, "message": f"Position {pos_id} closed successfully"}
        return {"error": "Position not found"}
    elif action == "emergency_close_all":
        for pos in list(bot_engine.positions):
            bot_engine.close_position(pos, "EMERGENCY_MANUAL_PANIC_CLOSE")
        return {"success": True, "message": "All positions liquidated instantly"}
    elif action == "reset":
        bot_engine.positions.clear()
        bot_engine.trade_history.clear()
        bot_engine.balance = 10000.0
        bot_engine.equity = 10000.0
        bot_engine.token_prices.clear()
        bot_engine.is_running = True
        bot_engine.log("System Reset: All trades cleared. Starting fresh with $10,000.00!", "SUCCESS")
        await bot_engine.broadcast_state()
        return {"success": True, "message": "Account reset to pristine $10,000"}
    return {"error": "Invalid action"}

@app.post("/api/bot/config")
async def update_config(payload: dict):
    if "symbol" in payload and payload["symbol"].upper() != bot_engine.symbol:
        await bot_engine.change_symbol(payload["symbol"].upper(), payload.get("interval"))
    if "strategy" in payload:
        bot_engine.active_strategy_name = payload["strategy"]
    if "leverage" in payload:
        bot_engine.leverage = int(payload["leverage"])
    if "risk_pct" in payload:
        bot_engine.risk_pct = float(payload["risk_pct"])
    if "sl_pct" in payload:
        bot_engine.sl_pct = float(payload["sl_pct"])
    if "tp_pct" in payload:
        bot_engine.tp_pct = float(payload["tp_pct"])
    if "trading_mode" in payload:
        bot_engine.trading_mode = payload["trading_mode"].upper()
    if "exchange" in payload:
        bot_engine.active_exchange = payload["exchange"].lower()

    await bot_engine.broadcast_state()
    return {"success": True, "state": bot_engine.get_full_state()}

@app.post("/api/exchange/connect")
async def connect_exchange_api(payload: dict):
    """Verify and connect Real Exchange API Keys (Binance, Bybit, OKX, etc.)"""
    exchange_id = payload.get("exchange", "binance").lower()
    api_key = payload.get("api_key", "")
    secret = payload.get("secret", "")
    passphrase = payload.get("passphrase", "")
    sandbox = bool(payload.get("sandbox", False))
    
    res = await exchange_mgr.configure_exchange(exchange_id, api_key, secret, passphrase, sandbox)
    if res.get("status") == "CONNECTED":
        bot_engine.active_exchange = exchange_id
        bot_engine.log(f"Verified & Connected API for {exchange_id.upper()}! Balance: {res.get('balance')}", "SUCCESS")
        return {"success": True, "data": res}
    else:
        return JSONResponse(status_code=400, content={"success": False, "error": res.get("message")})

@app.post("/api/trade/manual")
async def manual_trade(payload: dict):
    side = payload.get("side", "BUY").upper()
    if bot_engine.current_price <= 0:
        return {"error": "Waiting for live market price tick"}
    bot_engine.open_position(
        action=side,
        reason="Commander Manual Execution (Pro Terminal)",
        confidence=99
    )
    return {"success": True, "positions": bot_engine.positions}

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    bot_engine.subscribers.add(websocket)
    # Send initial state immediately
    await websocket.send_text(json.dumps({
        "event": "STATE_UPDATE",
        "data": bot_engine.get_full_state()
    }))
    try:
        while True:
            data = await websocket.receive_text()
            # Handle incoming client commands if any
            try:
                msg = json.loads(data)
                if msg.get("action") == "CHANGE_SYMBOL":
                    await bot_engine.change_symbol(msg.get("symbol"), msg.get("interval"))
            except Exception:
                pass
    except WebSocketDisconnect:
        bot_engine.subscribers.discard(websocket)

app.mount("/", StaticFiles(directory="public", html=True), name="public")