> ## Documentation Index
> Fetch the complete documentation index at: https://docs.arbitragem-crypto.cloud/llms.txt
> Use this file to discover all available pages before exploring further.

# Get Arbitrage Candlestick

## 📖 Descrição

Este endpoint retorna dados históricos de arbitragem em formato de candlestick, baseados nos dados armazenados na collection `operations_audit` do MongoDB. Os dados são agregados em snapshots temporais com oportunidades de arbitragem calculadas.

<Callout type="info">
  Esta funcionalidade utiliza dados históricos já processados, não fazendo chamadas em tempo real para APIs externas, garantindo performance e consistência.
</Callout>

***

## 🛠️ Requisição

### Método

`GET`

### URL

```plaintext theme={null}
/v1/candlestick
```

### Parâmetros de Query

| Parâmetro   | Tipo   | Obrigatório | Descrição                                                         |
| ----------- | ------ | ----------- | ----------------------------------------------------------------- |
| `ticker`    | string | Sim         | Par de moedas (ex: "BTC-USDT", "ETH-USDT")                        |
| `exchanges` | string | Não         | Lista de exchanges separadas por vírgula (ex: "binance,coinbase") |
| `period`    | string | Sim         | Período de análise: "7 days", "15 days", "30 days"                |

### Exemplo de Requisição

```bash theme={null}
curl --location 'localhost:8080/v1/candlestick?ticker=BTC-USDT&exchanges=binance,coinbase,kraken&period=7%20days'
```

### Exemplo de Resposta

```json theme={null}
{
  "ticker": "BTC-USDT",
  "exchanges": ["binance", "coinbase", "kraken"],
  "period": "7 days",
  "start_time": "2024-01-01T00:00:00Z",
  "end_time": "2024-01-08T00:00:00Z",
  "data": [
    {
      "timestamp": "2024-01-01T10:00:00Z",
      "exchange_data": {
        "binance": {
          "exchange_name": "binance",
          "symbol": "BTC-USDT",
          "bid_price": 45000.0,
          "ask_price": 45050.0,
          "bid_qty": 1.5,
          "ask_qty": 2.0,
          "bid_volume": 67500.0,
          "ask_volume": 90100.0,
          "total_volume": 157600.0,
          "last_price": 45025.0,
          "spread": 50.0,
          "spread_percentage": 0.11
        },
        "coinbase": {
          "exchange_name": "coinbase",
          "symbol": "BTC-USDT",
          "bid_price": 44980.0,
          "ask_price": 45030.0,
          "bid_qty": 1.2,
          "ask_qty": 1.8,
          "bid_volume": 53976.0,
          "ask_volume": 81054.0,
          "total_volume": 135030.0,
          "last_price": 45005.0,
          "spread": 50.0,
          "spread_percentage": 0.11
        }
      },
      "arbitrage_opportunities": [
        {
          "buy_exchange": "coinbase",
          "sell_exchange": "binance",
          "buy_price": 45030.0,
          "sell_price": 45000.0,
          "buy_qty": 1.2,
          "sell_qty": 1.2,
          "spread": -30.0,
          "spread_percentage": -0.07,
          "buy_fee": 54.04,
          "sell_fee": 54.0,
          "withdraw_fee": 0.0,
          "net_profit": -138.04,
          "net_profit_percentage": -0.31,
          "min_trade_amount": 450.3,
          "max_trade_amount": 54036.0,
          "is_profitable": false,
          "liquidity_score": 135030.0
        }
      ]
    }
  ],
  "statistics": {
    "total_snapshots": 168,
    "total_opportunities": 5040,
    "profitable_count": 1200,
    "avg_spread_percentage": 0.15,
    "max_spread_percentage": 2.5,
    "min_spread_percentage": -1.2,
    "avg_net_profit_percentage": 0.08,
    "max_net_profit_percentage": 1.8,
    "best_exchange_pair": "binance-coinbase",
    "total_volume": 125000.5
  }
}
```

***

## 📝 Notas sobre os Parâmetros

<Callout type="info">
  **Parâmetros de Query:**

  * `ticker`: Deve ser exatamente igual ao formato armazenado no banco (ex: "BTC-USDT")
  * `exchanges`: Se não especificado, usa todas as exchanges disponíveis
  * `period`: Define o intervalo de snapshot (5min para 7 dias, 15min para 15 dias, 30min para 30 dias)
</Callout>

## 🔍 Exchanges Suportadas

As exchanges suportadas são as mesmas disponíveis no sistema principal:

* **binance**, **coinbase**, **kraken**, **kucoin**, **gateio**
* **okx**, **bybit**, **mexc**, **htx**, **bitfinex**
* **bitstamp**, **bitget**, **novadax**, **bingx**
* **bitnuvem**, **crypto-ponto-com**, **mercado-btc**

<Callout type="warning">
  Certifique-se de que as exchanges especificadas estejam entre as suportadas pelo sistema.
</Callout>

***

## 📊 Estrutura de Dados

### 🎯 **ExchangePriceData**

```typescript theme={null}
{
  exchange_name: string,        // Nome da exchange
  symbol: string,              // Par de moedas
  bid_price: number,           // Preço de compra
  ask_price: number,           // Preço de venda
  bid_qty: number,             // Quantidade disponível para compra
  ask_qty: number,             // Quantidade disponível para venda
  bid_volume: number,          // Volume de compra
  ask_volume: number,          // Volume de venda
  total_volume: number,        // Volume total
  last_price: number,          // Preço médio
  spread: number,              // Spread absoluto
  spread_percentage: number    // Spread percentual
}
```

### 💰 **ArbitrageOpportunity**

```typescript theme={null}
{
  buy_exchange: string,           // Exchange de compra
  sell_exchange: string,          // Exchange de venda
  buy_price: number,              // Preço de compra
  sell_price: number,             // Preço de venda
  buy_qty: number,                // Quantidade para compra
  sell_qty: number,               // Quantidade para venda
  spread: number,                 // Spread absoluto
  spread_percentage: number,      // Spread percentual
  buy_fee: number,                // Taxa de compra
  sell_fee: number,               // Taxa de venda
  withdraw_fee: number,           // Taxa de saque
  net_profit: number,             // Lucro líquido
  net_profit_percentage: number,  // Lucro percentual
  min_trade_amount: number,       // Valor mínimo de trade
  max_trade_amount: number,       // Valor máximo de trade
  is_profitable: boolean,         // Se é lucrativo
  liquidity_score: number         // Score de liquidez
}
```

### 📈 **ArbitrageStatistics**

```typescript theme={null}
{
  total_snapshots: number,        // Total de snapshots
  total_opportunities: number,    // Total de oportunidades
  profitable_count: number,       // Oportunidades lucrativas
  avg_spread_percentage: number,  // Spread médio
  max_spread_percentage: number,  // Spread máximo
  min_spread_percentage: number,  // Spread mínimo
  avg_net_profit_percentage: number,  // Lucro médio
  max_net_profit_percentage: number,  // Lucro máximo
  best_exchange_pair: string,     // Melhor par de exchanges
  total_volume: number            // Volume total
}
```

***

## ⚡ Performance e Cache

### 🚀 **Sistema de Cache**

* **Duração**: 2 horas por chave
* **Chave**: `arbitrage_candlestick:{ticker}:{exchanges}:{period}`
* **Backend**: Redis (se configurado) ou memória local

### 📊 **Intervalos de Snapshot**

| Período | Intervalo  | Snapshots/Dia | Total (7 dias) |
| ------- | ---------- | ------------- | -------------- |
| 7 days  | 5 minutos  | 288           | 2,016          |
| 15 days | 15 minutos | 96            | 1,440          |
| 30 days | 30 minutos | 48            | 1,440          |

***

## 🔧 Códigos de Status HTTP

* `200 OK`: Sucesso
* `400 Bad Request`: Parâmetros inválidos ou ausentes
* `500 Internal Server Error`: Erro interno do servidor

## 🚨 Tratamento de Erros

```json theme={null}
{
  "error": "Missing required parameters: ticker, period"
}
```

```json theme={null}
{
  "error": "Invalid period. Use: 7 days, 15 days, or 30 days"
}
```

***

## 📚 Exemplos de Uso

### 🔍 **Análise de BTC-USDT em 7 dias**

```bash theme={null}
curl 'localhost:8080/v1/candlestick?ticker=BTC-USDT&period=7%20days'
```

### 🎯 **Análise específica de exchanges**

```bash theme={null}
curl 'localhost:8080/v1/candlestick?ticker=ETH-USDT&exchanges=binance,coinbase,kraken&period=15%20days'
```

### 📊 **Análise de longo prazo**

```bash theme={null}
curl 'localhost:8080/v1/candlestick?ticker=ADA-USDT&period=30%20days'
```

<Callout type="info">
  **Dica**: Use ferramentas como `jq` para processar as respostas JSON e extrair métricas específicas:

  ```bash theme={null}
  curl 'localhost:8080/v1/candlestick?ticker=BTC-USDT&period=7%20days' | jq '.statistics.best_exchange_pair'
  ```
</Callout>
