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

# Place an order

> Places an order on one instrument of one account: a market or limit order,
optionally conditional or trailing, with an optional take-profit/stop-loss.

- `order` sets exactly one of `market` and `limit`, and at most one of
  `stop` (conditional order) and `trailingStop` (trailing-stop order).
- `order.takeProfit`/`order.stopLoss` attach a take-profit/stop-loss to the
  order; their `limitPrice` makes them limit orders on trigger. Support
  differs per connector: see `takeProfit` and the connector's
  capabilities.
- `reduceOnly` applies to derivatives, `isLeverage` to spot.
- `label` tags the order; a bulk cancel can be narrowed to it.
- Check prices and quantities against the order-data stream before
  sending.

**Safe to retry** with the same `Idempotency-Key`: a repeated request never
creates a second order.

`202` means the order was accepted for asynchronous processing; it can
still fail or be rejected by the exchange. Follow it on the events stream.




## OpenAPI

````yaml /platform-api/specs/trading-openapi.yaml post /api/v1/trading/order/create
openapi: 3.0.3
info:
  title: TakeProfit API (Trading, REST)
  version: 0.16.2
  contact:
    email: support@charting.com
  description: >
    Trade on the exchange accounts you connected to TakeProfit, over REST.

    Live data is served over WebSocket by the same service and described by

    the AsyncAPI document at

    `https://public-api.charting.com/api/v1/trading/asyncapi.yaml`: the

    events stream (orders, fills, positions, balances - the way to see the

    outcome of your requests) and the order-data stream (instrument rules,

    account settings and live buying power).

    Securities and the exchange catalog are served by the marketdata part of

    the same API (`/api/v1/marketdata/...`) with the same API key. Guides

    live in the Platform API docs:

    [Authentication](https://takeprofit.com/docs/platform-api/authentication)

    (getting an API key) and

    [Credits and limits](https://takeprofit.com/docs/platform-api/limits).


    ## Requests


    - Base URL: `https://public-api.charting.com`.

    - Sign every request with your API key (see "Signing requests" below);
      exactly one value of each signature header is accepted. A key without
      the scope `trading:access:write` is answered with 403.
    - Request bodies are JSON (`Content-Type: application/json`). Unknown
      fields are rejected with 400.
    - Requests name the account and, where needed, the instrument:
      - `accountId` - the id of the exchange account, as listed by
        `/api/v1/trading/account/list` (not its title);
      - `connectorCode` - the exchange connector the account trades through,
        such as `binance_spot` or `binance_usdm`, as listed in `connectorCodes`
        by `/api/v1/trading/account/list`. Required in every trading
        command, also when the account has only one connector. What each
        connector supports is described by
        `/api/v1/trading/connector/capabilities`;
      - `instrument` - `{"exchange": ..., "symbol": ...}`, the security as
        returned by `/api/v1/marketdata/exchanges/{exchange}/securities`.
        Internal ids and GUIDs are not accepted.
    - Payloads are nested the way the trading backend models them: an
      `order` has one of `market` and `limit`, at most one of `stop` and
      `trailingStop`, and `takeProfit`/`stopLoss` objects.
    - `label` tags the orders of one strategy or script. It is optional
      when placing an order; a bulk cancel can be narrowed to one label, so
      it does not cancel orders placed by hand or by another script.
    - Prices, quantities and rates are decimal strings (`"0.001"`), never
      JSON numbers, so no precision is lost. Check them against the
      order-data stream (`/api/v1/trading/order/data/stream`) before
      sending: a price off the price step or a quantity below the minimum
      is rejected by the exchange.

    ## Signing requests


    Create an API key in TakeProfit

    ([Authentication](https://takeprofit.com/docs/platform-api/authentication))

    with the scope `trading:access:write` and an Ed25519 public key: TakeProfit
    keeps the public key, you keep the

    private key and sign every request with it. Send four headers:


    - `X-API-KEY` - the API key (`tpk_...`);

    - `X-API-TIMESTAMP` - the time of the request, Unix milliseconds;

    - `X-API-RECV-WINDOW` - optional, how long after `X-API-TIMESTAMP` the
      request is still accepted, in milliseconds: 1 to 60000, default 5000;
    - `X-API-SIGNATURE` - the Ed25519 signature, hex, of the bytes
      `timestamp + apiKey + recvWindow + payload`: the three header values
      exactly as sent (an omitted `X-API-RECV-WINDOW` contributes nothing),
      then the payload. The payload of a GET is its raw query string as sent,
      without `?` (empty when there is none); of a POST, its raw body as sent.

    ```python

    import json, time


    import requests

    from cryptography.hazmat.primitives.asymmetric.ed25519 import
    Ed25519PrivateKey


    def signed_headers(api_key: str, private_key: Ed25519PrivateKey, payload:
    bytes) -> dict:
        timestamp, recv_window = str(int(time.time() * 1000)), "5000"
        message = timestamp.encode() + api_key.encode() + recv_window.encode() + payload
        return {
            "X-API-KEY": api_key,
            "X-API-TIMESTAMP": timestamp,
            "X-API-RECV-WINDOW": recv_window,
            "X-API-SIGNATURE": private_key.sign(message).hex(),
        }

    body = json.dumps({"accountId": "...", "connectorCode": "bybit", "orderId":
    "..."}).encode()

    requests.post(url, data=body, headers={"Content-Type": "application/json",
                                           **signed_headers(api_key, private_key, body)})
    ```


    A request is accepted while its timestamp is at most `X-API-RECV-WINDOW`

    behind the server time and at most 1 second ahead of it; keep the clock

    in sync. There is no nonce: within the window, a captured request can be

    sent again. A repeated `/order/create` with the same `Idempotency-Key`

    places no second order; `/order/amend` and `/position/add-tpsl` are not

    idempotent. The method and the path are not signed, as with Bybit: a

    signature fits any request with the same timestamp, key and payload.


    Missing or malformed headers, a timestamp outside the window, an

    unknown, revoked or expired key, a key created without a public key and

    a wrong signature are all answered with 401 `unauthenticated`. A key

    without the scope `trading:access:write` is answered with 403. The message
    names the header or the clock

    problem, but never says whether the key or the signature was wrong.


    ## Requests are asynchronous


    Orders and positions are processed asynchronously. A `202 Accepted`

    answer means TakeProfit validated the request and accepted it for

    processing; it has not necessarily reached the exchange yet. It does not

    mean the order was placed, filled or cancelled: processing can still

    fail, and the exchange can still reject the request (insufficient

    balance, price outside the allowed band, and so on). Follow the outcome

    on the events stream (`/api/v1/trading/events/stream`): its `order`,

    `execution` and `position` frames show what happened, and

    `commandError` and `notification` frames say why a request failed.


    ## Retrying safely


    - Placing an order is safe to retry: send the same `Idempotency-Key`
      header and the same body, and a repeated request never creates a
      second order.
    - Amending an order is NOT safe to retry: a retry after a timeout may
      apply the change twice or fail. Check the order on the events stream
      first.
    - Adding take-profit/stop-loss to a position is NOT safe to retry: the
      exchange does not deduplicate it, and a retry after a timeout can
      create a duplicate leg.
    - Cancelling orders and closing positions are safe to repeat: there is
      nothing left to cancel or close the second time.

    ## Credits and limits


    Requests are metered in credits against the quota window of 100000

    credits per 60 seconds, shared by all API keys of the account and with

    the marketdata and indicators parts of the API. Windows are fixed:

    unused credits do not carry over, and there are no daily or monthly

    limits. See

    [Credits and limits](https://takeprofit.com/docs/platform-api/limits).

    Every authenticated response carries the window state:


    - `X-RateLimit-Limit` - credits per window;

    - `X-RateLimit-Remaining` - credits still available after this request;

    - `X-RateLimit-Reset` - epoch second the window resets at.


    Every request costs 1000 credits: the account list, the connector

    capabilities and every order and position request alike. Only a

    request that succeeds is billed; a rejected one is free. A request the

    remaining credits cannot cover is rejected with 429 and `Retry-After`.

    An account has at most 4 requests in flight at once, whichever of its

    API keys sends them; a fifth is rejected with 429.


    ## Errors


    Every error response is `{"error": {"code": "<stable code>", "message":

    "<human-readable text>"}}`. The statuses listed on each operation (400,

    401, 403, 404, 429) are the outcomes a client handles explicitly. In

    addition, any operation can answer 502 (`bad_gateway`), 503

    (`unavailable`) or 504 (`deadline_exceeded`) while the gateway or an

    upstream is unavailable or slow; these are transient - retry with

    exponential backoff and honour `Retry-After` when present. Retry an

    order placement only with the same `Idempotency-Key`.
servers:
  - url: https://public-api.charting.com
    description: Production
security: []
tags:
  - name: Account
    description: The exchange accounts connected to TakeProfit.
  - name: Orders
    description: Placing orders and cancelling them in bulk.
  - name: Positions
    description: Closing positions and protecting them with take-profit/stop-loss.
  - name: Connectors
    description: What each exchange connector supports.
paths:
  /api/v1/trading/order/create:
    post:
      tags:
        - Orders
      summary: Place an order
      description: >
        Places an order on one instrument of one account: a market or limit
        order,

        optionally conditional or trailing, with an optional
        take-profit/stop-loss.


        - `order` sets exactly one of `market` and `limit`, and at most one of
          `stop` (conditional order) and `trailingStop` (trailing-stop order).
        - `order.takeProfit`/`order.stopLoss` attach a take-profit/stop-loss to
        the
          order; their `limitPrice` makes them limit orders on trigger. Support
          differs per connector: see `takeProfit` and the connector's
          capabilities.
        - `reduceOnly` applies to derivatives, `isLeverage` to spot.

        - `label` tags the order; a bulk cancel can be narrowed to it.

        - Check prices and quantities against the order-data stream before
          sending.

        **Safe to retry** with the same `Idempotency-Key`: a repeated request
        never

        creates a second order.


        `202` means the order was accepted for asynchronous processing; it can

        still fail or be rejected by the exchange. Follow it on the events
        stream.
      operationId: placeOrder
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PlaceOrderRequest'
      responses:
        '202':
          description: The order was accepted for asynchronous processing.
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/RateLimitReset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PlaceOrderResponse'
              example:
                orderId: 1f2e3d4c-5b6a-4798-8a9b-0c1d2e3f4a5b
                requestId: 9a8b7c6d-5e4f-4321-8765-0fedcba98765
        '400':
          $ref: '#/components/responses/InvalidRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimited'
      security:
        - ApiKeyAuth: []
          Timestamp: []
          Signature: []
components:
  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      description: |
        Your unique key for this order placement, for example a UUID. It only
        protects against duplicates; it is not stored on the order and does
        not appear in order events.

        - A repeated request with the same key within 24 hours never creates
          a second order: it is answered with the `orderId` of the first one.
          Retry with the same key after a timeout or a 5xx.
        - Send the same body with the same key. The body of a repeated
          request is not compared: a reused key returns the first order even
          if the body differs.
        - A key already used with another account is rejected with 400.
        - After 24 hours the key is forgotten, and a request with it places
          a new order.
      schema:
        type: string
        minLength: 1
      example: 7f3c1a2e-5b8d-4e61-9a0f-2c4d6e8b1a37
  schemas:
    PlaceOrderRequest:
      type: object
      required:
        - accountId
        - connectorCode
        - instrument
        - order
      properties:
        accountId:
          $ref: '#/components/schemas/AccountId'
        connectorCode:
          $ref: '#/components/schemas/ConnectorCode'
        instrument:
          $ref: '#/components/schemas/Instrument'
        label:
          $ref: '#/components/schemas/Label'
        order:
          $ref: '#/components/schemas/Order'
      example:
        accountId: 4b8e2f6a-91c3-4d57-a0e8-3f1c7b9d2e45
        connectorCode: binance_usdm
        instrument:
          exchange: CXBNCE
          symbol: BTC/USDT
        label: grid-btc-1
        order:
          side: buy
          quantity: '0.001'
          limit:
            price: '60000'
            timeInForce: gtc
          takeProfit:
            triggerPrice: '65000'
          stopLoss:
            triggerPrice: '58000'
    PlaceOrderResponse:
      type: object
      required:
        - orderId
        - requestId
      properties:
        orderId:
          type: string
          description: TakeProfit id of the order.
        requestId:
          type: string
          description: Id of this request, for support.
    AccountId:
      type: string
      minLength: 1
      description: >-
        Id of the exchange account (a UUID), as listed in `accountId` by
        /api/v1/trading/account/list. Not the account's title.
      example: 4b8e2f6a-91c3-4d57-a0e8-3f1c7b9d2e45
    ConnectorCode:
      type: string
      description: |
        Exchange connector the account trades the instrument through, such as
        `binance_spot` or `binance_usdm`, as listed in `connectorCodes` by
        /api/v1/trading/account/list. Required in every trading command.
      example: binance_usdm
    Instrument:
      type: object
      required:
        - exchange
        - symbol
      description: >-
        A security as the marketdata part of the API names it. Internal ids and
        GUIDs are not accepted.
      properties:
        exchange:
          $ref: '#/components/schemas/ExchangeCode'
        symbol:
          $ref: '#/components/schemas/SecuritySymbol'
    Label:
      type: string
      minLength: 1
      description: |
        Your tag for the orders of one strategy or script. Cancelling orders
        in bulk can be narrowed to one label.
      example: grid-btc-1
    Order:
      type: object
      required:
        - side
        - quantity
      description: |
        An order: set exactly one of `market` and `limit`, and at most one of
        `stop` and `trailingStop`.
      properties:
        side:
          $ref: '#/components/schemas/Side'
        quantity:
          allOf:
            - $ref: '#/components/schemas/PositiveDecimal'
          description: >-
            Quantity, in the unit given by `instrumentInfo.quantityUnit` of the
            order-data stream.
        market:
          $ref: '#/components/schemas/MarketOrder'
        limit:
          $ref: '#/components/schemas/LimitOrder'
        stop:
          $ref: '#/components/schemas/Stop'
        trailingStop:
          $ref: '#/components/schemas/TrailingStop'
        takeProfit:
          allOf:
            - $ref: '#/components/schemas/TpSl'
          description: |
            Take-profit attached to the order, sent to the exchange in the same
            request as the order, so it is placed with it or not at all. With
            `stopLoss` the two form one group: when one triggers, the other is
            cancelled. How a connector carries it differs, and its
            capabilities say whether it accepts it (`tpSl` of the order type):

            - Bybit: attached to the order; on derivatives, once the order
              fills, it becomes a separate take-profit/stop-loss order on the
              position, linked by `parentOrderId` and `tpSlLeg.pairId`.
            - Binance spot: an order list (OTO with one of them, OTOCO with
              both) of the order and pending legs that wait for it to fill.
              Requires `limit`, and no `stop`, `trailingStop` or
              `reduceOnly`. Cancelling any leg cancels the whole list.
            - Binance USD-M: not accepted. Place the order, then protect the
              position with /api/v1/trading/position/add-tpsl.
            - Exness: price levels set on the order and its position, not
              separate orders.
        stopLoss:
          allOf:
            - $ref: '#/components/schemas/TpSl'
          description: Stop-loss attached to the order; see `takeProfit`.
        reduceOnly:
          type: boolean
          description: >-
            Derivatives only. The order may only reduce the position, never open
            or increase it.
        isLeverage:
          type: boolean
          description: >-
            Spot only. Trade on margin (borrowing) where the account has spot
            margin enabled.
        positionMode:
          allOf:
            - $ref: '#/components/schemas/PositionMode'
          description: >-
            The account's position mode as sent in
            `accountSettings.positionMode` of the order-data stream.
    ErrorResponse:
      type: object
      required:
        - error
      properties:
        error:
          type: object
          required:
            - code
            - message
          properties:
            code:
              type: string
              description: Stable error code.
              enum:
                - invalid_argument
                - unauthenticated
                - permission_denied
                - not_found
                - method_not_allowed
                - rate_limited
                - canceled
                - bad_gateway
                - unavailable
                - deadline_exceeded
            message:
              type: string
    ExchangeCode:
      type: string
      description: TakeProfit exchange code as returned by /api/v1/marketdata/exchanges.
      example: CXBNCE
    SecuritySymbol:
      type: string
      description: >-
        TakeProfit security symbol as returned by
        /api/v1/marketdata/exchanges/{exchange}/securities.
      example: BTC/USDT
    Side:
      type: string
      enum:
        - buy
        - sell
    PositiveDecimal:
      type: string
      pattern: ^(0*[1-9][0-9]*(\.[0-9]+)?|0+\.[0-9]*[1-9][0-9]*)$
      description: Positive decimal number as a string; zero is rejected.
      example: '0.001'
    MarketOrder:
      type: object
      description: The order executes at the market price.
      properties:
        marketUnit:
          type: string
          enum:
            - base
            - quote
          description: >
            Spot only: whether `quantity` is in the base asset (BTC of BTC/USDT)
            or

            the quote asset (USDT). Omitted means the exchange's default.
        slippageTolerance:
          $ref: '#/components/schemas/SlippageTolerance'
    LimitOrder:
      type: object
      required:
        - price
      description: The order rests on the book at `price` or better.
      properties:
        price:
          $ref: '#/components/schemas/PositiveDecimal'
        timeInForce:
          type: string
          enum:
            - gtc
            - ioc
            - fok
          description: Good till cancelled, immediate or cancel, fill or kill.
    Stop:
      type: object
      required:
        - triggerPrice
        - triggerDirection
      description: The order waits off the book until the price reaches `triggerPrice`.
      properties:
        triggerPrice:
          $ref: '#/components/schemas/PositiveDecimal'
        triggerDirection:
          $ref: '#/components/schemas/TriggerDirection'
        triggerBy:
          $ref: '#/components/schemas/TriggerBy'
    TrailingStop:
      type: object
      required:
        - distance
      description: |
        Makes the order itself a trailing-stop order: it triggers once the
        price retraces by `distance` from the best price reached since
        activation. Which distance kinds a connector accepts is in its
        capabilities (`trailingStop`); percent bounds are in
        `instrumentInfo.trailingStop` of the order-data stream.
      properties:
        distance:
          type: object
          description: Set exactly one of `price` and `percent`.
          properties:
            price:
              allOf:
                - $ref: '#/components/schemas/PositiveDecimal'
              description: An absolute price distance.
            percent:
              allOf:
                - $ref: '#/components/schemas/PositiveDecimal'
              description: Percent of the best price; "1.5" means 1.5%.
        activation:
          type: object
          required:
            - price
          description: >-
            The stop starts trailing once the price reaches `price`. Omitted
            means it trails from the next trade.
          properties:
            price:
              $ref: '#/components/schemas/PositiveDecimal'
            direction:
              allOf:
                - $ref: '#/components/schemas/TriggerDirection'
              description: |
                The side from which the price reaches `price`. Required on
                Binance spot; on Binance USD-M it follows from the order side,
                so leave it unset.
        triggerBy:
          $ref: '#/components/schemas/TriggerBy'
    TpSl:
      type: object
      required:
        - triggerPrice
      description: A take-profit or stop-loss.
      properties:
        triggerPrice:
          $ref: '#/components/schemas/PositiveDecimal'
        limitPrice:
          allOf:
            - $ref: '#/components/schemas/PositiveDecimal'
          description: >-
            Price of the limit order placed on trigger. Omitted means a market
            order.
        triggerBy:
          $ref: '#/components/schemas/TriggerBy'
    PositionMode:
      type: string
      enum:
        - oneWay
        - hedge
    SlippageTolerance:
      type: object
      description: >
        How far a market order may fill from the best opposite quote at

        placement (best ask for a buy, best bid for a sell); the rest of the

        order is cancelled. Set exactly one of `priceSteps` and `percent`.

        Which ones a connector accepts is in its capabilities; their bounds

        are in `instrumentInfo.slippage` of the order-data stream. A value
        outside

        the bounds is sent as the nearest bound.
      properties:
        priceSteps:
          allOf:
            - $ref: '#/components/schemas/PositiveDecimal'
          description: A number of price steps.
        percent:
          allOf:
            - $ref: '#/components/schemas/PositiveDecimal'
          description: Percent of the quote; "0.5" means 0.5%.
    TriggerDirection:
      type: string
      enum:
        - risesTo
        - fallsTo
      description: >-
        Whether the trigger fires when the price rises to or falls to the
        trigger price.
    TriggerBy:
      type: string
      enum:
        - lastPrice
        - markPrice
        - indexPrice
      description: Price the trigger watches. Omitted means the exchange's default.
  headers:
    RateLimitLimit:
      description: Credits allowed per quota window.
      schema:
        type: integer
    RateLimitRemaining:
      description: Credits still available in the current quota window after this request.
      schema:
        type: integer
    RateLimitReset:
      description: Epoch second at which the current quota window resets.
      schema:
        type: integer
        format: int64
    RetryAfter:
      description: Seconds until the request can be retried.
      schema:
        type: integer
  responses:
    InvalidRequest:
      description: Invalid request body or parameter (`invalid_argument`).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              code: invalid_argument
              message: field "price" is required for a limit order
    Unauthorized:
      description: |
        Missing or malformed signature headers, a timestamp outside the
        receive window, an unknown, revoked or expired key, or a wrong
        signature.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              code: unauthenticated
              message: invalid API key or signature
    Forbidden:
      description: Permission denied (the key lacks the scope `trading:access:write`).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              code: permission_denied
              message: permission denied
    NotFound:
      description: >-
        The account, the connector or the instrument is not available to this
        key.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              code: not_found
              message: account not found
    RateLimited:
      description: >-
        The remaining credits of the quota window cannot cover this request, or
        the account already has the maximum of requests in flight.
      headers:
        X-RateLimit-Limit:
          $ref: '#/components/headers/RateLimitLimit'
        X-RateLimit-Remaining:
          $ref: '#/components/headers/RateLimitRemaining'
        X-RateLimit-Reset:
          $ref: '#/components/headers/RateLimitReset'
        Retry-After:
          $ref: '#/components/headers/RetryAfter'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            error:
              code: rate_limited
              message: rate limit exceeded
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-KEY
      description: Your API key; see "Signing requests".
    Timestamp:
      type: apiKey
      in: header
      name: X-API-TIMESTAMP
      description: Time of the request in Unix milliseconds; see "Signing requests".
    Signature:
      type: apiKey
      in: header
      name: X-API-SIGNATURE
      description: |
        Hex Ed25519 signature of timestamp + API key + receive window +
        payload; see "Signing requests". `X-API-RECV-WINDOW` is optional.

````

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