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

# Add take-profit/stop-loss to a position

> Adds a take-profit, a stop-loss, or both to one open derivatives position,
protecting `size` of it.

- Name the position in `position`: by `positionId`, or by `instrument` with
  `positionSide` in hedge mode.
- Set at least one of `takeProfit` and `stopLoss`. When both are set they
  form one pair, identified by the returned `pairId`: when one triggers,
  the exchange cancels the other.
- Where the connector's `addPositionTpSl` capabilities say
  `wholePositionOnly`, `size` must equal the position size; where they say
  `limitPriceUnsupported`, `limitPrice` is rejected.

**Not safe to retry.** The exchange does not deduplicate this request: a
retry after a timeout can create a duplicate take-profit/stop-loss.

`202` means the request was accepted for asynchronous processing. The
outcome arrives on the events stream as a `notification` frame
(`addPositionTpSl`), and the created orders carry `tpSlLeg.pairId`.




## OpenAPI

````yaml /platform-api/specs/trading-openapi.yaml post /api/v1/trading/position/add-tpsl
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/position/add-tpsl:
    post:
      tags:
        - Positions
      summary: Add take-profit/stop-loss to a position
      description: >
        Adds a take-profit, a stop-loss, or both to one open derivatives
        position,

        protecting `size` of it.


        - Name the position in `position`: by `positionId`, or by `instrument`
        with
          `positionSide` in hedge mode.
        - Set at least one of `takeProfit` and `stopLoss`. When both are set
        they
          form one pair, identified by the returned `pairId`: when one triggers,
          the exchange cancels the other.
        - Where the connector's `addPositionTpSl` capabilities say
          `wholePositionOnly`, `size` must equal the position size; where they say
          `limitPriceUnsupported`, `limitPrice` is rejected.

        **Not safe to retry.** The exchange does not deduplicate this request: a

        retry after a timeout can create a duplicate take-profit/stop-loss.


        `202` means the request was accepted for asynchronous processing. The

        outcome arrives on the events stream as a `notification` frame

        (`addPositionTpSl`), and the created orders carry `tpSlLeg.pairId`.
      operationId: addPositionTpSl
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AddPositionTpSlRequest'
      responses:
        '202':
          description: The request 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/AddPositionTpSlResponse'
        '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:
  schemas:
    AddPositionTpSlRequest:
      type: object
      required:
        - accountId
        - connectorCode
        - position
        - size
      description: Set at least one of `takeProfit` and `stopLoss`.
      properties:
        accountId:
          $ref: '#/components/schemas/AccountId'
        connectorCode:
          $ref: '#/components/schemas/ConnectorCode'
        position:
          $ref: '#/components/schemas/PositionRef'
        size:
          allOf:
            - $ref: '#/components/schemas/PositiveDecimal'
          description: >-
            Part of the position the take-profit/stop-loss protects, in the
            position's quantity unit.
        takeProfit:
          $ref: '#/components/schemas/TpSl'
        stopLoss:
          $ref: '#/components/schemas/TpSl'
      example:
        accountId: 4b8e2f6a-91c3-4d57-a0e8-3f1c7b9d2e45
        connectorCode: binance_usdm
        position:
          instrument:
            exchange: CXBNCE
            symbol: BTC/USDT
        size: '0.001'
        takeProfit:
          triggerPrice: '65000'
        stopLoss:
          triggerPrice: '58000'
    AddPositionTpSlResponse:
      type: object
      required:
        - requestId
        - pairId
      properties:
        requestId:
          type: string
          description: Id of this request, for support.
        pairId:
          type: string
          description: Id of the take-profit/stop-loss pair; the created orders carry it.
    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
    PositionRef:
      type: object
      description: |
        The position: either `positionId`, or `instrument` (with
        `positionSide` in hedge mode). Not both.
      properties:
        positionId:
          type: string
          description: Id of the position, as sent in `positionId` on the events stream.
        instrument:
          $ref: '#/components/schemas/Instrument'
        positionSide:
          $ref: '#/components/schemas/PositionSide'
    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'
    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'
    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
    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'
    PositionSide:
      type: string
      enum:
        - long
        - short
      description: |
        Side of the position. Required in hedge mode, where an instrument can
        hold a long and a short position at once; must be omitted in one-way
        mode.
    TriggerBy:
      type: string
      enum:
        - lastPrice
        - markPrice
        - indexPrice
      description: Price the trigger watches. Omitted means the exchange's default.
    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
  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.