# AutoHedge — Namecheap deployment guide

This guide puts AutoHedge on a **Namecheap Stellar Plus** shared hosting account using
**Namecheap's own PostgreSQL database**. You don't need any outside database service, and you
never run `npm install` or a build on the server.

---

## 0. What's in the package

Unzip it and you get this (everything sits directly at the top, no extra wrapper folder):

```text
server.js              startup file (the one cPanel runs)
package.json           tells cPanel the startup file
env.example            settings template -> copy to .env
.env.example           same template, hidden-file version
htaccess.example       optional HTTPS redirect -> rename to .htaccess
DEPLOYMENT.md          this guide
README.md              short pointer to this guide
database/
  autohedge-setup.sql  everything in one file: tables, permissions, the 5 tested
                       strategies and the default admin login (run once)
  schema-hosted-backend.sql  only for a hosted backend, not needed on Namecheap
app/                   the pre-built app. Don't edit or rename.
tmp/restart.txt        touch it to restart the app
```

On first start `server.js` creates a `runtime/` folder next to `app/`. That's the copy that
actually runs; it's rebuilt automatically, so you can delete it whenever.

You'll need:
- cPanel access to your Stellar Plus account
- A domain or subdomain pointed at the account (for example `trade.yourdomain.com`)
- Optional: an Alpaca key (live prices), an EODHD key (history and news) and an AI key from
  OpenAI, OpenRouter, Groq or another OpenAI-compatible service. You can also add these later
  in the app.

---

## 1. Create the PostgreSQL database

1. cPanel → **Databases** → **PostgreSQL Databases**.
2. **Create New Database**: type `autohedge`. cPanel saves it as `youraccount_autohedge`.
3. **Add New User**: type `ahuser` and a strong password, then **Create User**.
   cPanel saves it as `youraccount_ahuser`. Write the password down.
4. **Add User To Database**: pick the user and the database, then tick **ALL PRIVILEGES**.
5. Note the connection details:
   - host `localhost`, port `5432`
   - database `youraccount_autohedge`, user `youraccount_ahuser`

> If you don't see "PostgreSQL Databases" in cPanel, ask Namecheap support to turn PostgreSQL
> on for your account. Stellar Plus includes it.

## 2. Load the database (one file, one run)

**Option A — phpPgAdmin (no command line)**
1. cPanel → **phpPgAdmin** → open `youraccount_autohedge` on the left.
2. Click **SQL** at the top → **Choose file** → pick `database/autohedge-setup.sql` → **Execute**.
   It should finish without a red error. That's it: tables, strategies and the admin login are in.

**Option B — Terminal (cPanel → Advanced → Terminal, or SSH)**
```bash
cd ~/autohedge
psql "postgresql://youraccount_ahuser:PASSWORD@localhost:5432/youraccount_autohedge" -f database/autohedge-setup.sql
```

> **If you get "ALTER TYPE ... ADD cannot run inside a transaction block"**: your PostgreSQL is
> older than version 12 and phpPgAdmin ran the file as one block. Use Option B (psql runs each
> statement separately), or run the file a second time. Every statement is safe to repeat.
> The schema needs PostgreSQL 9.6 or newer. It was tested on PostgreSQL 16 with a non-admin
> database user, which is the same setup as cPanel.

## 3. Create the Node.js app

1. cPanel → **Software** → **Setup Node.js App** → **Create Application**:
   - Node.js version: **20** (or the highest offered, at least 18)
   - Application mode: **Production**
   - Application root: `autohedge`
   - Application URL: your domain or subdomain
   - Application startup file: `server.js`
2. Click **Create**. Leave the page open.
3. **Don't** click "Run NPM Install". Nothing needs installing.

## 4. Upload the package

1. cPanel → **File Manager** → open the `autohedge` folder (the application root).
2. **Upload** `autohedge-namecheap.zip`, then right-click it → **Extract** into this same folder.
   `server.js`, `env.example`, `app/` and `database/` now sit directly in `~/autohedge/`.
3. Delete the zip.

## 5. Fill in the settings

1. Right-click `env.example` → **Copy** → name the copy `.env`, then edit `.env`:
   (`.env` starts with a dot, so turn on **Settings → Show Hidden Files** to see it afterwards.)
   ```
   DATABASE_URL=postgresql://youraccount_ahuser:PASSWORD@localhost:5432/youraccount_autohedge
   SESSION_SECRET=<at least 32 random characters>
   ADMIN_EMAILS=you@yourdomain.com
   ```
   - Password characters such as `@ # / :` must be written as `%40 %23 %2F %3A`.
   - For a random secret, use any password generator set to 40+ characters.
2. Optional: fill in `ALPACA_*`, `EODHD_API_TOKEN` and `AI_*`, or add them later in the app.
3. Save.

## 6. Start it

1. In **Setup Node.js App**, click **Restart** (or create or touch the file `tmp/restart.txt`).
2. Wait 15–20 seconds, then open your domain.
3. On first start, `server.js` copies `app/` to `runtime/` and switches the app to
   PostgreSQL mode. You'll see the line `config injected` in `stderr.log`.

## 7. First login

### Default admin account (demo)

Loading `autohedge-setup.sql` creates a ready-made administrator:

| Email | Password |
|---|---|
| `demo.admin@autohedge.app` | `AutoHedgeAdmin2026!` |

Open `https://yourdomain/auth` → **Sign in** with it and you have full control of the app.
This login is public in this document, so for anything beyond a demo, create your own admin
(below), then remove the demo admin's Administrator switch under **Administration → Users**.

### Your own admin account

1. Open `https://yourdomain/auth` → **Create account** with the email you put in `ADMIN_EMAILS`.
   That account becomes an admin straight away.
   (If you forgot `ADMIN_EMAILS`, use **Claim admin access** on the dashboard. The first account
   to claim it becomes admin.)
2. **Administration → API keys**: paste the Alpaca, EODHD and AI keys and press **Test** on each.
3. **Strategies**: the 5 tested strategies are already published.
4. Traders sign up the same way. Each new account gets 100,000 demo money.

### Who can add users?

- **Anyone** who can open `/auth` can create their own account (email + password). Admins do not
  create accounts; there are no invitations.
- New accounts are always traders. They become admins only if their email is listed in
  `ADMIN_EMAILS` before they sign up, or when an admin turns on **Administrator** for them under
  **Administration → Users**. Admins can also top up demo money there.
- The package ships clean: no user accounts, no demo allocations or trades — only the 5 tested
  strategies (from `autohedge-setup.sql`).

## 8. HTTPS

- cPanel → **SSL/TLS Status** → run AutoSSL for the domain (it's usually already on).
- Optional: rename `htaccess.example` to `.htaccess` to send everyone to `https://`.
- Login cookies are marked secure, so **use https**. On a plain-http test domain, add
  `INSECURE_COOKIES=1` to `.env`.

## 9. Updating to a new version

1. On your own computer, in the project folder, run: `bash deploy/namecheap/build-package.sh`
2. Upload the new zip and extract it. Replace `app/`, `server.js` and `database/`.
3. Delete the `runtime/` folder (it's rebuilt on start). **Keep `.env`.**
4. If the release notes mention database changes, run the new `database/autohedge-setup.sql` again.
5. Restart.

## 10. Backups

- cPanel → **Backup** → **Download a PostgreSQL Database Backup** → `youraccount_autohedge`.
- Or in Terminal: `pg_dump "$DATABASE_URL" > autohedge-$(date +%F).sql`

## 11. Hosting limits (Stellar Plus) and what they mean

| Limit | Effect |
|---|---|
| No build or npm install on the server | The package is pre-built and every library is inside `app/server`. |
| About 1 GB RAM, limited CPU, few processes | Runs as one Node process. Keep backtests to 10 tickers and 2 years or less. |
| Idle apps go to sleep | Auto-trade runs only while someone has the app open. The first visit after a pause takes a few seconds. |
| Web requests time out after about 120 seconds | Very long backtests can time out. Shorten the date range if that happens. |
| No background jobs for Node | To keep the app awake, add a cPanel Cron Job: `curl -s https://yourdomain/ > /dev/null` every 10 minutes. |
| Outgoing connections are HTTPS only | Alpaca, EODHD and the AI services all use HTTPS, so this is fine. |
| PostgreSQL is reachable only from the account | `localhost` in `DATABASE_URL` is correct. Remote database tools need an SSH tunnel. |

## 12. Troubleshooting

| Symptom | Fix |
|---|---|
| 503 or blank page | Open `stderr.log` in the app root. If it says `.env missing`, create `.env`. |
| `SESSION_SECRET missing` | Add a secret of 32+ characters to `.env` and restart. |
| `password authentication failed` | Check the user, password and URL-encoding in `DATABASE_URL`. Re-add the user to the database with ALL PRIVILEGES. |
| `relation "strategies" does not exist` | Step 2 wasn't run on this database. |
| Signed in, but sent straight back to login | You're on http instead of https. Use https, or set `INSECURE_COOKIES=1`. |
| "Unauthorized: please sign in" after changing `.env` | The `SESSION_SECRET` changed, so sign in again. |
| AI, price or backtest errors | Administration → API keys → press **Test** on each provider. |

## 13. How it works (technical)

- `DATABASE_URL` set: the app uses PostgreSQL directly and its own email/password login
  (scrypt password hashes, signed http-only session cookie). Nothing else is needed.
- Permissions stay inside the database. Each request runs as the signed-in user, and the
  row-level security policies in `schema-postgres.sql` decide what that user can see or change.
  For example, a trader can't read another trader's portfolio or edit a strategy.
- `DATABASE_URL` empty: the app falls back to a hosted backend (the Lovable preview setup).
- Boot order: `LiteSpeed → Passenger → server.js → runtime/server/index.mjs`.
