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

# Enviar ordens

> Envie uma ou mais ordens à exchange

Envie uma ou mais ordens. O endpoint aceita um lote: os resultados por ordem voltam em `data.createdSessions`, **de forma posicional** em relação ao seu array `orders` de entrada. Cada entrada é um resultado bem-sucedido `{ matched, unmatched }` ou uma falha `{ error, errorType }`.

## Requisição

`POST /session/v3/place`

```bash curl theme={null}
curl -X POST https://api.4casters.io/session/v3/place \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "orders": [
      {
        "gameID": "688c0516fbc14da0c202d426",
        "type": "moneyline",
        "side": "5c12bc1ce0daba000f47ba8b",
        "odds": -175,
        "bet": 100,
        "orderType": "post",
        "userReference": "docs-example"
      }
    ]
  }'
```

```json Corpo JSON theme={null}
{
  "orders": [
    {
      "gameID": "4CASTER_GAME_ID",
      "type": "moneyline | spread | total | moneyline1x2",
      "side": "PARTICIPANT_ID | over | under | yes | no",
      "market": "PARTICIPANT_ID | draw",
      "odds": -110,
      "bet": 100,
      "number": 3.5,
      "orderType": "limit | post | postArb | fillAndKill | fillOrKill",
      "expirationMinutes": 10,
      "userReference": "OPTIONAL_CLIENT_SIDE_IDENTIFIER"
    }
  ]
}
```

### Campos da ordem

<Snippet file="pt-BR/types/order-fields.mdx" />

## Tipos de ordem

### `limit`

O tipo de ordem padrão. Executa contra qualquer liquidez correspondente ao seu preço ou melhor como taker (com comissão de taker) e deixa o restante no livro como maker. Uma ordem `limit` pode ficar totalmente casada, totalmente em aberto, ou parcialmente casada com o restante em aberto.

### `post`

Cria uma oferta em aberto. Se a ordem **casaria** com liquidez existente ao ser enviada, o servidor a rejeita (`rejected_order_type_rules`, p. ex. `"post order cannot have matches"`).

### `postArb`

Comporta-se como `post`, mas você pode enviar **mesmo quando a ordem casaria**, **somente se** suas odds americanas estiverem dentro de **1%** das odds da ordem em aberto com a qual você casaria. Se a diferença de preço for maior que 1%, o envio é rejeitado.

Exemplos:

* Melhor oferta **+100** e você envia **+100** — `post` é rejeitada (casaria); `postArb` é permitida.
* Melhor oferta **+200** — `postArb` a **+190** é rejeitada (longe demais de **+200**). Em torno de **+198** está na borda da faixa de 1% frente a **+200**.
* Melhor ordem **−200** — a faixa se estende até cerca de **−202** no lado negativo (a mesma regra de 1%).
* Com **+100** no livro, **−101** é o limite de referência do outro lado para a tolerância de 1%.

`postArb` evita as **comissões de taker** de um cruzamento normal: você não é cobrado por comissões de taker neste fluxo como ocorreria se tomasse liquidez em aberto como taker.

As ordens enviadas como `postArb` são marcadas com `isPostArb: true` em suas atualizações do [feed de usuário](https://docs.4casters.io/pt-BR/pages/streaming/user-feed.md) e do [feed de preços](https://docs.4casters.io/pt-BR/pages/streaming/price-feed.md); o campo é omitido nos demais tipos de ordem. A própria resposta de envio não inclui o indicador.

### `fillAndKill`

Executa imediatamente como taker contra o tamanho disponível ao seu preço ou melhor e cancela o restante. Um `fillAndKill` nunca fica no livro.

Um casamento **parcial** é um resultado correto: se você envia `bet: 1000` e só há $400 de liquidez casável, você casa por $400 e o restante de \$600 é cancelado: a resposta é um sucesso, não um erro. A ordem só é rejeitada (`rejected_order_type_rules`, `"fill and kill has no matches"`) quando não há liquidez casável alguma. Consulte os cenários de Fill And Kill nos [exemplos](#examples) abaixo.

### `fillOrKill`

Tudo ou nada. Seu `bet` **inteiro** deve casar imediatamente ao seu preço ou melhor; caso contrário, toda a ordem é rejeitada, incluindo os casamentos que ela teria feito pelo caminho, que são revertidos. Um `fillOrKill` nunca fica no livro e nunca deixa você parcialmente casado.

Use-o quando uma posição parcial for pior do que nenhuma posição, por exemplo quando a ordem é uma perna de uma cobertura que você só pode executar por completo.

As rejeições levam `errorType: rejected_order_type_rules` com uma de duas mensagens, que distinguem "não havia nada" de "não havia o suficiente":

* `"fill or kill has no matches"` — não há liquidez casável ao seu preço.
* `"fill or kill matched but not fully"` — parte da liquidez casou, mas não o seu tamanho completo. Esses casamentos foram revertidos.

> [!NOTE]
>
> Um resíduo de \*\*$10 ou menos** conta como completo: um `fillOrKill` de $1,000 que casa $992 tem sucesso, porque os $8 que não puderam casar estão abaixo do tamanho mínimo que poderia ficar no livro. Um resíduo maior que \$10 rejeita a ordem.

## Resposta

**data.createdSessions** `array`

Resultados por ordem, na mesma ordem posicional que o array `orders` de entrada. Cada entrada é um envio bem-sucedido ou um erro.

**Envio bem-sucedido**

**matched** `array`

Casamentos produzidos por esta ordem. Vazio quando a ordem não casou.

**MatchedFill**

**amount** `number`

Valor apostado da porção casada.

**odds** `integer`

Odds americanas do casamento.

**number** `number`

Spread ou total do casamento (`null` em moneylines).

**type** `string`

Tipo de mercado.

**side** `string`

Lado da ordem.

**market** `string`

Presente em `moneyline1x2`.

**orderID** `string`

Id da ordem da oferta casada do outro lado.

**txID** `string`

Id de transação do casamento.

**wagerRequestID** `string`

Id gerado pelo servidor que agrupa cada casamento ou oferta derivado desta ordem de entrada.

**userReference** `string`

**risk** `number`

**win** `number`

Valor a ganhar, líquido da comissão de taker.

**winWithoutCommission** `number`

Valor a ganhar antes da comissão.

**unmatched** `object`

Oferta em aberto criada a partir do restante não casado. Pode estar vazia (`{}`) quando a ordem casou por completo.

**UnmatchedOffer**

**orderID** `string`

Id da nova ordem em aberto. Use-o para cancelar.

**wagerRequestID** `string`

**offered** `number`

**odds** `integer`

**type** `string`

**side** `string`

**market** `string`

Presente em `moneyline1x2`.

**number** `number`

**userReference** `string`

**Erro por ordem**

**error** `string`

Descrição da falha em texto legível.

**errorType** `string`

`validation_error`, `rejected_liability`, `rejected_order_type_rules` ou `system_error`.

## Exemplos

### Cenário 1 — Ordens que casam sem liquidez restante

Três ordens que casam na hora com a liquidez disponível.

```json Requisição theme={null}
{
  "orders": [
    { "gameID": "688c0516fbc14da0c202d426", "type": "moneyline", "side": "5c12bc1ce0daba000f47ba8b", "odds": -175, "bet": 100, "orderType": "post" },
    { "gameID": "688c0516fbc14da0c202d426", "type": "spread",    "side": "5c12bc1ce0daba000f47ba8b", "odds": -110, "bet": 100, "orderType": "post", "number": 3.5 },
    { "gameID": "688c0516fbc14da0c202d426", "type": "total",     "side": "over",                     "odds": -104, "bet": 100, "orderType": "post", "number": 50 }
  ]
}
```

```json Resposta theme={null}
{
  "data": {
    "createdSessions": [
      {
        "matched": [
          {
            "amount": 50, "odds": -175, "type": "moneyline",
            "side": "5d48bd5198366d41ec7238da",
            "orderID": "68d42f82cfebf0b249a2c26e",
            "txID":    "68d42f83cfebf0b249a2c279",
            "wagerRequestID": "68d42f83cfebf0b249a2c278",
            "risk": 50.286, "win": 28.286, "winWithoutCommission": 28.571
          }
        ],
        "unmatched": {}
      },
      { "matched": [/* spread fill */], "unmatched": {} },
      { "matched": [/* total fill  */], "unmatched": {} }
    ]
  }
}
```

### Cenário 2 — Ordem limit com liquidez restante

Uma ordem limit de 300 que casa parcialmente e deixa o restante em aberto.

```json Resposta theme={null}
{
  "data": {
    "createdSessions": [
      {
        "matched": [
          {
            "amount": 185, "odds": -185, "type": "moneyline",
            "side": "5d48bd5198366d41ec7238da",
            "orderID": "68d43574cfebf0b249a2c28d",
            "txID":    "68d43574cfebf0b249a2c290",
            "wagerRequestID": "68d43574cfebf0b249a2c28f",
            "risk": 186, "win": 99, "winWithoutCommission": 100
          }
        ],
        "unmatched": {
          "orderID": "68d43575cfebf0b249a2c292",
          "wagerRequestID": "68d43574cfebf0b249a2c28f",
          "offered": 115, "odds": -185, "type": "moneyline",
          "side": "5d48bd5198366d41ec7238da", "number": null
        }
      }
    ]
  }
}
```

### Cenário 3 — Fill and Kill, casamento completo

```json Resposta theme={null}
{
  "data": {
    "createdSessions": [
      {
        "matched": [
          {
            "amount": 100, "odds": -186, "type": "moneyline",
            "side": "5d48bd5198366d41ec7238da",
            "orderID": "68d4368acfebf0b249a2c298",
            "txID":    "68d436bacfebf0b249a2c29b",
            "wagerRequestID": "68d436bacfebf0b249a2c29a",
            "userReference": "docs-fillandkill-match",
            "risk": 100.538, "win": 53.226, "winWithoutCommission": 53.763
          }
        ],
        "unmatched": {}
      }
    ]
  }
}
```

### Cenário 4 — Fill and Kill, sem casamento

Um `fillAndKill` sem casamento retorna um erro por ordem.

```json Resposta theme={null}
{
  "data": {
    "createdSessions": [
      {
        "error": "fill and kill has no matches",
        "errorType": "rejected_order_type_rules"
      }
    ]
  }
}
```

### Cenário 5 — Fill or Kill, liquidez insuficiente

`fillOrKill` é o equivalente de tudo ou nada de `fillAndKill`. Onde um `fillAndKill` de $1,000 contra $400 de liquidez casa $400 e cancela o restante, um `fillOrKill` rejeita toda a ordem e reverte esses $400: nunca deixa você parcialmente casado.

```json Requisição theme={null}
{
  "orders": [
    {
      "gameID": "688c0516fbc14da0c202d426",
      "type": "moneyline",
      "side": "5c12bc1ce0daba000f47ba8b",
      "odds": -110,
      "bet": 1000,
      "orderType": "fillOrKill",
      "userReference": "docs-fillorkill-partial"
    }
  ]
}
```

```json Resposta theme={null}
{
  "data": {
    "createdSessions": [
      {
        "error": "fill or kill matched but not fully",
        "errorType": "rejected_order_type_rules"
      }
    ]
  }
}
```

Sem liquidez casável alguma, a mesma ordem é rejeitada com `"fill or kill has no matches"` em vez disso.

### Cenário 6 — `postArb` frente a `post` quando o livro casaria

`post` rejeita uma ordem que casaria com liquidez em aberto (por exemplo, melhor oferta **+100** e você tenta enviar **+100**). `postArb` permite essa situação quando suas odds estão dentro de **1%** da ordem com a qual você casaria, de modo que o mesmo envio a **+100** pode ter sucesso como `postArb` e você evita as comissões de taker que pagaria em um cruzamento normal. Se o seu preço estiver longe demais da cotação em aberto (p. ex. melhor oferta **+200** mas você envia **+190**), `postArb` é rejeitada.

```json Requisição theme={null}
{
  "orders": [
    {
      "gameID": "688c0516fbc14da0c202d426",
      "type": "moneyline",
      "side": "5c12bc1ce0daba000f47ba8b",
      "odds": 100,
      "bet": 50,
      "orderType": "postArb",
      "userReference": "docs-postarb-same-line-as-offer"
    }
  ]
}
```

### Cenário 7 — `moneyline1x2` (futebol de três vias)

`moneyline1x2` é o mercado de futebol de três vias — mandante / visitante / empate — enviado como uma aposta yes/no sobre o resultado indicado por `market`. Abaixo, **yes sobre o empate** a +250.

```json Requisição theme={null}
{
  "orders": [
    {
      "gameID": "65f0c3...",
      "type": "moneyline1x2",
      "side": "yes",
      "market": "draw",
      "odds": 250,
      "bet": 50,
      "orderType": "post",
      "userReference": "docs-ml1x2-yes-draw"
    }
  ]
}
```

Para apostar que o **time mandante não vence**, envie `side: "no"` e defina `market` como o id do participante mandante.

## Atraso ao vivo

As ordens enviadas em um evento marcado como live seguem estas regras:

1. Se a ordem não casar com nenhuma liquidez existente, é enviada imediatamente.
2. Se a ordem casar com liquidez existente, incorre em um atraso antes da execução.
3. Ligas diferentes têm períodos de atraso ao vivo diferentes:

   * **NFL, NCAAF, NBA, WNBA, NCAAB, MLB, NHL**: 0.5 segundo.
   * **Futebol principal (Premier League, La Liga, Serie A, Bundesliga, Ligue 1 e as demais primeiras divisões europeias, Champions League, Europa League, MLS, Liga MX, Libertadores, Copa do Mundo e as demais competições principais), ATP, WTA, CFL**: 2 segundos.
   * **UFCMMA**: 3 segundos.
   * **EURO-CUP e o restante do futebol ao vivo (segundas divisões, Brasil, o resto da América do Sul, Ásia)**: 5 segundos.
   * **Padrão**: 10 segundos.

   Os mercados ao vivo de tempos, períodos e props de jogadores usam o atraso da liga principal. Esses valores são configurações operacionais e podem mudar sem aviso.
4. Após o atraso, a ordem tenta executar:
   * Se as odds melhoram, casa na hora.
   * Se as odds pioram, não casa.

## Limites de taxa

Cada ordem conta contra o orçamento da sua conta, compartilhado com o WebSocket. Um lote que não cabe é rejeitado por inteiro com `429`. Aplicado a partir de 2026-11-02. Consulte [Limitação de taxa](https://docs.4casters.io/pt-BR/pages/rate-limiting.md).

## Erros por ordem

<Snippet file="pt-BR/types/order-error.mdx" />

Exemplo com vários envios, alguns com erro:

```json Resposta theme={null}
{
  "data": {
    "createdSessions": [
      { "matched": [/* successful fill */], "unmatched": {} },
      { "error": "game not found: invalid gameID", "errorType": "validation_error" },
      { "error": "Insufficient balance.",          "errorType": "rejected_liability" },
      { "error": "post order cannot have matches", "errorType": "rejected_order_type_rules" },
      { "error": "failed to interact with database","errorType": "system_error" }
    ]
  }
}
```


## OpenAPI

````yaml POST /session/v3/place
openapi: 3.1.0
info:
  title: 4casters REST API
  version: 1.0.0
  description: >-
    Public REST API for the 4casters peer-to-peer betting exchange. Use this API
    to manage your account, query the orderbook and games, and place / edit /
    cancel orders.


    All responses (unless noted otherwise) are JSON envelopes of the form `{
    "data": ... }`.
  contact:
    name: 4casters
    url: https://4casters.io
servers:
  - url: https://api.4casters.io
    description: Production
security:
  - bearerAuth: []
tags:
  - name: Authentication
    description: Login and account session management
  - name: User
    description: Read account info, bets, and orders
  - name: Orders
    description: Place, edit, look up, and cancel orders
  - name: Markets
    description: Browse leagues, games, participants, and orderbooks
  - name: Affiliate
    description: Affiliate / referral commission
paths:
  /session/v3/place:
    post:
      tags:
        - Orders
      summary: Place orders
      description: >-
        Submit one or more orders. Per-order results are returned in
        `data.createdSessions`, **positionally** with the input `orders` array.
        Each entry is either a successful `{ matched, unmatched }` result or an
        `{ error, errorType }` failure.


        See the dedicated [Place order](/pages/rest/orders/place-order) page for
        examples and the full set of order-type rules (`limit`, `post`,
        `postArb`, `fillAndKill`, `fillOrKill`).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PlaceOrderRequest'
      responses:
        '200':
          description: Per-order results (positional with input).
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      createdSessions:
                        type: array
                        items:
                          $ref: '#/components/schemas/PlaceOrderResult'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '503':
          description: Orders service unreachable
components:
  schemas:
    PlaceOrderRequest:
      type: object
      required:
        - orders
      properties:
        orders:
          type: array
          items:
            $ref: '#/components/schemas/PlaceOrderInput'
    PlaceOrderResult:
      oneOf:
        - $ref: '#/components/schemas/PlaceOrderSuccess'
        - $ref: '#/components/schemas/OrderError'
      description: >-
        Either a successful place result or a per-order error. Returned
        positionally with the request `orders` array.
    PlaceOrderInput:
      type: object
      required:
        - gameID
        - type
        - side
        - odds
        - bet
      properties:
        gameID:
          type: string
          description: 4casters game id.
        type:
          $ref: '#/components/schemas/MarketType'
        side:
          $ref: '#/components/schemas/MarketSide'
        market:
          type: string
          description: >-
            **`moneyline1x2` only.** Either `"draw"` or a participant id — names
            the outcome you're betting yes/no on.
        odds:
          type: integer
          description: Order odds in **American** format (e.g. `-110`, `+150`).
        bet:
          type: number
          description: Amount to risk on the bet.
        number:
          type: number
          description: >-
            Spread or total number. Required for `spread` and `total`. Not used
            for `moneyline` or `moneyline1x2`.
        orderType:
          $ref: '#/components/schemas/OrderType'
        expirationMinutes:
          type: integer
          description: Auto-cancel after N minutes. Omit to keep until game start.
        userReference:
          type: string
          description: >-
            Client-defined identifier preserved on every fill / offer derived
            from this order.
    PlaceOrderSuccess:
      type: object
      properties:
        matched:
          type: array
          items:
            $ref: '#/components/schemas/MatchedFill'
        unmatched:
          $ref: '#/components/schemas/UnmatchedOffer'
    OrderError:
      type: object
      properties:
        error:
          type: string
          description: Human-readable, non-stable description of the failure.
        errorType:
          $ref: '#/components/schemas/ErrorType'
        error_type:
          type: string
          deprecated: true
          description: >-
            Legacy alias of `errorType` (still emitted by the WebSocket placeV3
            path).
    MarketType:
      type: string
      enum:
        - moneyline
        - spread
        - total
        - moneyline1x2
      description: >-
        Market type. `moneyline1x2` is **soccer-only** (three-way money line:
        home / away / draw).
    MarketSide:
      type: string
      description: |-
        Order side. Meaning depends on `type`:

        - `moneyline`, `spread` — the participant id you are backing.
        - `total` — `"over"` or `"under"`.
        - `moneyline1x2` — `"yes"` or `"no"` on the outcome named by `market`.
    OrderType:
      type: string
      enum:
        - limit
        - post
        - postArb
        - fillAndKill
        - fillOrKill
      description: >-
        Order placement strategy.


        - `limit` — default. Match against any liquidity at your price or better
        as a taker, rest the remainder as a maker.

        - `post`  — guarantee maker. Reject if the order would match resting
        liquidity.

        - `postArb` — like `post`, but allowed to match if the matched odds are
        within 1% of yours, avoiding taker fees.

        - `fillAndKill` — guarantee taker. Match whatever size is available at
        your price or better and cancel the remainder; never rests. A partial
        fill is a success; rejected only when there is no matchable liquidity at
        all.

        - `fillOrKill` — all-or-nothing taker. Match the entire `bet`
        immediately or the whole order is rejected and any partial fills are
        rolled back; never rests.
    MatchedFill:
      type: object
      description: A portion of an order that matched against existing liquidity.
      properties:
        amount:
          type: number
          description: Stake on the matched portion.
        odds:
          type: integer
          description: American odds of the fill.
        number:
          type: number
          nullable: true
          description: Spread or total of the fill (`null` for moneylines).
        type:
          $ref: '#/components/schemas/MarketType'
        side:
          $ref: '#/components/schemas/MarketSide'
        market:
          type: string
          description: Present for `moneyline1x2`.
        orderID:
          type: string
          description: Order id of the matched offer on the other side.
        txID:
          type: string
          description: Transaction id of the fill.
        wagerRequestID:
          type: string
          description: >-
            Server-generated id grouping every fill / offer derived from the
            input order.
        userReference:
          type: string
        risk:
          type: number
        win:
          type: number
          description: Win amount, net of taker commission.
        winWithoutCommission:
          type: number
          description: Win amount before commission.
    UnmatchedOffer:
      type: object
      description: >-
        Resting offer created from the unfilled remainder of a place request.
        May be empty (`{}`) when the order matched fully.
      properties:
        orderID:
          type: string
          description: Id of the new resting order.
        wagerRequestID:
          type: string
        offered:
          type: number
        odds:
          type: integer
        type:
          $ref: '#/components/schemas/MarketType'
        side:
          $ref: '#/components/schemas/MarketSide'
        market:
          type: string
          description: Present for `moneyline1x2`.
        number:
          type: number
          nullable: true
        userReference:
          type: string
    ErrorType:
      type: string
      enum:
        - validation_error
        - rejected_liability
        - rejected_order_type_rules
        - system_error
      description: >-
        Programmatic per-order error class:


        - `validation_error` — payload or state failed validation (missing
        fields, bad odds/number, invalid side, inactive game).

        - `rejected_liability` — user/account/liability constraints prevented
        posting or execution.

        - `rejected_order_type_rules` — order-type rules forbade execution (e.g.
        `fillAndKill` had no executable liquidity, `fillOrKill` could not be
        filled in full, `post` would match, or `postArb` is more than 1% away
        from the resting price).

        - `system_error` — transient/internal error; retry may succeed.
  responses:
    Unauthorized:
      description: Missing or invalid auth token
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: >-
        Pass your auth token in the `Authorization` header. The `Bearer` prefix
        is optional; the server also accepts a signed `auth` cookie or a `token`
        field in the request body.

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.