> For the complete documentation index, see [llms.txt](https://docs.openalgo.in/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.openalgo.in/api-documentation/v1/orders-api/placegttorder.md).

# PlaceGttOrder

Place a new GTT (Good Till Triggered) order: a price-trigger that sits with the broker until LTP crosses your level, then automatically places the underlying order. Useful for setting buy/sell levels without watching the screen.

## SINGLE vs OCO: Pick One

| Type                        | Use when…                                                                                                                                                                | Triggers | Orders fired                                       |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------- | -------------------------------------------------- |
| **SINGLE**                  | You want **one** entry or exit at a level. Example: *"Buy IDEA if it dips to 9.55"* or *"Sell RELIANCE if it crosses 1450"*.                                             | 1        | 1                                                  |
| **OCO** (One-Cancels-Other) | You're already in a position and want **both a stoploss and a target**, whichever hits first. Example: *"I hold INFY @ 1550. Stop me out at 1480, take profit at 1620."* | 2        | Broker-dependent; native OCO cancels the other leg |

> **In SINGLE there is no second leg and no automatic cancel**: once your one trigger fires and the order is placed, the GTT is finished.

## How to Choose `triggerprice_sl` vs `triggerprice_tg` (SINGLE only)

For SINGLE, send the intended trigger in one of these fields and set the other to `0`. If both are positive, the current schema resolves `triggerprice_sl` and clears the other; it does not create two SINGLE legs. Pick based on **where your trigger sits relative to LTP**. This also matches the leg name the broker assigns internally:

| Field             | Trigger sits…         | Typical intent                                |
| ----------------- | --------------------- | --------------------------------------------- |
| `triggerprice_sl` | **below** current LTP | SELL stop-loss · BUY-on-dip · BUY-the-fall    |
| `triggerprice_tg` | **above** current LTP | BUY breakout · SELL-at-target · SELL-the-rise |

For OCO, you always send **both**: `triggerprice_sl` (the lower trigger, your stoploss) **and** `triggerprice_tg` (the higher trigger, your target).

> **Note on naming.** In **SINGLE**, `triggerprice_sl` / `triggerprice_tg` are just *the trigger price*, the generic "price at which the order is triggered". The `_sl` / `_tg` suffix is only a directional hint (sits below / above LTP); SINGLE has no stoploss leg. In **OCO**, the suffix becomes a real role: `triggerprice_sl` is the **stoploss-leg trigger** and `triggerprice_tg` is the **target-leg trigger**.

## Endpoint URL

```http
Local Host   :  POST http://127.0.0.1:5000/api/v1/placegttorder
Ngrok Domain :  POST https://<your-ngrok-domain>.ngrok-free.app/api/v1/placegttorder
Custom Domain:  POST https://<your-custom-domain>/api/v1/placegttorder
```

## Sample API Request (SINGLE): "Buy IDEA if it dips to 9.55, place a LIMIT order at 9.50"

```json
{
  "apikey": "<your_app_apikey>",
  "strategy": "My GTT Strategy",
  "trigger_type": "SINGLE",
  "exchange": "NSE",
  "symbol": "IDEA",
  "action": "BUY",
  "product": "CNC",
  "quantity": 1,
  "pricetype": "LIMIT",
  "price": 9.50,
  "triggerprice_sl": 9.55,
  "triggerprice_tg": 0,
  "stoploss": null,
  "target": null
}
```

LTP is currently above 9.55 → trigger sits **below** LTP → use `triggerprice_sl`.

## Sample cURL Request

```bash
curl -X POST http://127.0.0.1:5000/api/v1/placegttorder \
  -H 'Content-Type: application/json' \
  -d '{
  "apikey": "<your_app_apikey>",
  "strategy": "My GTT Strategy",
  "trigger_type": "SINGLE",
  "exchange": "NSE",
  "symbol": "IDEA",
  "action": "BUY",
  "product": "CNC",
  "quantity": 1,
  "pricetype": "LIMIT",
  "price": 9.50,
  "triggerprice_sl": 9.55,
  "triggerprice_tg": 0,
  "stoploss": null,
  "target": null
}'
```

## Sample API Response

```json
{
  "status": "success",
  "trigger_id": "23132604291205"
}
```

## Sample API Request (SINGLE): "Buy RELIANCE at MARKET if it breaks above 1450"

```json
{
  "apikey": "<your_app_apikey>",
  "strategy": "My GTT Strategy",
  "trigger_type": "SINGLE",
  "exchange": "NSE",
  "symbol": "RELIANCE",
  "action": "BUY",
  "product": "CNC",
  "quantity": 1,
  "pricetype": "MARKET",
  "price": 0,
  "triggerprice_sl": 0,
  "triggerprice_tg": 1450,
  "stoploss": null,
  "target": null
}
```

LTP is currently below 1450 → trigger sits **above** LTP → use `triggerprice_tg`. `price=0` because pricetype is MARKET.

## Sample API Request (OCO): "Protect my INFY holding, stop at 1480, take profit at 1620"

```json
{
  "apikey": "<your_app_apikey>",
  "strategy": "Bracket OCO",
  "trigger_type": "OCO",
  "exchange": "NSE",
  "symbol": "INFY",
  "action": "SELL",
  "product": "CNC",
  "quantity": 5,
  "pricetype": "LIMIT",
  "price": 0,
  "triggerprice_sl": 1480,
  "stoploss": 1478,
  "triggerprice_tg": 1620,
  "target": 1622
}
```

`price=0` because OCO uses per-leg limit prices: `stoploss` (the SL leg's limit) and `target` (the target leg's limit).

## Sample API Response (OCO)

```json
{
  "status": "success",
  "trigger_id": "23132604291213"
}
```

## Parameters Description

| Parameters       | Description                                                                                                                                    | Mandatory/Optional | Default Value |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | ------------- |
| apikey           | OpenAlgo API key (string)                                                                                                                      | Mandatory          | -             |
| strategy         | Strategy identifier (string, used as broker correlation id where supported)                                                                    | Mandatory          | -             |
| trigger\_type    | `SINGLE` or `OCO` (string)                                                                                                                     | Mandatory          | -             |
| exchange         | Any value in the shared `VALID_EXCHANGES` list (string)                                                                                        | Mandatory          | -             |
| symbol           | Trading symbol in OpenAlgo format (string)                                                                                                     | Mandatory          | -             |
| action           | `BUY` or `SELL` (string). For OCO, applies to both legs.                                                                                       | Mandatory          | -             |
| product          | `CNC` (equity delivery) or `NRML` (F\&O overnight). MIS is **not** supported because GTTs can sit for days. (string)                           | Mandatory          | -             |
| quantity         | Order quantity. Integer for equity/F\&O; fractional float allowed for crypto (number).                                                         | Mandatory          | -             |
| pricetype        | `LIMIT` or `MARKET` (string)                                                                                                                   | Optional           | `LIMIT`       |
| price            | **SINGLE only**. Limit price of the child order. Send `0` when `pricetype=MARKET`. Ignored for OCO. (float)                                    | Mandatory          | -             |
| triggerprice\_sl | Trigger price below LTP. **SINGLE**: use this OR `triggerprice_tg`. **OCO**: required (the stoploss-leg trigger). (float)                      | Conditional        | `0`           |
| triggerprice\_tg | Trigger price above LTP. **SINGLE**: use this OR `triggerprice_sl`. **OCO**: required (the target-leg trigger). (float)                        | Conditional        | `0`           |
| stoploss         | **OCO only**. Limit price for the stoploss leg's child order. Ignored for SINGLE. (float, `null`, or `""`)                                     | Conditional        | `null`        |
| target           | **OCO only**. Limit price for the target leg's child order. Ignored for SINGLE. (float, `null`, or `""`)                                       | Conditional        | `null`        |
| expires\_at      | Requested expiry for the trigger, passed through to brokers that support one. Brokers without an explicit expiry ignore it. (string or `null`) | Optional           | `null`        |

Unlike most OpenAlgo request schemas, `PlaceGTTOrderSchema` sets `unknown = EXCLUDE`, so an unrecognized field is dropped rather than rejected with HTTP 400. Do not rely on that to smuggle broker-specific parameters through: dropped fields never reach the broker. `last_price` in particular is discarded if you send it; an adapter fetches it server-side when its broker requires it.

### Trigger Field Rules

| trigger\_type | What you must send                                                                   | Constraint                                                                            |
| ------------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------- |
| `SINGLE`      | send one positive trigger; the schema prefers `triggerprice_sl` if both are positive | `price` is the child order's limit; send `0` for MARKET.                              |
| `OCO`         | all four: `triggerprice_sl`, `stoploss`, `triggerprice_tg`, `target` (all >0)        | `triggerprice_sl < triggerprice_tg`. Both legs share `action`, `quantity`, `product`. |

## Response Fields

| Field       | Type   | Description                                                                      |
| ----------- | ------ | -------------------------------------------------------------------------------- |
| status      | string | `"success"` or `"error"`                                                         |
| trigger\_id | string | Unique trigger ID from broker (on success). Save this to modify or cancel later. |
| message     | string | Error message (on error)                                                         |

## Approval and execution outcomes

In Semi-Auto mode this request can return HTTP `200`, `status: "success"`, `mode: "semi_auto"` and `pending_order_id` after queuing for Action Center approval. It has not yet placed a broker order. In Auto/analyzer execution, inspect the placement result and confirm fills separately. See [order outcomes and retries](https://docs.openalgo.in/api-documentation/v1.md#order-outcomes-and-retries).

## Notes

* Numeric fields (`quantity`, `price`, `triggerprice_sl`, `triggerprice_tg`, `stoploss`, `target`) are JSON floats. Empty strings (`""`) for `stoploss`/`target`/`triggerprice_sl`/`triggerprice_tg` are also accepted and coerced to `null`/`0`.
* Where a broker requires `last_price`, its adapter obtains it server-side. Do not send it as a request field; some integrations, such as Rupeezy, do not require that snapshot.
* **MARKET handling**: some brokers' GTT APIs only accept LIMIT child orders. When that's the case, OpenAlgo automatically converts a MARKET request into a Market-Price-Protected LIMIT (a slab-based buffer around LTP for SINGLE, or around each leg's trigger for OCO) rather than sending a native market child. The protected limit can remain unfilled; semantics vary by broker.
* **OCO direction**: stoploss-leg trigger must be **below** target-leg trigger (`triggerprice_sl < triggerprice_tg`). The `action` (BUY or SELL) applies to both legs.
* **Analyzer (sandbox) mode** places the GTT in the sandbox instead of at the broker: the response carries `"mode": "analyze"` and a `GTT-...` trigger id, margin is reserved at placement, and the trigger is evaluated against available live LTP to place a sandbox order. See [GTTOrderBook](https://docs.openalgo.in/api-documentation/v1/orders-api/gttorderbook.md) for how to read what fired.
* **Symbol format**:
  * Equity: `RELIANCE`
  * Futures: `NIFTY30JAN25FUT`
  * Options: `NIFTY30JAN2525000CE`

A fired trigger creates an ordinary child order; triggering does not guarantee a fill. MARKET requests converted to protected LIMIT orders can remain unfilled. Sandbox triggering does not reproduce broker queues, exchange liquidity or outage behavior.

## Broker-Specific Behaviour

This checkout includes live GTT modules for **Angel, Dhan, Fyers, Rupeezy, Upstox and Zerodha**. Other brokers return `501` in live mode. Sandbox GTT is routed before that live capability gate. Supported exchanges, products, child-order types and history differ by broker.

### Angel — two independent rules

Angel has no native two-leg OCO. OpenAlgo creates two independent single rules and returns a composite trigger ID such as `1234567-1234568`. Keep that entire ID for modify/cancel. The book exposes two separate SINGLE rows, because the broker does not store their pairing. **Do not rely on one rule automatically cancelling the other** when it fires. Modify and cancel operate sequentially and can fail after only one rule was changed; reconcile both rules before retrying. A failed second placement attempts to cancel the first rule, but a transport failure can still require broker-book verification.

### Rupeezy — per-leg modification and history

Rupeezy's Vortex integration supports SINGLE/OCO and history. Modification reads the current book to obtain the leg IDs; a failed book read prevents modification. Its trigger engine uses broker LTP, so it does not require the same `last_price` snapshot as Kite.

### Upstox — OCO opens a position

> **Warning.** On Upstox, `trigger_type=OCO` does **not** behave like it does on Zerodha or Dhan. It will **open a position at market** before activating its two exit rules. If you meant to protect something you already hold, use `SINGLE` instead.

Upstox has no exit-only two-leg GTT. Every Upstox GTT must carry an `ENTRY` rule (error `UDAPI1141`), and a multi-rule GTT needs 2–3 rules (`UDAPI1137`) — so there is no combination that omits the entry. What Upstox calls a multi-leg GTT is a **bracket**: an entry, with a target and stop-loss attached that stay dormant until the entry fills. Upstox Pro's own GTT ticket builds exactly this ("Place order if price is below X", plus optional *Add stop loss* / *Add target*).

OpenAlgo's OCO describes only exits on a position assumed to already exist, so it carries no entry price. Mapping it onto Upstox therefore adds an `ENTRY` rule sent as `IMMEDIATE` at LTP, which Upstox acts on straight away:

| You send         | Upstox does                                         |
| ---------------- | --------------------------------------------------- |
| `action: "SELL"` | **BUYs** at market now, then activates target/stop  |
| `action: "BUY"`  | **SELLs** at market now, then activates target/stop |

The entry side is the inverse of `action`, because OpenAlgo's OCO `action` is the side of both *exit* legs. Every OCO placement logs a warning naming the position that will open.

Two further consequences on Upstox:

* **`stoploss` and `target` limit prices are discarded.** Upstox has no per-rule limit-price field; each rule fires at its own trigger price, optionally widened by a market-protection band. A dropped limit is logged.
* **A delivery sell entry needs EDIS.** If the entry leg sells, Upstox rejects the GTT with `UDAPI100500 — EDIS is not validated` until you authorise EDIS once via Upstox Pro. The message mentions demat authorisation rather than the entry leg, which makes it easy to misread.

**What to use instead.** A stop or a target on an existing holding is a `SINGLE` sell GTT, which works on Upstox exactly as it does elsewhere. Upstox's bracket GTT is a useful product, but it needs an entry trigger price that the OCO request shape has no field for; exposing it would require a separate OpenAlgo request type.

## Error Scenarios

| Error                                                                                | Cause                                         |
| ------------------------------------------------------------------------------------ | --------------------------------------------- |
| `triggerprice_sl: SINGLE GTT requires a positive triggerprice_sl or triggerprice_tg` | SINGLE without any trigger price              |
| `triggerprice_sl: Stoploss trigger must be less than target trigger`                 | OCO with `triggerprice_sl >= triggerprice_tg` |
| `triggerprice_sl/stoploss/triggerprice_tg/target: Required for OCO`                  | OCO missing one of the four required fields   |
| `Quantity must be a positive number`                                                 | quantity ≤ 0                                  |
| `GTT supports only CNC (delivery) or NRML (overnight F&O); MIS is intraday-only.`    | `product=MIS` submitted                       |
| `Fractional quantity is not allowed for non-crypto exchanges`                        | Non-integer qty on equity/F\&O                |
| `GTT orders are not supported for broker 'X' yet` (501)                              | Broker doesn't ship a `gtt_api` module        |

***

**Back to**: [API Documentation](https://docs.openalgo.in/api-documentation/v1.md)
