# 🐧 REXMULTITRADE - Instalação em Servidor Linux

## 📋 Pré-requisitos

```bash
# Python 3.8+
python3 --version

# Git (para clonar repositório)
sudo apt update
sudo apt install -y git

# Tkinter (para GUI em modo desktop)
sudo apt install -y python3-tk

# Outras dependências
sudo apt install -y curl wget
```

---

## 🚀 Instalação Passo a Passo

### 1️⃣ Clone o Repositório
```bash
cd /home/seu-usuario
git clone https://github.com/seu-usuario/rexmultitrade.git
cd rexmultitrade

# Verifique estrutura
ls -la
```

### 2️⃣ Configure Permissões
```bash
# Executáveis
chmod +x iniciar_gui.sh
chmod +x iniciar_gui_mac.sh

# Diretórios
mkdir -p logs
chmod 755 logs

# Criar arquivo de log vazio
touch logs/log_trades.log
chmod 644 logs/log_trades.log
```

### 3️⃣ Configure as Credenciais Binance

Edite `configuracoes.json`:
```bash
nano configuracoes.json
```

```json
{
  "binance_api_key": "sua_chave_aqui",
  "binance_secret_key": "seu_secret_aqui",
  "moedas": [
    {
      "par": "TRX/USDT",
      "symbol": "TRXUSDT",
      "capital": 100,
      "capital_min": 50,
      "agressividade": 0.98,
      "ativo": true
    }
  ]
}
```

### 4️⃣ Teste a Instalação
```bash
python3 teste_instalacao.py
```

Deve exibir:
```
✓ Python 3.8+
✓ Binance API responde
✓ Estrutura de diretórios OK
✓ Arquivo de configuração OK
```

---

## 🎯 3 Formas de Rodar

### **Opção 1: Interface Gráfica (Desktop)**

#### Se servidor tem GUI (desktop Linux)
```bash
./iniciar_gui.sh
```

**Vai:**
- Abrir janela GUI
- Carregar dashboard
- Permitir clicar em [▶ Iniciar Robô]

---

### **Opção 2: Linha de Comando com tmux (Recomendado)**

#### Instalar tmux
```bash
sudo apt install -y tmux
```

#### Criar sessão
```bash
# Nova sessão
tmux new-session -d -s rexmultitrade "cd ~/rexmultitrade && python3 rexmultitrade.py"

# Listar sessões
tmux list-sessions

# Conectar para monitorar
tmux attach -t rexmultitrade

# Desconectar (deixa rodando): Ctrl+B depois D
```

#### Monitorar logs
```bash
# Em outro terminal
tail -f logs/log_trades.log

# Ou em tempo real com grep
tail -f logs/log_trades.log | grep "VENDA\|COMPRA\|ERROR"
```

---

### **Opção 3: Systemd (Profissional)**

#### Criar arquivo de serviço

```bash
sudo nano /etc/systemd/system/rexmultitrade.service
```

```ini
[Unit]
Description=REXMULTITRADE - Robô de Trading
After=network.target

[Service]
Type=simple
User=seu-usuario
WorkingDirectory=/home/seu-usuario/rexmultitrade
ExecStart=/usr/bin/python3 /home/seu-usuario/rexmultitrade/rexmultitrade.py
Restart=always
RestartSec=10
StandardOutput=append:/home/seu-usuario/rexmultitrade/logs/systemd.log
StandardError=append:/home/seu-usuario/rexmultitrade/logs/systemd.log
Environment="PATH=/usr/local/bin:/usr/bin:/bin"

[Install]
WantedBy=multi-user.target
```

#### Habilitar e iniciar
```bash
# Recarregar systemd
sudo systemctl daemon-reload

# Habilitar (iniciar ao boot)
sudo systemctl enable rexmultitrade

# Iniciar serviço
sudo systemctl start rexmultitrade

# Verificar status
sudo systemctl status rexmultitrade

# Ver logs
journalctl -u rexmultitrade -f
```

#### Comandos úteis
```bash
# Parar serviço
sudo systemctl stop rexmultitrade

# Reiniciar
sudo systemctl restart rexmultitrade

# Desabilitar do auto-start
sudo systemctl disable rexmultitrade

# Ver logs completos
journalctl -u rexmultitrade -n 100

# Monitorar em tempo real
journalctl -u rexmultitrade -f
```

---

## 📊 Setup Recomendado para Produção

### Estrutura Ideal
```
Servidor Linux (Produção)
├─ rexmultitrade (seu repositório)
├─ Robô rodando via systemd
├─ Logs em /home/usuario/rexmultitrade/logs
├─ XAMPP/Apache para dashboard web
└─ Acesso SSH para monitorar
```

### Script de Instalação Completo
```bash
#!/bin/bash
# setup-rexmultitrade.sh

# 1. Atualizar sistema
sudo apt update && sudo apt upgrade -y

# 2. Instalar dependências
sudo apt install -y python3-tk python3-pip git curl wget

# 3. Clone repo (ou pull se já existe)
cd /home/seu-usuario
if [ ! -d "rexmultitrade" ]; then
  git clone https://github.com/seu-usuario/rexmultitrade.git
else
  cd rexmultitrade
  git pull
fi

cd rexmultitrade

# 4. Configurar permissões
chmod +x iniciar_gui.sh
mkdir -p logs
chmod 755 logs

# 5. Criar serviço systemd
sudo cp rexmultitrade.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable rexmultitrade
sudo systemctl start rexmultitrade

# 6. Verificar
sudo systemctl status rexmultitrade

echo "✓ Instalação concluída!"
```

---

## 🌐 Acessar Dashboard Web

### 1️⃣ Verificar Apache/XAMPP
```bash
# Verificar se Apache está rodando
sudo systemctl status apache2

# Ou iniciar
sudo systemctl start apache2
```

### 2️⃣ Criar link simbólico
```bash
# Se usando XAMPP
sudo ln -s /home/seu-usuario/rexmultitrade /opt/lampp/htdocs/rexmultitrade

# Se usando Apache nativo
sudo ln -s /home/seu-usuario/rexmultitrade /var/www/html/rexmultitrade

# Dar permissões
sudo chmod -R 755 /home/seu-usuario/rexmultitrade
```

### 3️⃣ Acessar
```
http://seu-servidor/rexmultitrade/rexmultitrade_dashboard.php
```

---

## 📱 Acessar de Dispositivos Remotos

### Do Celular/Laptop (mesma rede)
```
http://ip-do-servidor/rexmultitrade/rexmultitrade_dashboard.php

# Exemplo:
http://192.168.1.100/rexmultitrade/rexmultitrade_dashboard.php
```

### Via SSH Tunnel
```bash
# De seu laptop
ssh -L 8000:localhost:80 seu-usuario@seu-servidor

# Depois abra no navegador
http://localhost:8000/rexmultitrade/rexmultitrade_dashboard.php
```

---

## 🛡️ Segurança

### Credenciais Binance
```bash
# Nunca colocar em GitHub!
# Adicionar ao .gitignore
echo "configuracoes.json" >> .gitignore

# Restringir permissões
chmod 600 configuracoes.json
```

### Arquivo de Log
```bash
# Restringir para seu usuário apenas
chmod 600 logs/log_trades.log
```

### Dashboard Web
```bash
# Proteger com .htpasswd
sudo apt install -y apache2-utils
sudo htpasswd -c /home/seu-usuario/rexmultitrade/.htpasswd seu-usuario
```

Editar `/etc/apache2/sites-enabled/000-default.conf`:
```apache
<Directory /var/www/html/rexmultitrade>
    AuthType Basic
    AuthName "REXMULTITRADE"
    AuthUserFile /home/seu-usuario/rexmultitrade/.htpasswd
    Require valid-user
</Directory>
```

---

## 🔧 Troubleshooting

### "Módulo não encontrado"
```bash
pip3 install requests websocket-client
```

### "Conexão Binance recusada"
```bash
# Verificar internet
ping 8.8.8.8

# Testar API
python3 -c "import requests; print(requests.get('https://api.binance.com/api/v3/ping').status_code)"
```

### "Permissão negada"
```bash
# Verificar proprietário
ls -la logs/

# Corrigir
sudo chown seu-usuario:seu-usuario logs -R
```

### "Robô não inicia via systemd"
```bash
# Ver erro completo
journalctl -u rexmultitrade -n 50

# Ou
sudo systemctl status rexmultitrade -l
```

### "Logs não aparecem"
```bash
# Verificar se arquivo está sendo criado
ls -la logs/log_trades.log

# Ou criar manualmente
touch logs/log_trades.log
chmod 644 logs/log_trades.log
```

---

## 📊 Monitorar Saúde do Sistema

### CPU e Memória
```bash
# Ver robô
ps aux | grep rexmultitrade.py

# Monitorar em tempo real
top -p $(pgrep -f rexmultitrade.py)

# Ou usar btop (mais bonito)
sudo apt install -y btop
btop
```

### Conectividade
```bash
# Verificar latência Binance
ping api.binance.com

# Testar requisição
curl -I https://api.binance.com/api/v3/ping
```

### Espaço em Disco
```bash
# Ver espaço
df -h

# Tamanho de logs
du -sh logs/
```

---

## 🔄 Backup Automático

### Script de Backup
```bash
#!/bin/bash
# backup-rexmultitrade.sh

DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/home/seu-usuario/backups"

mkdir -p $BACKUP_DIR

# Backup de configuração e estado
tar -czf $BACKUP_DIR/rexmultitrade_${DATE}.tar.gz \
  /home/seu-usuario/rexmultitrade/configuracoes.json \
  /home/seu-usuario/rexmultitrade/estado_robos.json \
  /home/seu-usuario/rexmultitrade/logs

# Manter apenas últimos 7 dias
find $BACKUP_DIR -name "*.tar.gz" -mtime +7 -delete

echo "Backup criado: rexmultitrade_${DATE}.tar.gz"
```

### Agendar com Cron
```bash
# Editar crontab
crontab -e

# Adicionar (backup diário às 3 da manhã)
0 3 * * * /home/seu-usuario/backup-rexmultitrade.sh
```

---

## ✅ Checklist de Produção

```
☑️ Python 3.8+ instalado
☑️ Tkinter instalado (para GUI)
☑️ Credenciais Binance configuradas
☑️ Logs com permissões corretas
☑️ Serviço systemd criado
☑️ Inicialização automática habilitada
☑️ Dashboard acessível
☑️ Backup configurado
☑️ Firewall permite acesso SSH
☑️ Monitoramento de logs ativo
```

---

## 🎓 Exemplo Completo: Do Zero à Produção

```bash
# 1. SSH para servidor
ssh seu-usuario@seu-servidor

# 2. Clone repositório
cd ~
git clone https://github.com/seu-usuario/rexmultitrade.git
cd rexmultitrade

# 3. Instale dependências
sudo apt update
sudo apt install -y python3-tk git curl

# 4. Configure credenciais
nano configuracoes.json
# (edite com suas credenciais)

# 5. Teste
python3 teste_instalacao.py

# 6. Crie serviço systemd
sudo cp rexmultitrade.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable rexmultitrade
sudo systemctl start rexmultitrade

# 7. Verifique
sudo systemctl status rexmultitrade

# 8. Monitore logs
journalctl -u rexmultitrade -f

# ✓ Pronto! Robô rodando 24/7!
```

---

**Seu REXMULTITRADE está pronto para rodar em produção! 🚀**
