# Gold AI — MetaTrader 4 + MetaEditor Setup Guide v2.10

## Arsitektur Sistem

```
+---------------------------+          +------------------------+          +-----------------+
|   MetaTrader 4            |   HTTP   |   Gold AI Server       |   WS    |   PWA Dashboard |
|                           |          |   (Node.js :3000)      |         |   localhost:3000|
|  GoldAI_Bridge_EA.mq4    |---POST-->| POST /api/mt4/data     |-------->|   Realtime UI   |
|  (kirim OHLCV tiap 3s)   |          | (simpan candle data)   |         |   Multi-TF Grid |
|                           |<--JSON---| GET  /api/mt4/signals  |         |   MT4 Status    |
|  GoldAI_Signals_          |          | (kirim sinyal AI)      |         +-----------------+
|  Indicator.mq4            |          |                        |
|  (tampilkan sinyal visual)|          | AI Engine:             |
|                           |          |  RSI/MACD/EMA/BB/ADX  |
|  Chart Comment Panel      |          |  6 Timeframe Analysis  |
|  Arrow BUY/SELL           |          |  Multi-TF Confluence   |
|  SL / TP1 / TP2 / TP3    |          |  Entry + SL + TP       |
+---------------------------+          +------------------------+
```

---

## LANGKAH 1 — Aktifkan WebRequest di MT4

> **WAJIB** — tanpa ini EA tidak bisa komunikasi ke server

1. Buka **MetaTrader 4**
2. Klik menu **Tools → Options**
3. Pilih tab **Expert Advisors**
4. Centang ✅ **"Allow WebRequest for listed URL"**
5. Klik tombol **[+]** lalu ketik: `http://127.0.0.1:3000`
6. Klik **OK**

```
Tools > Options > Expert Advisors
[ ] Allow automated trading
[x] Allow WebRequest for listed URL:
    + http://127.0.0.1:3000
```

---

## LANGKAH 2 — Salin File ke MT4

### Cara Mudah: Buka Data Folder dari MT4
1. Di MT4: **File → Open Data Folder**
2. Masuk ke folder `MQL4`

### Tujuan file:

| File | Salin ke |
|------|----------|
| `GoldAI_Bridge_EA.mq4` | `MQL4\Experts\` |
| `GoldAI_Signals_Indicator.mq4` | `MQL4\Indicators\` |

### Path default MT4:
```
C:\Users\[NamaUser]\AppData\Roaming\MetaQuotes\Terminal\[ID]\MQL4\Experts\
C:\Users\[NamaUser]\AppData\Roaming\MetaQuotes\Terminal\[ID]\MQL4\Indicators\
```

---

## LANGKAH 3 — Compile di MetaEditor (WAJIB)

### Buka MetaEditor:
- Dari MT4: tekan **F4** atau klik ikon MetaEditor

### Compile EA:
1. Buka file: `MQL4\Experts\GoldAI_Bridge_EA.mq4`
2. Tekan **F7** atau klik **[Compile]**
3. Lihat tab **"Errors"** di bagian bawah
4. ✅ Harus tampil: `0 error(s), 0 warning(s)`

### Compile Indicator:
1. Buka file: `MQL4\Indicators\GoldAI_Signals_Indicator.mq4`
2. Tekan **F7** atau klik **[Compile]**
3. ✅ Harus tampil: `0 error(s), 0 warning(s)`

### Jika ada error:
| Error | Penyebab | Solusi |
|-------|----------|--------|
| `'CP_UTF8' - undeclared identifier` | File versi lama | Download versi terbaru |
| `'WebRequest' - wrong parameter count` | File versi lama | Download versi terbaru v2.10 |
| `implicit conversion from 'uchar' to 'char'` | Versi MT4 < 600 | Update MT4 ke versi terbaru |

---

## LANGKAH 4 — Jalankan Server AI

Buka **Command Prompt** / **Terminal** di folder project:

```cmd
cd "C:\path\ke\gold_ai_institutional_terminal_v2"
npm install
npm start
```

Output yang benar:
```
Gold AI Institutional Terminal v2 -- UPGRADED
   Dashboard  : http://localhost:3000
   WebSocket  : ws://localhost:3000
   MT4 Push   : POST http://localhost:3000/api/mt4/data
   MT4 Pull   : GET  http://localhost:3000/api/mt4/signals?symbol=XAUUSD
   MT4 Status : http://localhost:3000/api/mt4/status
```

> Server harus berjalan sebelum EA di-attach ke chart

---

## LANGKAH 5 — Pasang EA ke Chart

1. Buka chart **XAUUSD** (atau simbol apapun yang ingin dianalisis)
2. Pilih timeframe bebas (H1 direkomendasikan)
3. Di **Navigator panel**: buka **Expert Advisors** → cari `GoldAI_Bridge_EA`
4. **Drag & Drop** EA ke chart
5. Konfigurasi parameter:

| Parameter | Nilai Default | Keterangan |
|-----------|---------------|------------|
| `ServerURL` | `http://127.0.0.1:3000` | URL Gold AI server |
| `UpdateSeconds` | `3` | Interval kirim data (detik) |
| `BarsToSend` | `100` | Jumlah candle per timeframe |
| `SendM5` – `SendD1` | `true` | Pilih timeframe yang dikirim |
| `ShowArrows` | `true` | Gambar panah BUY/SELL di chart |
| `ShowInfoPanel` | `true` | Tampilkan panel info (Comment) |
| `EnableAlerts` | `true` | Alert + notif HP saat sinyal kuat |
| `AlertThreshold` | `70.0` | Min strength (%) untuk alert |
| `BuyColor` | `clrLime` | Warna sinyal BUY |
| `SellColor` | `clrRed` | Warna sinyal SELL |

6. Di tab **"Common"**:
   - ✅ **Allow live trading**
   - ✅ **Allow imports from DLL** (jika diminta)
7. Klik **OK**
8. Pastikan tombol **Auto Trading** aktif (ikon robot + warna hijau di toolbar)

---

## LANGKAH 6 — Pasang Indicator ke Chart (Opsional)

1. Di **Navigator** → **Indicators** → cari `GoldAI_Signals_Indicator`
2. **Drag & Drop** ke chart yang sama
3. Pastikan `ServerURL` sama dengan server
4. Konfigurasi:

| Parameter | Default | Keterangan |
|-----------|---------|------------|
| `ServerURL` | `http://127.0.0.1:3000` | Harus sama dengan EA |
| `RefreshSeconds` | `5` | Interval polling sinyal |
| `DrawTP` | `true` | Tampilkan garis TP1/TP2/TP3 |
| `DrawSL` | `true` | Tampilkan garis SL |
| `ShowPanel` | `true` | Panel info di chart (Comment) |
| `MinStrength` | `30.0` | Min strength untuk gambar panah |

5. Indicator akan menampilkan:
   - **Panah hijau ▲** = sinyal BUY
   - **Panah merah ▼** = sinyal SELL
   - **Garis TP1/TP2/TP3** = target profit (putus-putus)
   - **Garis SL** = stop loss (merah putus-putus)

---

## LANGKAH 7 — Verifikasi Koneksi

### Di MetaTrader 4:
- Chart Comment (pojok kiri atas) harus tampil:
```
+------ GOLD AI TERMINAL v2 --------+
| Signal  : BUY
| Prob    : 72.5%  Conf: 68.1%
| Strength: 45.0%  RSI: 58.3  ADX: 34.2
+-----------------------------------+
| Entry   : 2645.30000
| SL      : 2635.00000
| TP1     : 2655.60000
| TP2     : 2665.90000
| TP3     : 2676.20000  (1:3)
+-----------------------------------+
| Session : LONDON
| MACD    : BULL  Updates: 12
| Server  : [LIVE]  3s ago
+-----------------------------------+
```

### Di Tab MT4 "Experts" (F3):
```
Gold AI Bridge EA v2.10 STARTED
Symbol   : XAUUSD
Server   : http://127.0.0.1:3000
Interval : 3s  Bars:100
```

### Di Dashboard (http://localhost:3000):
- Status bar atas: **MT4: CONNECTED (Xs)**
- Data source: **MT4** (bukan SIMULATED)
- Multi-TF grid menampilkan data real dari broker

---

## TROUBLESHOOTING

| Gejala | Penyebab | Solusi |
|--------|----------|--------|
| Panel tampil `[OFFLINE]` | Server belum jalan | `npm start` di folder project |
| Panel tampil `[OFFLINE]` | WebRequest belum diizinkan | Langkah 1: Allow WebRequest |
| Panel tampil `HTTP 404` | URL salah | Cek `ServerURL` di EA settings |
| Panel tampil `HTTP -1` | Server offline | Jalankan `npm start` |
| `0 errors` tapi EA tidak jalan | Auto Trading OFF | Klik tombol robot hijau di toolbar |
| Panah tidak muncul | Strength < MinStrength | Kurangi `AlertThreshold` / `MinStrength` |
| MT4 status di dashboard offline | EA tidak aktif | Re-attach EA, aktifkan Auto Trading |
| Error compile `'WebRequest'` | File versi lama | Gunakan file v2.10 dari paket ini |

### Test Server Manual:
Buka browser, ketik:
```
http://localhost:3000/api/mt4/status
http://localhost:3000/api/mt4/signals?symbol=XAUUSD
http://localhost:3000/api/health
```
Harus tampil JSON response.

### Test MT4 Connection:
Di MetaEditor → Script baru, jalankan:
```mql4
void OnStart() {
   char empty[], result[];
   string hdr;
   ArrayResize(empty, 0);
   int code = WebRequest("GET","http://127.0.0.1:3000/api/health","",3000,empty,result,hdr);
   Print("HTTP Code: ", code);  // Harus 200
}
```

---

## Cara Kerja AI Engine

### Data Flow Detail:
```
MT4 (setiap 3 detik)
  Kirim: OHLCV 100 bar x 6 TF (M5, M15, M30, H1, H4, D1)

Server Gold AI Engine:
  [1] Per Timeframe:
      EMA 9/21/50/200 --> trend direction + alignment
      RSI (14)        --> overbought/oversold/momentum
      MACD (12,26,9)  --> crossover + histogram direction
      Bollinger Bands --> squeeze, breakout, %B position
      Stochastic (14,3)-> cyclic momentum overbought/oversold
      ATR (14)        --> volatility sizing (SL/TP distance)
      ADX (14)        --> trend strength (ranging vs trending)
      Support/Resistance -> pivot highs/lows (50 bar)
      Fibonacci (50 bar) -> 23.6/38.2/50/61.8/78.6 levels
      Candlestick Patterns -> 8 pattern types detected

  [2] Scoring (per TF):
      Tiap indikator + pola = skor bull atau bear
      EMA: 20pts  RSI: 18pts  MACD: 25pts  BB: 12pts
      Stoch: 10pts  ADX: 8pts  Volume: 8pts  S/R: 10pts

  [3] Multi-TF Confluence:
      Weight: M5(10%) M15(15%) M30(15%) H1(20%) H4(25%) D1(15%)
      Session weight: London(100%) NY(90%) Tokyo(70%)
      Agreement 80%+ TF -> +15 confidence bonus
      Agreement 60%+ TF -> +8 confidence bonus

  [4] Output per Sinyal:
      Direction: BUY / SELL / NEUTRAL
      Probability: 0.0 - 1.0
      Confidence: 0 - 100%
      Entry, SL, TP1, TP2, TP3

Kirim kembali ke MT4 dan Dashboard
```

### Timeframe Prediction Window:
| TF | Prediksi Untuk |
|----|----------------|
| M5  | 5-15 menit ke depan |
| M15 | 15-45 menit ke depan |
| M30 | 30 menit - 2 jam |
| H1  | 1-4 jam ke depan |
| H4  | 4-24 jam ke depan |
| D1  | 1-5 hari ke depan |

---

## API Reference

### MT4 → Server (Push candle data)
```
POST http://localhost:3000/api/mt4/data
Content-Type: application/json

{
  "symbol": "XAUUSD",
  "tick": { "bid": 2645.30, "ask": 2645.35, "time": 1234567890 },
  "timeframes": {
    "M5":  [ {"open":2644,"high":2646,"low":2643,"close":2645,"volume":512,"time":1234} ],
    "M15": [ ... ],
    "H1":  [ ... ],
    "H4":  [ ... ],
    "D1":  [ ... ]
  }
}

Response: {
  "status": "ok",
  "signal": "BUY",
  "probability": 0.72,
  "confidence": 68.5,
  "trade": { "entry":2645.30, "sl":2635.00, "tp1":2655.60, "tp2":2665.90, "tp3":2676.20 }
}
```

### Server → MT4 (Pull signals)
```
GET http://localhost:3000/api/mt4/signals?symbol=XAUUSD

Response: {
  "symbol": "XAUUSD",
  "direction": "BUY",
  "probability": 0.72,
  "confidence": 68.5,
  "strength": 44.0,
  "entry": 2645.30,
  "sl": 2635.00,
  "tp1": 2655.60,
  "tp2": 2665.90,
  "tp3": 2676.20,
  "rsi": 58.3,
  "adx": 34.2,
  "macdBull": true,
  "session": "LONDON",
  "timestamp": "2026-03-14T10:30:00.000Z"
}
```

---

## Catatan Penting

- **EA tidak melakukan trading otomatis** — hanya menampilkan sinyal
- **Server wajib berjalan** sebelum EA di-attach
- **Semua sinyal bersifat informatif** — tetap gunakan manajemen risiko
- **BarsToSend = 100** direkomendasikan untuk performa optimal
- Untuk pair lain (BTCUSD, EURUSD, dll.), attach EA ke chart masing-masing

---

*Gold AI Institutional Terminal v2.10 — MT4 Integration Guide*
*Build: 2026-03-14 | Compatible: MetaTrader 4 Build 600+*
