Initial Commit

This commit is contained in:
Senofy
2026-03-07 22:07:02 -06:00
parent b33c43aa0c
commit a9b6acd479
17 changed files with 1665 additions and 117 deletions
+83
View File
@@ -0,0 +1,83 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
export default function AddPage() {
const router = useRouter();
const [firmName, setFirmName] = useState('');
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [saving, setSaving] = useState(false);
const inputCls = 'w-full border border-slate-200 rounded-lg px-3 py-2 text-sm text-slate-800 focus:outline-none focus:ring-2 focus:ring-blue-400';
const labelCls = 'block text-xs font-semibold uppercase tracking-wider text-slate-500 mb-1';
const handleSave = async () => {
if (!firmName.trim() || !username.trim() || !password.trim()) return;
setSaving(true);
setError('');
try {
const res = await fetch('/api/firms', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: firmName.trim(), username: username.trim(), password: password.trim() }),
});
if (!res.ok) {
const data = await res.json() as { error?: string };
setError(data.error ?? 'Failed to save firm');
return;
}
router.push('/');
} catch {
setError('Could not connect to server');
} finally {
setSaving(false);
}
};
return (
<div className="min-h-screen bg-slate-50 p-8">
<div className="max-w-7xl mx-auto">
<div className="flex items-center gap-3 mb-6">
<button onClick={() => router.push('/')} className="text-slate-400 hover:text-slate-600 text-sm transition-colors">
Back
</button>
<h1 className="text-2xl font-bold text-slate-900">Add New Firm</h1>
</div>
<div className="bg-white border border-slate-200 rounded-xl p-6 shadow-sm max-w-md space-y-4">
{error && (
<div className="text-sm text-red-600 bg-red-50 border border-red-100 rounded-lg px-3 py-2">
{error}
</div>
)}
<div>
<label className={labelCls}>Firm Name</label>
<input value={firmName} onChange={(e) => setFirmName(e.target.value)} className={inputCls} placeholder="e.g. MyFirm" />
</div>
<div>
<label className={labelCls}>Username</label>
<input value={username} onChange={(e) => setUsername(e.target.value)} className={inputCls} placeholder="Username" />
</div>
<div>
<label className={labelCls}>Password</label>
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} className={inputCls} placeholder="Password" />
</div>
<div className="flex justify-end gap-2 pt-2">
<button onClick={() => router.push('/')} className="px-4 py-2 text-sm text-slate-600 hover:text-slate-800 transition-colors">
Cancel
</button>
<button
onClick={handleSave}
disabled={saving || !firmName.trim() || !username.trim() || !password.trim()}
className="px-4 py-2 bg-green-100 hover:bg-green-200 disabled:opacity-40 disabled:cursor-not-allowed text-green-700 text-sm font-semibold rounded-lg transition-colors"
>
{saving ? 'Saving...' : 'Add Firm'}
</button>
</div>
</div>
</div>
</div>
);
}
+27
View File
@@ -0,0 +1,27 @@
import { NextRequest, NextResponse } from 'next/server';
import { deleteFirm } from '@/lib/db';
import { removeClient } from '@/lib/clients';
export async function DELETE(
_req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { id: idStr } = await params;
const id = parseInt(idStr, 10);
if (isNaN(id)) {
return NextResponse.json({ error: 'Invalid id' }, { status: 400 });
}
try {
const deleted = deleteFirm(id);
if (!deleted) {
return NextResponse.json({ error: 'Firm not found' }, { status: 404 });
}
removeClient(id);
return NextResponse.json({ success: true });
} catch (err) {
console.error('[DELETE /api/firms/:id]', err);
return NextResponse.json({ error: 'Failed to delete firm' }, { status: 500 });
}
}
+54
View File
@@ -0,0 +1,54 @@
import { NextRequest, NextResponse } from 'next/server';
import { getFirms, createFirm } from '@/lib/db';
import { initClient } from '@/lib/clients';
export async function GET() {
try {
const firms = getFirms();
const result = firms.map((f) => ({
id: f.id,
firm: f.name,
username: f.username,
password: f.password,
accounts: f.accounts.map((a) => ({
prefix: a.prefix,
profitTarget: a.profit_target,
consistency: a.consistency,
minDayPnL: a.min_day_pnl,
minTradingDays: a.min_trading_days,
})),
}));
return NextResponse.json(result);
} catch (err) {
console.error('[GET /api/firms]', err);
return NextResponse.json({ error: 'Failed to fetch firms' }, { status: 500 });
}
}
export async function POST(req: NextRequest) {
const body = await req.json() as { name?: string; username?: string; password?: string };
const { name, username, password } = body;
if (!name?.trim() || !username?.trim() || !password?.trim()) {
return NextResponse.json({ error: 'name, username, and password are required' }, { status: 400 });
}
try {
const firm = createFirm(name.trim(), username.trim(), password.trim());
initClient(firm.id, firm.username, firm.password, firm.name);
return NextResponse.json({
id: firm.id,
firm: firm.name,
username: firm.username,
password: firm.password,
accounts: [],
}, { status: 201 });
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
if (msg.includes('UNIQUE')) {
return NextResponse.json({ error: 'A firm with that name already exists' }, { status: 409 });
}
console.error('[POST /api/firms]', err);
return NextResponse.json({ error: 'Failed to create firm' }, { status: 500 });
}
}
+35
View File
@@ -0,0 +1,35 @@
import { NextResponse } from 'next/server';
import { getFirms } from '@/lib/db';
import { getClients } from '@/lib/clients';
export async function GET() {
try {
const firms = getFirms();
const clients = getClients();
const state = firms.map((f) => {
const client = clients.get(f.id);
if (!client || client.accountList.length === 0) {
return { firm: f.name, connected: false, accounts: [] };
}
const accounts = client.accountList.map((acc) => {
const cash = client.accountCashBalances[acc.id] ?? { amount: 0, realizedPnL: 0 };
return {
id: acc.id,
name: acc.name,
active: acc.active,
amount: cash.amount,
realizedPnL: cash.realizedPnL,
daysTraded: client.daysTraded[acc.id] ?? 0,
hasPosition: !!client.positions[acc.id],
};
});
return { firm: f.name, connected: true, accounts };
});
return NextResponse.json(state);
} catch (err) {
console.error('[GET /api/state]', err);
return NextResponse.json({ error: 'Failed to fetch state' }, { status: 500 });
}
}
+8 -21
View File
@@ -1,26 +1,13 @@
@import "tailwindcss";
:root {
--background: #ffffff;
--foreground: #171717;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
}
.chevron {
transition: transform 0.2s;
}
.chevron.open {
transform: rotate(180deg);
}
+3 -18
View File
@@ -1,20 +1,9 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
title: "AutoTrader",
description: "AutoTrader Firm Dashboard",
};
export default function RootLayout({
@@ -24,11 +13,7 @@ export default function RootLayout({
}>) {
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
</body>
<body className="antialiased">{children}</body>
</html>
);
}
+263 -61
View File
@@ -1,65 +1,267 @@
import Image from "next/image";
'use client';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import type { FirmConfig, FirmState, AccountState, AccountConfig } from '@/types';
function getAccountConfig(name: string, firm: FirmConfig): AccountConfig | undefined {
return [...firm.accounts]
.sort((a, b) => b.prefix.length - a.prefix.length)
.find((a) => name.startsWith(a.prefix));
}
function fmt(value: number) {
return value.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
function SettingsIcon() {
return (
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<circle cx="12" cy="12" r="3" />
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
</svg>
);
}
function ChevronIcon({ open }: { open: boolean }) {
return (
<svg className={`chevron${open ? ' open' : ''}`} width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
<polyline points="6 9 12 15 18 9" />
</svg>
);
}
function AccountRow({ account, firm }: { account: AccountState; firm: FirmConfig }) {
const cfg = getAccountConfig(account.name, firm);
const pnlColor = account.realizedPnL > 0 ? 'text-green-600 font-medium' : account.realizedPnL < 0 ? 'text-red-600 font-medium' : 'text-slate-400';
return (
<tr className={`border-b border-slate-100 hover:bg-slate-50 transition-colors${!account.active ? ' opacity-40' : ''}`}>
<td className="px-4 py-3">
<div className="flex items-center gap-2 font-medium text-slate-800 pl-4">
{account.name}
</div>
</td>
<td className="px-4 py-3 text-slate-600 tabular-nums">${fmt(account.amount)}</td>
<td className={`px-4 py-3 tabular-nums ${pnlColor}`}>
{account.realizedPnL >= 0 ? '+' : ''}${fmt(account.realizedPnL)}
</td>
<td className="px-4 py-3 text-slate-600 tabular-nums">
{account.daysTraded} / {cfg?.minTradingDays ?? '—'}
</td>
<td className="px-4 py-3 text-slate-600 tabular-nums">
${cfg?.profitTarget?.toLocaleString() ?? '—'}
</td>
<td className="px-4 py-3">
{!account.active
? <span className="inline-block px-2.5 py-0.5 rounded-full text-xs font-semibold bg-red-100 text-red-700">Inactive</span>
: account.hasPosition
? <span className="inline-block px-2.5 py-0.5 rounded-full text-xs font-semibold bg-blue-100 text-blue-700">In Trade</span>
: <span className="inline-block px-2.5 py-0.5 rounded-full text-xs font-semibold bg-slate-100 text-slate-500">Flat</span>}
</td>
</tr>
);
}
function FirmRows({ state, firm, deleteMode, selected, onToggle }: {
state: FirmState;
firm: FirmConfig;
deleteMode: boolean;
selected: boolean;
onToggle: () => void;
}) {
const [open, setOpen] = useState(true);
return (
<>
<tr
className="border-t border-slate-200 bg-slate-50 hover:bg-slate-100 cursor-pointer select-none transition-colors"
onClick={() => setOpen((o) => !o)}
>
<td className="px-4 py-3.5">
<div className="flex items-center gap-2.5">
{deleteMode && (
<input
type="checkbox"
checked={selected}
onChange={onToggle}
onClick={(e) => e.stopPropagation()}
className="w-4 h-4 accent-red-500 cursor-pointer flex-shrink-0"
/>
)}
<span className="font-bold text-sm text-slate-800">{state.firm}</span>
</div>
</td>
<td /><td /><td /><td />
<td className="px-4 py-3.5">
<div className="flex items-center justify-end gap-1">
<button
className="text-slate-400 hover:text-slate-600 hover:bg-slate-200 p-1 rounded-md transition-colors inline-flex"
onClick={(e) => e.stopPropagation()}
title="Settings"
>
<SettingsIcon />
</button>
<ChevronIcon open={open} />
</div>
</td>
</tr>
{open && (
state.accounts.length === 0 ? (
<tr>
<td colSpan={6} className="px-4 py-5 pl-12 text-sm text-slate-400 italic">
Waiting for data...
</td>
</tr>
) : (
state.accounts.map((acc) => (
<AccountRow key={acc.id} account={acc} firm={firm} />
))
)
)}
</>
);
}
export default function Home() {
return (
<div className="flex min-h-screen items-center justify-center bg-zinc-50 font-sans dark:bg-black">
<main className="flex min-h-screen w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={100}
height={20}
priority
/>
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
To get started, edit the page.tsx file.
</h1>
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
Looking for a starting point or more instructions? Head over to{" "}
<a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Templates
</a>{" "}
or the{" "}
<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Learning
</a>{" "}
center.
</p>
const router = useRouter();
const [config, setConfig] = useState<FirmConfig[]>([]);
const [firms, setFirms] = useState<FirmState[]>([]);
const [deleteMode, setDeleteMode] = useState(false);
const [selected, setSelected] = useState<Set<number>>(new Set());
const fetchConfig = async () => {
try {
const res = await fetch('/api/firms');
if (res.ok) {
const data: FirmConfig[] = await res.json();
setConfig(data);
}
} catch {
// server not running yet
}
};
useEffect(() => {
fetchConfig();
const fetchState = async () => {
try {
const res = await fetch('/api/state');
if (res.ok) {
const data: FirmState[] = await res.json();
setFirms(data);
}
} catch {
// server not running yet
}
};
fetchState();
const interval = setInterval(fetchState, 5000);
return () => clearInterval(interval);
}, []);
const handleConfirmDelete = async () => {
await Promise.all(
[...selected].map((id) =>
fetch(`/api/firms/${id}`, { method: 'DELETE' }).catch(() => {})
)
);
setSelected(new Set());
setDeleteMode(false);
fetchConfig();
};
const toggleSelected = (id: number) => {
setSelected((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
};
return (
<div className="min-h-screen bg-slate-50 p-8">
<div className="max-w-7xl mx-auto">
<div className="flex items-center justify-between mb-6">
<h1 className="text-2xl font-bold text-slate-900">AutoTrader</h1>
<div className="flex items-center gap-2">
{deleteMode ? (
<>
{selected.size > 0 && (
<button
onClick={handleConfirmDelete}
className="px-4 py-2 bg-red-100 hover:bg-red-200 text-red-700 text-sm font-semibold rounded-lg transition-colors"
>
Confirm Delete ({selected.size})
</button>
)}
<button
onClick={() => { setDeleteMode(false); setSelected(new Set()); }}
className="px-4 py-2 text-sm text-slate-600 hover:text-slate-800 border border-slate-200 bg-white rounded-lg transition-colors"
>
Cancel
</button>
</>
) : (
<>
<button
onClick={() => router.push('/add')}
className="px-4 py-2 bg-green-100 hover:bg-green-200 text-green-700 text-sm font-semibold rounded-lg transition-colors"
>
+ Add New
</button>
<button
onClick={() => setDeleteMode(true)}
className="px-4 py-2 bg-red-100 hover:bg-red-200 text-red-700 text-sm font-semibold rounded-lg transition-colors"
>
Delete
</button>
</>
)}
</div>
</div>
<div className="w-full bg-white border border-slate-200 rounded-xl overflow-hidden shadow-sm">
<table className="w-full text-sm border-collapse">
<thead>
<tr className="border-b border-slate-200 bg-slate-50">
<th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-400">Account</th>
<th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-400">Balance</th>
<th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-400">Day P&L</th>
<th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-400">Days Traded</th>
<th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-400">Target</th>
<th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-400">Status</th>
</tr>
</thead>
<tbody>
{config.length === 0 ? (
<tr>
<td colSpan={6} className="px-4 py-8 text-center text-sm text-slate-400 italic">
No firms yet click + Add New to get started
</td>
</tr>
) : (
config.map((cfg) => {
const state = firms.find((f) => f.firm === cfg.firm) ?? { firm: cfg.firm, connected: false, accounts: [] };
return (
<FirmRows
key={cfg.id}
state={state}
firm={cfg}
deleteMode={deleteMode}
selected={selected.has(cfg.id)}
onToggle={() => toggleSelected(cfg.id)}
/>
);
})
)}
</tbody>
</table>
</div>
</div>
</div>
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
<a
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={16}
height={16}
/>
Deploy Now
</a>
<a
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Documentation
</a>
</div>
</main>
</div>
);
);
}