# Delta Terminal Backend

Self-hosted Node service that powers the frontend. Ships with **two
interchangeable database drivers** — pick one via a single env var, no
code changes required.

## Choose your database

| `DB_DRIVER` | Backing store          | When to use                              |
| ----------- | ---------------------- | ---------------------------------------- |
| `mongo`     | MongoDB (default)      | Flexible schema, high-write tick logs    |
| `mysql`     | MySQL 8+ (JSON column) | Existing MySQL infra / relational tools  |

Both adapters implement the same `DbAdapter` interface
(`src/db/adapter.js`) so the rest of the app never branches on driver.
Schema evolves freely — the MySQL adapter stores documents in a `data
JSON` column with generated-column indexes for hot fields.

## Quick start

```bash
cd backend
cp .env.example .env          # then edit DB_DRIVER + credentials + ENCRYPTION_KEY
npm install
npm run dev                   # → http://localhost:4000
```

### With Docker (Mongo + MySQL + backend, all local)

```bash
docker compose up --build
```

Then set `DB_DRIVER=mongo` or `DB_DRIVER=mysql` in `.env` and restart the
`backend` service to switch.

## Wire the frontend to it

Set in the Lovable project env:

```
VITE_API_BASE_URL=http://localhost:4000/api
VITE_BACKEND_WS_URL=ws://localhost:4000/ws
```

If the frontend runs on the Lovable preview (a `*.lovable.app` HTTPS
origin) and the backend runs on your machine at `http://localhost:4000`,
the browser will refuse the mixed HTTPS→HTTP request. Two options:

1. Run the frontend locally too (`bun dev`) so both are on `localhost`.
2. Expose the backend over HTTPS (Cloudflare Tunnel, ngrok, or deploy to
   Fly/Render) and point `VITE_API_BASE_URL` at the public URL.

## Endpoints

- `GET  /api/health` – driver + status
- `POST /api/delta/credentials` – link Delta API key/secret (signs + verifies)
- `GET  /api/delta/account` – live profile + USDT balance
- `GET  /api/positions` – active trades
- `POST /api/positions/:id/close` – manual close
- `GET  /api/signals?status=pending` – pending trade signals
- `POST /api/signals/:id/approve` – approve → creates ActiveTrade
- `POST /api/signals/:id/reject` – reject
- `WS   /ws` – push updates (`position.update`, `signal.new`, …)

## Security notes

- API secrets are encrypted at rest with AES-256-GCM
  (`ENCRYPTION_KEY` in `.env`, ≥32 chars).
- CORS defaults to `*` for local dev — lock it down in production via
  `CORS_ORIGIN`.
- `DEMO_USER_ID` is a placeholder — swap in real JWT auth before
  exposing this publicly.
