> ## 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.

# Processar Calculadora (Consulta Pontual)

> Calcula o PNL atual de uma posição aberta consultando os dados de mercado mais recentes do MongoDB

## 📖 Descrição

Endpoint que calcula **pontualmente** o PNL (Profit and Loss) atual de uma posição de arbitragem spot-futuro. Busca os preços de mercado mais recentes da coleção `operations_future` (com cache de 55 segundos) e recalcula o PNL em relação aos dados de entrada salvos.

<Callout title="Prefira o stream SSE" icon="zap" color="green">
  Para monitoramento contínuo da posição, use `GET /v1/calculators/stream` em vez deste endpoint. O stream SSE elimina o polling e reduz a latência para \~1 segundo com menor sobrecarga no servidor.
</Callout>

***

## 🛠️ Requisição

### Método

`POST`

### URL

```plaintext theme={null}
/v1/calculators/process
```

### Request Body

| Campo      | Tipo   | Obrigatório | Descrição                           |
| ---------- | ------ | ----------- | ----------------------------------- |
| `email`    | string | Sim         | Email do usuário dono da posição    |
| `ticker`   | string | Sim         | Par de trading (ex: `BTC-USDT`)     |
| `exchange` | string | Sim         | Exchange da posição (ex: `binance`) |

### Exemplo de Requisição

```bash theme={null}
curl -X POST http://localhost:8080/v1/calculators/process \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "ticker": "BTC-USDT",
    "exchange": "binance"
  }'
```

***

## 📤 Resposta

### Exemplo de Resposta (200 OK)

```json theme={null}
{
  "email": "user@example.com",
  "ticker": "BTC-USDT",
  "exchange": "binance",
  "entrySpotValue": 83000.00,
  "entryShortValue": 83150.00,
  "entrySpotQty": 0.1,
  "entryFuturesQty": 0.1,
  "entrySpread": 150.00,
  "entrySpreadPercentage": 0.18,
  "currentSpotPrice": 85400.00,
  "currentFuturePrice": 85450.00,
  "currentSpread": 50.00,
  "currentSpreadPercentage": 0.058,
  "fundingRate": 0.0001,
  "pnl": 42.50,
  "pnlPercentage": 0.026,
  "isProfitable": true
}
```

### Campos da Resposta

| Campo                     | Tipo    | Descrição                |
| ------------------------- | ------- | ------------------------ |
| `email`                   | string  | Email do usuário         |
| `ticker`                  | string  | Par de trading           |
| `exchange`                | string  | Exchange                 |
| `entrySpotValue`          | float   | Preço spot de entrada    |
| `entryShortValue`         | float   | Preço futuro de entrada  |
| `entrySpotQty`            | float   | Quantidade spot          |
| `entryFuturesQty`         | float   | Quantidade futuro        |
| `entrySpread`             | float   | Spread na abertura       |
| `entrySpreadPercentage`   | float   | Spread na abertura em %  |
| `currentSpotPrice`        | float   | Preço spot atual         |
| `currentFuturePrice`      | float   | Preço futuro atual       |
| `currentSpread`           | float   | Spread atual             |
| `currentSpreadPercentage` | float   | Spread atual em %        |
| `fundingRate`             | float   | Taxa de funding atual    |
| `pnl`                     | float   | PNL total em USDT        |
| `pnlPercentage`           | float   | PNL em % sobre o capital |
| `isProfitable`            | boolean | `true` se `pnl > 0`      |

***

## 📝 Códigos de Resposta

<Callout type="success">
  **200 OK**: PNL calculado com sucesso.
</Callout>

<Callout type="warning">
  **400 Bad Request**:

  * `Invalid request body`: JSON malformado
  * `email is required`
  * `ticker is required`
  * `exchange is required`
</Callout>

<Callout type="error">
  **404 Not Found**:

  * `calculator not found`: Não há posição salva para `email + ticker`. Salve via `POST /v1/calculators` primeiro.
  * `market data not found`: Não há dados de mercado recentes (últimos 20 min) para o par na exchange.
</Callout>

<Callout type="error">
  **500 Internal Server Error**: `Failed to process calculator` — Erro interno.
</Callout>

***

## 💡 Cache de Dados de Mercado

Internamente, o endpoint usa um cache de **55 segundos** por `ticker + exchange`. Isso significa que chamadas feitas dentro desse intervalo reutilizam o mesmo dado, evitando queries repetidas ao MongoDB. A primeira chamada após o TTL faz uma nova query à coleção `operations_future`.

Para dados mais frescos (atualização a cada 5s), use `GET /v1/calculators/stream`.

***

## 🔁 Fórmula do PNL

```
spotValueChange    = (currentSpotPrice − entrySpotValue) × entrySpotQty
futureValueChange  = (entryShortValue − currentFuturePrice) × entryFuturesQty
PNL                = spotValueChange + futureValueChange

entryTotalValue    = (entrySpotValue × entrySpotQty) + (entryShortValue × entryFuturesQty)
PNLPercentage      = (PNL / entryTotalValue) × 100
```
