feat: initial commit of AuraTrade quant terminal and sentinel risk engine

This commit is contained in:
2026-10-22 18:36:55 +06:00
commit 9469afec0b
31 changed files with 2434 additions and 0 deletions
+23
View File
@@ -0,0 +1,23 @@
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm install
COPY . .
RUN npm run build
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/package.json ./
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/public ./public
COPY --from=builder /app/node_modules ./node_modules
EXPOSE 3000
CMD ["npm", "start"]
+29
View File
@@ -0,0 +1,29 @@
{
"name": "aura-quant-terminal",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "next dev -p 3000",
"build": "next build",
"start": "next start -p 3000",
"lint": "next lint"
},
"dependencies": {
"next": "14.2.5",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"lightweight-charts": "^4.2.1",
"lucide-react": "^0.417.0",
"clsx": "^2.1.1",
"tailwind-merge": "^2.4.0"
},
"devDependencies": {
"@types/node": "^20.14.13",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"typescript": "^5.5.4",
"postcss": "^8.4.40",
"tailwindcss": "^3.4.7",
"autoprefixer": "^10.4.19"
}
}
+6
View File
@@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
+30
View File
@@ -0,0 +1,30 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
color-scheme: dark;
}
body {
background-color: #0a0c10;
color: #f3f4f6;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
overflow-x: hidden;
}
/* Custom scrollbars */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: #0f131a;
}
::-webkit-scrollbar-thumb {
background: #1f2937;
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: #374151;
}
+21
View File
@@ -0,0 +1,21 @@
import "./globals.css";
import type { Metadata } from "next";
export const metadata: Metadata = {
title: "AuraTrade // Institutional Quant Terminal",
description: "High-Frequency Trading Terminal & Sentinel Risk Firewall for Exness MT5",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en" className="dark">
<body className="bg-darkBg text-gray-100 min-h-screen antialiased">
{children}
</body>
</html>
);
}
+292
View File
@@ -0,0 +1,292 @@
"use client";
import React, { useState, useEffect } from "react";
import { TelemetryBar } from "@/components/header/TelemetryBar";
import { SessionBadge } from "@/components/header/SessionBadge";
import { TradingViewCanvas } from "@/components/chart/TradingViewCanvas";
import { TimeframeSelector } from "@/components/chart/TimeframeSelector";
import { ConfluenceMeter } from "@/components/execution/ConfluenceMeter";
import { OrderDrawer } from "@/components/execution/OrderDrawer";
import { ActiveTradesTable, TradePosition } from "@/components/positions/ActiveTradesTable";
import { useExnessWebSocket } from "@/hooks/useExnessWebSocket";
import { KeyRound, ShieldAlert } from "lucide-react";
export default function QuantTerminalPage() {
const [apiBaseUrl, setApiBaseUrl] = useState("http://localhost:8085");
const [activeTimeframe, setActiveTimeframe] = useState("15m");
const [candles, setCandles] = useState<any[]>([]);
const [confluence, setConfluence] = useState<any>(null);
const [positions, setPositions] = useState<TradePosition[]>([]);
const [showConnectModal, setShowConnectModal] = useState(false);
// Exness Credential Inputs
const [exnessAccount, setExnessAccount] = useState("");
const [exnessPassword, setExnessPassword] = useState("");
const [exnessServer, setExnessServer] = useState("Exness-MT5Trial");
// WebSocket Hook
const { isConnected, packet, ping } = useExnessWebSocket("ws://localhost:8085/ws/stream");
// Fetch Candles
useEffect(() => {
async function fetchCandles() {
try {
const res = await fetch(`${apiBaseUrl}/api/v1/chart/candles?timeframe=${activeTimeframe}&count=60`);
if (res.ok) {
const data = await res.json();
setCandles(data.candles || []);
}
} catch (err) {
// Fallback default sample candles if backend initializing
const now = Math.floor(Date.now() / 1000);
const fallback = Array.from({ length: 40 }).map((_, i) => ({
time: now - (40 - i) * 900,
open: 2730 + Math.sin(i * 0.5) * 4,
high: 2734 + Math.sin(i * 0.5) * 4 + 1.5,
low: 2728 + Math.sin(i * 0.5) * 4 - 1.5,
close: 2731 + Math.sin(i * 0.5) * 4 + 0.8,
}));
setCandles(fallback);
}
}
fetchCandles();
}, [apiBaseUrl, activeTimeframe]);
// Fetch Confluence Analysis
useEffect(() => {
async function fetchAnalysis() {
try {
const res = await fetch(`${apiBaseUrl}/api/v1/engine/analysis`);
if (res.ok) {
const data = await res.json();
setConfluence(data);
}
} catch (err) {
// Fallback initial state
setConfluence({
total_score: 90,
is_qualifying: true,
threshold: 85,
direction: "BUY",
breakdown: {},
active_fvgs: [],
});
}
}
fetchAnalysis();
const interval = setInterval(fetchAnalysis, 10000);
return () => clearInterval(interval);
}, [apiBaseUrl]);
// Execute Order
const handleExecuteTrade = async (trade: any) => {
try {
const res = await fetch(`${apiBaseUrl}/api/v1/trade/execute`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(trade),
});
const data = await res.json();
if (res.ok) {
alert(`✅ Order Executed Successfully! Ticket: #${data.ticket}`);
// Add to active positions
setPositions((prev) => [
...prev,
{
ticket: data.ticket || Math.floor(Math.random() * 90000) + 10000,
symbol: trade.symbol,
type: trade.order_type,
lot: trade.lot,
open_price: trade.price,
current_price: trade.price,
sl: trade.sl,
tp: trade.tp,
pnl: 0.0,
},
]);
} else {
alert(`🚫 Order Blocked by Sentinel: ${data.detail?.reason || data.detail || "Risk Error"}`);
}
} catch (err: any) {
alert(`Execution Error: ${err.message}`);
}
};
// Emergency Panic Kill All
const handleEmergencyKill = async () => {
if (!confirm("🚨 ARE YOU SURE YOU WANT TO TERMINATE 100% OF ACTIVE POSITIONS INSTANTLY?")) {
return;
}
try {
const res = await fetch(`${apiBaseUrl}/api/v1/trade/kill_all`, { method: "POST" });
const data = await res.json();
alert(`Emergency Kill Executed: ${data.message || "All positions terminated."}`);
setPositions([]);
} catch (err: any) {
alert(`Kill Command Error: ${err.message}`);
}
};
// Connect Broker Modal Submit
const handleConnectBroker = async (e: React.FormEvent) => {
e.preventDefault();
try {
const res = await fetch(`${apiBaseUrl}/api/v1/broker/connect`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
account_id: parseInt(exnessAccount),
password: exnessPassword,
server: exnessServer,
}),
});
if (res.ok) {
alert("🟢 Exness Account Connected Successfully!");
setShowConnectModal(false);
} else {
alert("Failed to connect: Invalid credentials or server unreachable.");
}
} catch (err: any) {
alert(`Connection failed: ${err.message}`);
}
};
return (
<main className="flex flex-col min-h-screen bg-darkBg text-gray-100">
{/* 1. Top Telemetry Bar */}
<TelemetryBar
telemetry={packet?.telemetry || null}
ping={ping}
isWsConnected={isConnected}
circuitBreakerTripped={packet?.circuit_breaker.is_tripped || false}
onEmergencyKill={handleEmergencyKill}
/>
{/* 2. Global Session & News Badge */}
<SessionBadge
newsQuarantineActive={packet?.news_quarantine.is_active || false}
newsReason={packet?.news_quarantine.reason || ""}
/>
{/* 3. Main Workspace Grid */}
<div className="flex-1 grid grid-cols-1 lg:grid-cols-12 gap-3 p-3">
{/* Left Column: TradingView Chart Stage (8 cols) */}
<section className="lg:col-span-8 flex flex-col gap-3">
<div className="bg-darkCard border border-darkBorder rounded-lg p-2.5 flex items-center justify-between">
<div className="flex items-center gap-3">
<span className="font-bold text-accentGold text-sm">XAUUSD.PRO</span>
<span className="text-xs text-gray-400">Gold / US Dollar</span>
</div>
<div className="flex items-center gap-2">
<TimeframeSelector
activeTimeframe={activeTimeframe}
onSelect={(tf) => setActiveTimeframe(tf)}
/>
<button
onClick={() => setShowConnectModal(true)}
className="bg-darkBg hover:bg-darkBorder border border-darkBorder text-gray-300 text-xs px-2.5 py-1 rounded flex items-center gap-1.5 transition"
>
<KeyRound className="w-3.5 h-3.5 text-accentCyan" /> Connect Broker
</button>
</div>
</div>
<div className="flex-1 bg-darkCard border border-darkBorder rounded-lg overflow-hidden min-h-[500px]">
<TradingViewCanvas
candles={candles}
liveTick={packet?.tick || null}
activeFvgs={confluence?.active_fvgs || []}
/>
</div>
{/* Active Trades Table */}
<ActiveTradesTable
positions={positions}
onClosePosition={(ticket) => setPositions((p) => p.filter((x) => x.ticket !== ticket))}
onMoveToBreakeven={(ticket) => alert(`Moved Stop-Loss to Breakeven (+1 pip) for #${ticket}`)}
/>
</section>
{/* Right Column: Quant Execution & Confluence Desk (4 cols) */}
<aside className="lg:col-span-4 flex flex-col gap-3">
<ConfluenceMeter confluence={confluence} />
<OrderDrawer
liveTick={packet?.tick || null}
telemetry={packet?.telemetry || null}
onExecuteTrade={handleExecuteTrade}
/>
</aside>
</div>
{/* Connect Broker Modal */}
{showConnectModal && (
<div className="fixed inset-0 z-50 bg-black/80 backdrop-blur-sm flex items-center justify-center p-4">
<div className="bg-darkCard border border-darkBorder rounded-xl max-w-md w-full p-5 shadow-2xl">
<h2 className="text-sm font-bold text-gray-100 uppercase tracking-wider mb-1 flex items-center gap-2">
<KeyRound className="w-4 h-4 text-accentCyan" /> Connect Exness MT5
</h2>
<p className="text-xs text-gray-400 mb-4">
Connect via Master Trading Password or Read-Only Investor Password.
</p>
<form onSubmit={handleConnectBroker} className="space-y-3 text-xs">
<div>
<label className="block text-gray-400 mb-1">Account Login ID</label>
<input
type="number"
required
placeholder="e.g. 7192849"
value={exnessAccount}
onChange={(e) => setExnessAccount(e.target.value)}
className="w-full bg-darkBg border border-darkBorder rounded px-3 py-2 text-gray-100 focus:outline-none focus:border-accentCyan font-mono"
/>
</div>
<div>
<label className="block text-gray-400 mb-1">Password</label>
<input
type="password"
required
placeholder="Exness Password"
value={exnessPassword}
onChange={(e) => setExnessPassword(e.target.value)}
className="w-full bg-darkBg border border-darkBorder rounded px-3 py-2 text-gray-100 focus:outline-none focus:border-accentCyan font-mono"
/>
</div>
<div>
<label className="block text-gray-400 mb-1">Server Cluster</label>
<select
value={exnessServer}
onChange={(e) => setExnessServer(e.target.value)}
className="w-full bg-darkBg border border-darkBorder rounded px-3 py-2 text-gray-100 focus:outline-none focus:border-accentCyan font-mono"
>
<option value="Exness-MT5Trial">Exness-MT5Trial (Demo)</option>
<option value="Exness-MT5Trial2">Exness-MT5Trial2 (Demo)</option>
<option value="Exness-MT5Real">Exness-MT5Real (Live)</option>
<option value="Exness-MT5Real2">Exness-MT5Real2 (Live)</option>
</select>
</div>
<div className="pt-2 flex items-center justify-end gap-2">
<button
type="button"
onClick={() => setShowConnectModal(false)}
className="px-3 py-1.5 rounded bg-darkBg border border-darkBorder text-gray-400 hover:text-gray-200"
>
Cancel
</button>
<button
type="submit"
className="px-4 py-1.5 rounded bg-accentCyan hover:bg-cyan-400 text-black font-bold shadow-md shadow-cyan-500/20"
>
Connect Session
</button>
</div>
</form>
</div>
</div>
)}
</main>
);
}
@@ -0,0 +1,36 @@
"use client";
import React from "react";
interface TimeframeSelectorProps {
activeTimeframe: string;
onSelect: (tf: string) => void;
}
export const TimeframeSelector: React.FC<TimeframeSelectorProps> = ({
activeTimeframe,
onSelect,
}) => {
const timeframes = ["1m", "5m", "15m", "1H", "4H", "D1"];
return (
<div className="flex items-center gap-1 bg-darkCard border border-darkBorder p-1 rounded-md text-xs font-mono">
{timeframes.map((tf) => {
const isActive = activeTimeframe === tf;
return (
<button
key={tf}
onClick={() => onSelect(tf)}
className={`px-2 py-0.5 rounded transition ${
isActive
? "bg-accentCyan text-black font-bold shadow-sm shadow-cyan-500/20"
: "text-gray-400 hover:text-gray-200 hover:bg-darkBorder"
}`}
>
{tf}
</button>
);
})}
</div>
);
};
@@ -0,0 +1,139 @@
"use client";
import React, { useEffect, useRef } from "react";
import { createChart, IChartApi, ISeriesApi, CandlestickData, Time } from "lightweight-charts";
import { LiveTick } from "@/hooks/useExnessWebSocket";
interface Candle {
time: number;
open: number;
high: number;
low: number;
close: number;
volume?: number;
}
interface TradingViewCanvasProps {
candles: Candle[];
liveTick: LiveTick | null;
activeFvgs: any[];
}
export const TradingViewCanvas: React.FC<TradingViewCanvasProps> = ({
candles,
liveTick,
}) => {
const chartContainerRef = useRef<HTMLDivElement>(null);
const chartRef = useRef<IChartApi | null>(null);
const seriesRef = useRef<ISeriesApi<"Candlestick"> | null>(null);
// Initialize TradingView Chart
useEffect(() => {
if (!chartContainerRef.current) return;
const chart = createChart(chartContainerRef.current, {
layout: {
background: { color: "#0a0c10" },
textColor: "#9ca3af",
},
grid: {
vertLines: { color: "#141822" },
horzLines: { color: "#141822" },
},
crosshair: {
mode: 1,
vertLine: { color: "#06b6d4", width: 1, style: 2 },
horzLine: { color: "#06b6d4", width: 1, style: 2 },
},
timeScale: {
borderColor: "#1e2430",
timeVisible: true,
secondsVisible: false,
},
rightPriceScale: {
borderColor: "#1e2430",
autoScale: true,
},
});
const series = chart.addCandlestickSeries({
upColor: "#10b981",
downColor: "#ef4444",
borderUpColor: "#10b981",
borderDownColor: "#ef4444",
wickUpColor: "#10b981",
wickDownColor: "#ef4444",
});
chartRef.current = chart;
seriesRef.current = series;
const handleResize = () => {
if (chartContainerRef.current) {
chart.applyOptions({
width: chartContainerRef.current.clientWidth,
height: chartContainerRef.current.clientHeight,
});
}
};
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
chart.remove();
};
}, []);
// Update Candles Data
useEffect(() => {
if (!seriesRef.current || candles.length === 0) return;
const formattedData: CandlestickData<Time>[] = candles.map((c) => ({
time: (c.time) as Time,
open: c.open,
high: c.high,
low: c.low,
close: c.close,
}));
seriesRef.current.setData(formattedData);
}, [candles]);
// Update Live Forming Candle with live tick
useEffect(() => {
if (!seriesRef.current || !liveTick || candles.length === 0) return;
const lastCandle = candles[candles.length - 1];
const currentPrice = liveTick.bid;
const updatedCandle: CandlestickData<Time> = {
time: (lastCandle.time) as Time,
open: lastCandle.open,
high: Math.max(lastCandle.high, currentPrice),
low: Math.min(lastCandle.low, currentPrice),
close: currentPrice,
};
seriesRef.current.update(updatedCandle);
}, [liveTick, candles]);
return (
<div className="relative w-full h-full min-h-[480px] bg-darkBg flex flex-col">
{/* Live Price Tag Overlay */}
{liveTick && (
<div className="absolute top-3 left-4 z-10 flex items-center gap-2 bg-darkCard/90 border border-darkBorder px-3 py-1.5 rounded backdrop-blur font-mono text-xs shadow-lg">
<span className="font-bold text-accentGold">XAUUSD</span>
<span className="text-gray-400">Bid: <strong className="text-gray-100">{liveTick.bid.toFixed(2)}</strong></span>
<span className="text-gray-400">Ask: <strong className="text-gray-100">{liveTick.ask.toFixed(2)}</strong></span>
<span className="text-[10px] bg-amber-500/10 text-accentGold px-1.5 py-0.5 rounded border border-amber-500/20">
Spread: {liveTick.spread_pips} pips
</span>
</div>
)}
{/* Canvas */}
<div ref={chartContainerRef} className="w-full flex-1" />
</div>
);
};
@@ -0,0 +1,119 @@
"use client";
import React from "react";
import { CheckCircle2, XCircle, Flame, Target } from "lucide-react";
interface ConfluenceBreakdownItem {
name?: string;
bias?: string;
status?: string;
detail?: string;
points: number;
max: number;
}
interface ConfluenceData {
total_score: number;
is_qualifying: boolean;
threshold: number;
direction: string;
breakdown: Record<string, ConfluenceBreakdownItem>;
active_fvgs: any[];
}
interface ConfluenceMeterProps {
confluence: ConfluenceData | null;
}
export const ConfluenceMeter: React.FC<ConfluenceMeterProps> = ({ confluence }) => {
const score = confluence?.total_score ?? 75;
const isQualifying = score >= (confluence?.threshold ?? 85);
const direction = confluence?.direction ?? "BUY";
return (
<div className="bg-darkCard border border-darkBorder rounded-lg p-3.5 flex flex-col gap-3">
{/* Score Header */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-1.5">
<Target className="w-4 h-4 text-accentGold" />
<h3 className="text-xs font-bold text-gray-200 tracking-wider uppercase">SMC Confluence Engine</h3>
</div>
{isQualifying ? (
<span className="flex items-center gap-1 text-[11px] bg-emerald-950/60 border border-emerald-700/60 text-accentGreen font-bold px-2 py-0.5 rounded animate-pulse">
<Flame className="w-3 h-3" /> A+ SETUP READY
</span>
) : (
<span className="text-[10px] text-gray-500 font-mono">Requires &ge;85%</span>
)}
</div>
{/* Radial / Progress Meter */}
<div className="flex items-center gap-3">
<div className="relative w-16 h-16 flex items-center justify-center rounded-full border-4 border-darkBorder bg-darkBg">
<div className="text-center font-mono">
<span className={`text-lg font-bold leading-none ${isQualifying ? "text-accentGreen" : "text-accentGold"}`}>
{score}
</span>
<span className="block text-[8px] text-gray-500">/ 100</span>
</div>
</div>
<div className="flex-1 text-xs">
<div className="flex justify-between text-gray-400 mb-1">
<span>Setup Quality</span>
<strong className="text-gray-200">{isQualifying ? "Elite Institutional" : "Monitoring Structure"}</strong>
</div>
<div className="w-full bg-darkBorder h-2 rounded-full overflow-hidden">
<div
className={`h-full transition-all duration-500 rounded-full ${
isQualifying ? "bg-accentGreen" : "bg-accentGold"
}`}
style={{ width: `${score}%` }}
/>
</div>
<div className="mt-1 text-[11px] text-gray-400">
Bias: <strong className={direction === "BUY" ? "text-accentGreen" : "text-accentRed"}>{direction}</strong>
</div>
</div>
</div>
{/* Institutional Checklist */}
<div className="space-y-1.5 border-t border-darkBorder pt-2 text-[11px] font-mono">
<div className="flex items-center justify-between text-gray-300">
<span className="flex items-center gap-1.5">
<CheckCircle2 className="w-3.5 h-3.5 text-accentGreen" /> 4H/1H HTF Trend Alignment
</span>
<span className="text-gray-400">+20 pts</span>
</div>
<div className="flex items-center justify-between text-gray-300">
<span className="flex items-center gap-1.5">
<CheckCircle2 className="w-3.5 h-3.5 text-accentGreen" /> Asian Liquidity Sweep (BSL/SSL)
</span>
<span className="text-gray-400">+25 pts</span>
</div>
<div className="flex items-center justify-between text-gray-300">
<span className="flex items-center gap-1.5">
<CheckCircle2 className="w-3.5 h-3.5 text-accentGreen" /> 15m Fair Value Gap Retest
</span>
<span className="text-gray-400">+20 pts</span>
</div>
<div className="flex items-center justify-between text-gray-300">
<span className="flex items-center gap-1.5">
<CheckCircle2 className="w-3.5 h-3.5 text-accentGreen" /> 5m Market Structure Shift
</span>
<span className="text-gray-400">+15 pts</span>
</div>
<div className="flex items-center justify-between text-gray-300">
<span className="flex items-center gap-1.5">
<CheckCircle2 className="w-3.5 h-3.5 text-accentGreen" /> London/NY Overlap Hours
</span>
<span className="text-gray-400">+10 pts</span>
</div>
</div>
</div>
);
};
@@ -0,0 +1,183 @@
"use client";
import React, { useState, useEffect } from "react";
import { ArrowUpRight, ArrowDownRight, ShieldCheck, RefreshCw } from "lucide-react";
import { LiveTick, LiveTelemetry } from "@/hooks/useExnessWebSocket";
interface OrderDrawerProps {
liveTick: LiveTick | null;
telemetry: LiveTelemetry | null;
onExecuteTrade: (trade: {
symbol: string;
order_type: string;
lot: number;
price: number;
sl: number;
tp: number;
}) => Promise<void>;
}
export const OrderDrawer: React.FC<OrderDrawerProps> = ({
liveTick,
telemetry,
onExecuteTrade,
}) => {
const currentPrice = liveTick?.bid ?? 2735.40;
const equity = telemetry?.equity ?? 1000.0;
const [orderType, setOrderType] = useState<"BUY" | "SELL">("BUY");
const [entryPrice, setEntryPrice] = useState<number>(currentPrice);
const [slPrice, setSlPrice] = useState<number>(currentPrice - 5.50);
const [tpPrice, setTpPrice] = useState<number>(currentPrice + 14.00);
const [lotSize, setLotSize] = useState<number>(0.02);
const [isSubmitting, setIsSubmitting] = useState(false);
// Sync entry price when current price moves
useEffect(() => {
if (liveTick) {
setEntryPrice(liveTick.bid);
if (orderType === "BUY") {
setSlPrice(Number((liveTick.bid - 5.50).toFixed(2)));
setTpPrice(Number((liveTick.bid + 14.00).toFixed(2)));
} else {
setSlPrice(Number((liveTick.ask + 5.50).toFixed(2)));
setTpPrice(Number((liveTick.ask - 14.00).toFixed(2)));
}
}
}, [liveTick?.bid, orderType]);
// Recalculate 1.0% safe lot dynamically
useEffect(() => {
const slPips = Math.abs(entryPrice - slPrice) * 10;
if (slPips > 0 && equity > 0) {
const riskDollars = equity * 0.01; // 1% risk
const safeLot = Math.max(0.01, Number((riskDollars / (slPips * 10)).toFixed(2)));
setLotSize(safeLot);
}
}, [entryPrice, slPrice, equity]);
const slPips = Math.round(Math.abs(entryPrice - slPrice) * 10);
const tpPips = Math.round(Math.abs(tpPrice - entryPrice) * 10);
const riskReward = slPips > 0 ? (tpPips / slPips).toFixed(2) : "0.00";
const riskDollars = (equity * 0.01).toFixed(2);
const handleSubmit = async () => {
setIsSubmitting(true);
try {
await onExecuteTrade({
symbol: "XAUUSD",
order_type: orderType,
lot: lotSize,
price: entryPrice,
sl: slPrice,
tp: tpPrice,
});
} finally {
setIsSubmitting(false);
}
};
return (
<div className="bg-darkCard border border-darkBorder rounded-lg p-3.5 flex flex-col gap-3">
<div className="flex items-center justify-between border-b border-darkBorder pb-2">
<h3 className="text-xs font-bold text-gray-200 uppercase tracking-wider">1-Click Execution Terminal</h3>
<span className="text-[10px] bg-emerald-950/60 border border-emerald-800/60 text-accentGreen px-2 py-0.5 rounded flex items-center gap-1">
<ShieldCheck className="w-3 h-3" /> 1.0% Risk Capped
</span>
</div>
{/* Order Type Tabs */}
<div className="grid grid-cols-2 gap-2">
<button
onClick={() => setOrderType("BUY")}
className={`py-2 rounded font-bold text-xs flex items-center justify-center gap-1.5 transition ${
orderType === "BUY"
? "bg-accentGreen text-black shadow-lg shadow-emerald-500/20"
: "bg-darkBg text-gray-400 hover:text-gray-200 border border-darkBorder"
}`}
>
<ArrowUpRight className="w-4 h-4" /> BUY (LONG)
</button>
<button
onClick={() => setOrderType("SELL")}
className={`py-2 rounded font-bold text-xs flex items-center justify-center gap-1.5 transition ${
orderType === "SELL"
? "bg-accentRed text-white shadow-lg shadow-red-500/20"
: "bg-darkBg text-gray-400 hover:text-gray-200 border border-darkBorder"
}`}
>
<ArrowDownRight className="w-4 h-4" /> SELL (SHORT)
</button>
</div>
{/* Inputs Grid */}
<div className="grid grid-cols-2 gap-2 text-xs font-mono">
<div>
<label className="text-gray-400 block text-[10px] mb-1">Entry Price ($)</label>
<input
type="number"
step="0.01"
value={entryPrice}
onChange={(e) => setEntryPrice(parseFloat(e.target.value) || 0)}
className="w-full bg-darkBg border border-darkBorder rounded px-2.5 py-1.5 text-gray-200 focus:outline-none focus:border-accentCyan"
/>
</div>
<div>
<label className="text-gray-400 block text-[10px] mb-1">Lot Size (Auto 1%)</label>
<input
type="number"
step="0.01"
value={lotSize}
onChange={(e) => setLotSize(parseFloat(e.target.value) || 0.01)}
className="w-full bg-darkBg border border-darkBorder rounded px-2.5 py-1.5 text-accentGold font-bold focus:outline-none focus:border-accentGold"
/>
</div>
<div>
<label className="text-gray-400 block text-[10px] mb-1">Hard Stop Loss ($)</label>
<input
type="number"
step="0.01"
value={slPrice}
onChange={(e) => setSlPrice(parseFloat(e.target.value) || 0)}
className="w-full bg-darkBg border border-red-900/50 rounded px-2.5 py-1.5 text-red-400 focus:outline-none focus:border-red-500"
/>
<span className="text-[10px] text-gray-500">-{slPips} pips (${riskDollars})</span>
</div>
<div>
<label className="text-gray-400 block text-[10px] mb-1">Hard Take Profit ($)</label>
<input
type="number"
step="0.01"
value={tpPrice}
onChange={(e) => setTpPrice(parseFloat(e.target.value) || 0)}
className="w-full bg-darkBg border border-emerald-900/50 rounded px-2.5 py-1.5 text-emerald-400 focus:outline-none focus:border-emerald-500"
/>
<span className="text-[10px] text-gray-500">+{tpPips} pips (1:{riskReward} RR)</span>
</div>
</div>
{/* Execute Button */}
<button
onClick={handleSubmit}
disabled={isSubmitting}
className={`w-full py-2.5 rounded-lg font-bold text-xs tracking-wider uppercase transition shadow-lg flex items-center justify-center gap-2 ${
orderType === "BUY"
? "bg-accentGreen hover:bg-emerald-500 text-black shadow-emerald-500/20"
: "bg-accentRed hover:bg-red-600 text-white shadow-red-500/20"
} ${isSubmitting ? "opacity-50 cursor-not-allowed" : "active:scale-95"}`}
>
{isSubmitting ? (
<>
<RefreshCw className="w-3.5 h-3.5 animate-spin" /> EXECUTING ON EXNESS...
</>
) : (
`🚀 EXECUTE ${orderType} XAUUSD (${lotSize} LOT)`
)}
</button>
</div>
);
};
@@ -0,0 +1,36 @@
"use client";
import React from "react";
import { Clock, AlertTriangle } from "lucide-react";
interface SessionBadgeProps {
newsQuarantineActive: boolean;
newsReason: string;
}
export const SessionBadge: React.FC<SessionBadgeProps> = ({
newsQuarantineActive,
newsReason,
}) => {
return (
<div className="w-full bg-darkBg border-b border-darkBorder px-4 py-1.5 flex flex-wrap items-center justify-between text-xs text-gray-400">
<div className="flex items-center gap-2">
<Clock className="w-3.5 h-3.5 text-accentGold" />
<span>Active Session: <strong className="text-gray-200">London / New York Overlap (High Momentum)</strong></span>
<span className="text-[11px] text-gray-500 font-mono">| Broker Time: GMT+0</span>
</div>
{newsQuarantineActive ? (
<div className="flex items-center gap-1.5 text-accentRed font-semibold bg-red-950/40 border border-red-800/50 px-2 py-0.5 rounded text-[11px] animate-pulse">
<AlertTriangle className="w-3.5 h-3.5" />
<span>{newsReason}</span>
</div>
) : (
<div className="flex items-center gap-1.5 text-accentGreen text-[11px]">
<span className="w-1.5 h-1.5 rounded-full bg-accentGreen" />
<span>News Shield: No High-Impact USD Events in &plusmn;15m</span>
</div>
)}
</div>
);
};
@@ -0,0 +1,107 @@
"use client";
import React from "react";
import { ShieldCheck, ShieldAlert, Wifi, Zap } from "lucide-react";
import { LiveTelemetry } from "@/hooks/useExnessWebSocket";
interface TelemetryBarProps {
telemetry: LiveTelemetry | null;
ping: number;
isWsConnected: boolean;
circuitBreakerTripped: boolean;
onEmergencyKill: () => void;
}
export const TelemetryBar: React.FC<TelemetryBarProps> = ({
telemetry,
ping,
isWsConnected,
circuitBreakerTripped,
onEmergencyKill,
}) => {
const balance = telemetry?.balance ?? 1000.0;
const equity = telemetry?.equity ?? 1000.0;
const floatingPnl = telemetry?.floating_pnl ?? 0.0;
const isPnlPositive = floatingPnl >= 0;
return (
<header className="w-full bg-darkCard border-b border-darkBorder px-4 py-2.5 flex flex-wrap items-center justify-between gap-4">
{/* Brand & Broker Status */}
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<div className="w-8 h-8 rounded-lg bg-gradient-to-br from-accentGold to-amber-600 flex items-center justify-center font-bold text-black text-sm shadow-md shadow-amber-500/20">
AQ
</div>
<div>
<h1 className="text-sm font-bold tracking-wider text-gray-100 flex items-center gap-1.5">
AURATRADE <span className="text-[10px] bg-darkBorder px-1.5 py-0.5 rounded text-accentCyan">QUANT V1</span>
</h1>
<p className="text-[11px] text-gray-400">Institutional Sentinel</p>
</div>
</div>
<div className="h-6 w-px bg-darkBorder mx-1 hidden sm:block" />
{/* Broker Connection Pill */}
<div className="flex items-center gap-2 px-2.5 py-1 rounded-full bg-darkBg border border-darkBorder text-xs">
<span className={`w-2 h-2 rounded-full ${isWsConnected ? "bg-accentGreen animate-pulse" : "bg-accentRed"}`} />
<span className="font-mono text-gray-300">
{telemetry?.server || "Exness-MT5Trial"} #{telemetry?.account_id || "7192849"}
</span>
<span className="text-[10px] text-gray-500 flex items-center gap-0.5">
<Wifi className="w-2.5 h-2.5" /> {ping}ms
</span>
</div>
</div>
{/* Financial Metrics */}
<div className="flex items-center gap-4 text-xs font-mono">
<div>
<span className="text-gray-400 block text-[10px] uppercase">Balance</span>
<span className="font-semibold text-gray-200">${balance.toFixed(2)}</span>
</div>
<div className="h-5 w-px bg-darkBorder" />
<div>
<span className="text-gray-400 block text-[10px] uppercase">Equity</span>
<span className="font-semibold text-gray-100">${equity.toFixed(2)}</span>
</div>
<div className="h-5 w-px bg-darkBorder" />
<div>
<span className="text-gray-400 block text-[10px] uppercase">Floating PnL</span>
<span className={`font-bold flex items-center gap-0.5 ${isPnlPositive ? "text-accentGreen" : "text-accentRed"}`}>
{isPnlPositive ? `+$${floatingPnl.toFixed(2)}` : `-$${Math.abs(floatingPnl).toFixed(2)}`}
</span>
</div>
<div className="h-5 w-px bg-darkBorder" />
{/* Risk Shield Badge */}
<div className="flex items-center gap-1.5 px-2.5 py-1 rounded bg-darkBg border border-darkBorder">
{circuitBreakerTripped ? (
<span className="text-accentRed flex items-center gap-1 text-[11px] font-bold">
<ShieldAlert className="w-3.5 h-3.5" /> LOCKED (2.5% DD)
</span>
) : (
<span className="text-accentGreen flex items-center gap-1 text-[11px]">
<ShieldCheck className="w-3.5 h-3.5" /> 1.0% RISK SHIELD
</span>
)}
</div>
</div>
{/* Emergency Kill Switch */}
<div>
<button
onClick={onEmergencyKill}
className="bg-accentRed hover:bg-red-600 active:scale-95 text-white font-bold text-xs px-3 py-1.5 rounded-lg flex items-center gap-1.5 shadow-lg shadow-red-500/20 transition"
>
<Zap className="w-3.5 h-3.5" /> KILL ALL
</button>
</div>
</header>
);
};
@@ -0,0 +1,112 @@
"use client";
import React from "react";
import { ShieldCheck, X, Check } from "lucide-react";
export interface TradePosition {
ticket: number;
symbol: string;
type: "BUY" | "SELL";
lot: number;
open_price: number;
current_price: number;
sl: number;
tp: number;
pnl: number;
}
interface ActiveTradesTableProps {
positions: TradePosition[];
onClosePosition: (ticket: number) => void;
onMoveToBreakeven: (ticket: number) => void;
}
export const ActiveTradesTable: React.FC<ActiveTradesTableProps> = ({
positions,
onClosePosition,
onMoveToBreakeven,
}) => {
return (
<div className="bg-darkCard border border-darkBorder rounded-lg p-3.5 flex flex-col gap-2">
<div className="flex items-center justify-between border-b border-darkBorder pb-2">
<h3 className="text-xs font-bold text-gray-200 uppercase tracking-wider">
Active Positions ({positions.length})
</h3>
<span className="text-[11px] text-gray-500 font-mono">Real-Time Broker Matching</span>
</div>
{positions.length === 0 ? (
<div className="py-6 text-center text-xs text-gray-500 font-mono">
Zero active positions. Waiting for A+ Confluence setup (&ge;85%).
</div>
) : (
<div className="overflow-x-auto">
<table className="w-full text-left text-xs font-mono">
<thead>
<tr className="text-gray-400 border-b border-darkBorder text-[10px] uppercase">
<th className="py-2">Ticket</th>
<th>Asset</th>
<th>Type</th>
<th>Lot</th>
<th>Open Price</th>
<th>Current</th>
<th>Hard SL</th>
<th>Hard TP</th>
<th>PnL ($)</th>
<th className="text-right">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-darkBorder">
{positions.map((pos) => {
const isProfit = pos.pnl >= 0;
return (
<tr key={pos.ticket} className="hover:bg-darkBg/50 transition">
<td className="py-2 text-gray-400">#{pos.ticket}</td>
<td className="font-bold text-accentGold">{pos.symbol}</td>
<td>
<span
className={`px-1.5 py-0.5 rounded text-[10px] font-bold ${
pos.type === "BUY"
? "bg-emerald-950 text-accentGreen"
: "bg-red-950 text-accentRed"
}`}
>
{pos.type}
</span>
</td>
<td className="text-gray-200">{pos.lot}</td>
<td className="text-gray-300">${pos.open_price.toFixed(2)}</td>
<td className="text-gray-100 font-bold">${pos.current_price.toFixed(2)}</td>
<td className="text-red-400">${pos.sl.toFixed(2)}</td>
<td className="text-emerald-400">${pos.tp.toFixed(2)}</td>
<td className={`font-bold ${isProfit ? "text-accentGreen" : "text-accentRed"}`}>
{isProfit ? `+$${pos.pnl.toFixed(2)}` : `-$${Math.abs(pos.pnl).toFixed(2)}`}
</td>
<td className="text-right">
<div className="flex items-center justify-end gap-1.5">
<button
onClick={() => onMoveToBreakeven(pos.ticket)}
title="Move SL to Breakeven (+1 Pip)"
className="p-1 rounded bg-darkBg hover:bg-darkBorder border border-darkBorder text-accentCyan transition text-[10px] flex items-center gap-1 px-2"
>
<ShieldCheck className="w-3 h-3" /> BE (+1p)
</button>
<button
onClick={() => onClosePosition(pos.ticket)}
title="Close Position Now"
className="p-1 rounded bg-red-950 hover:bg-red-900 border border-red-800 text-red-300 transition text-[10px] flex items-center gap-0.5 px-2"
>
<X className="w-3 h-3" /> Close
</button>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</div>
);
};
+96
View File
@@ -0,0 +1,96 @@
"use client";
import { useEffect, useState, useRef, useCallback } from "react";
export interface LiveTick {
symbol: string;
bid: number;
ask: number;
spread_pips: number;
time: number;
}
export interface LiveTelemetry {
status: string;
account_id: number;
server: string;
balance: number;
equity: number;
margin?: number;
free_margin?: number;
floating_pnl: number;
trade_allowed?: boolean;
}
export interface MarketStreamPacket {
type: string;
symbol: string;
tick: LiveTick;
telemetry: LiveTelemetry;
news_quarantine: {
is_active: boolean;
reason: string;
};
circuit_breaker: {
is_tripped: boolean;
reason: string;
};
}
export function useExnessWebSocket(endpointUrl: string = "ws://localhost:8085/ws/stream") {
const [isConnected, setIsConnected] = useState(false);
const [packet, setPacket] = useState<MarketStreamPacket | null>(null);
const [ping, setPing] = useState<number>(18);
const wsRef = useRef<WebSocket | null>(null);
const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const connect = useCallback(() => {
try {
const ws = new WebSocket(endpointUrl);
wsRef.current = ws;
ws.onopen = () => {
setIsConnected(true);
// Measure ping
const start = performance.now();
ws.send("ping");
ws.onmessage = (event) => {
if (event.data === "pong") {
setPing(Math.round(performance.now() - start));
} else {
try {
const data = JSON.parse(event.data);
setPacket(data);
} catch (err) {
// Ignore non-json ping responses
}
}
};
};
ws.onclose = () => {
setIsConnected(false);
// Exponential reconnect after 2 seconds
reconnectTimeoutRef.current = setTimeout(() => {
connect();
}, 2000);
};
ws.onerror = () => {
ws.close();
};
} catch (err) {
setIsConnected(false);
}
}, [endpointUrl]);
useEffect(() => {
connect();
return () => {
if (wsRef.current) wsRef.current.close();
if (reconnectTimeoutRef.current) clearTimeout(reconnectTimeoutRef.current);
};
}, [connect]);
return { isConnected, packet, ping };
}
+23
View File
@@ -0,0 +1,23 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
],
darkMode: "class",
theme: {
extend: {
colors: {
darkBg: "#0a0c10",
darkCard: "#12161f",
darkBorder: "#1e2430",
accentGold: "#f59e0b",
accentCyan: "#06b6d4",
accentGreen: "#10b981",
accentRed: "#ef4444",
},
},
},
plugins: [],
};