This API is used to replace order, modify quantity or price.

<CliCommand>
# Replace the order ID below with your actual order ID
longbridge order replace 693664675163312128 --qty 200 --price 255.00
</CliCommand>

<SDKLinks module="trade" klass="TradeContext" method="replace_order" />

## Request

<table className="http-basic">
<tbody>
<tr><td className="http-basic-key">HTTP Method</td><td>PUT</td></tr>
<tr><td className="http-basic-key">HTTP URL</td><td>/v1/trade/order </td></tr>
</tbody>
</table>

### Parameters

> Content-Type: application/json; charset=utf-8

| Name              | Type   | Required | Description                                                                                            |
| ----------------- | ------ | -------- | ------------------------------------------------------------------------------------------------------ |
| order_id          | string | YES      | Order ID                                                                                               |
| quantity          | string | YES      | Replaced quantity, example: `100`                                                                      |
| price             | string | NO       | Replaced price, example: `388.5`<br/><br/> `LO` / `ELO` / `ALO` / `ODD` / `LIT` Order Required         |
| trigger_price     | string | NO       | Trigger price, example: `388.5`<br/><br/> `LIT` / `MIT` Order Required                                 |
| limit_offset      | string | NO       | Limit offset amount<br/><br/> `TSLPAMT` / `TSLPPCT` Order Required when`limit_depth_level` is set to 0 |
| trailing_amount   | string | NO       | Trailing amount<br/><br/> `TSLPAMT` Order Required                                                     |
| trailing_percent  | string | NO       | Trailing percent<br/><br/> `TSLPPCT` Order Required                                                    |
| remark            | string | NO       | Remark (Maximum 64 characters)                                                                         |
| limit_depth_level | int32  | NO       | Specifies the bid/ask depth level. `TSLPAMT` / `TSLPPCT` Order Required                                |
| monitor_price     | string | NO       | Monitoring price. `TSLPAMT` / `TSLPPCT` Order Required                                                 |
| trigger_count     | int32  | NO       | Number of triggers. `LIT` / `MIT` / `TSLPAMT` / `TSLPPCT` Order Required                               |
| attached_params   | object | NO       | Attached order parameters (take-profit / stop-loss)                                                    |
| attached_params.attached_order_type | string | NO | Attached order type<br/><br/>**Enum Value:**<br/>`PROFIT_TAKER` - Take Profit<br/>`STOP_LOSS` - Stop Loss<br/>`BRACKET` - Bracket Order |
| attached_params.profit_taker_price | string | NO | Take-profit trigger price |
| attached_params.stop_loss_price | string | NO | Stop-loss trigger price |
| attached_params.time_in_force | string | NO | Attached order time in force type<br/><br/>**Enum Value:**<br/>`Day` - Day Order<br/> `GTC` - Good Til Canceled Order<br/> `GTD` - Good Til Date Order (inherits the main order's `expire_date` in this case) |
| attached_params.expire_time | int64 | NO | Expire time (Unix timestamp, in seconds) |
| attached_params.profit_taker_id | int64 | NO | Take-profit order ID, fill in when modifying an existing take-profit order |
| attached_params.stop_loss_id | int64 | NO | Stop-loss order ID, fill in when modifying an existing stop-loss order |
| attached_params.cancel_all_attached | bool | NO | Whether to cancel all attached orders |
| attached_params.main_id | int64 | NO | Main order ID |
| attached_params.quantity | string | NO | Attached order quantity |
| attached_params.market_price | string | NO | Market price |
| attached_params.activate_order_type | string | NO | Order type submitted after triggering, e.g. `LIT` (limit-if-touched) or `MIT` (market-if-touched) |
| attached_params.profit_taker_submit_price | string | NO | Take-profit limit order submitted price, required when `activate_order_type` is `LIT` |
| attached_params.stop_loss_submit_price | string | NO | Stop-loss limit order submitted price, required when `activate_order_type` is `LIT` |
| attached_params.activate_rth | string | NO | Whether the order submitted after triggering allows pre/post market trading<br/><br/>**Enum Value:**<br/> `RTH_ONLY` - Regular trading hours only<br/> `ANY_TIME` - Any time |

### Request Example

<Tabs groupId="request-example">
  <TabItem value="python" label="Python" default>

```python
from decimal import Decimal
from longbridge.openapi import TradeContext, Config, OAuthBuilder

oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = TradeContext(config)

ctx.replace_order(
    order_id = "709043056541253632",
    quantity = Decimal(100),
    price = Decimal(50),
)
```

  </TabItem>
  <TabItem value="python-async" label="Python (async)">

```python
import asyncio
from decimal import Decimal
from longbridge.openapi import AsyncTradeContext, Config, OAuthBuilder

async def main() -> None:
    oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
    config = Config.from_oauth(oauth)
    ctx = AsyncTradeContext.create(config)

    ctx.replace_order(
        order_id = "709043056541253632",
        quantity = Decimal(100),
        price = Decimal(50),
    )

if __name__ == "__main__":
    asyncio.run(main())
```

  </TabItem>
  <TabItem value="nodejs" label="Node.js">

```javascript
const { Config, TradeContext, OAuth, Decimal } = require('longbridge')

async function main() {
  const oauth = await OAuth.build('your-client-id', (_, url) => {
    console.log('Open this URL to authorize: ' + url)
  })
  const config = Config.fromOAuth(oauth)
  const ctx = TradeContext.new(config)
  await ctx.replaceOrder({ orderId: '701276261045858304', quantity: new Decimal(400), price: new Decimal(60) })
  console.log('replaced')
}
main().catch(console.error)
```

  </TabItem>
  <TabItem value="java" label="Java">

```java
import com.longbridge.*;
import com.longbridge.trade.*;
import java.math.BigDecimal;
class Main {
    public static void main(String[] args) throws Exception {
        try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
             Config config = Config.fromOAuth(oauth);
             TradeContext ctx = TradeContext.create(config)) {
            ctx.replaceOrder(new ReplaceOrderOptions("701276261045858304", new BigDecimal("400")).setPrice(new BigDecimal("60"))).get();
            System.out.println("replaced");
        }
    }
}
```

  </TabItem>
  <TabItem value="rust" label="Rust">

```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, trade::{TradeContext, ReplaceOrderOptions}, Config};
use rust_decimal::Decimal;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
    let config = Arc::new(Config::from_oauth(oauth));
    let (ctx, _) = TradeContext::new(config);
    ctx.replace_order(
        ReplaceOrderOptions::new("701276261045858304", Decimal::from(400))
            .price(Decimal::from(60))
    ).await?;
    println!("replaced");
    Ok(())
}
```

  </TabItem>
  <TabItem value="cpp" label="C++">

```cpp
#include <iostream>
#include <longbridge.hpp>

#ifdef WIN32
#include <windows.h>
#endif

using namespace longbridge;
using namespace longbridge::trade;

static void
run(const OAuth& oauth)
{
    Config config = Config::from_oauth(oauth);
    TradeContext ctx = TradeContext::create(config);

    ReplaceOrderOptions opts{"701276261045858304", 400, Decimal(60.0)};
    ctx.replace_order(opts, [](auto res) {
        if (!res) { std::cout << "failed" << std::endl; return; }
        std::cout << "replaced" << std::endl;
    });
}

int main(int argc, char const* argv[]) {
#ifdef WIN32
    SetConsoleOutputCP(CP_UTF8);
#endif

    const std::string client_id = "your-client-id";
    OAuthBuilder(client_id).build(
    [](const std::string& url) {
        std::cout << "Open this URL to authorize: " << url << std::endl;
    },
    [](auto res) {
        if (!res) {
            std::cout << "authorization failed: " << *res.status().message() << std::endl;
            return;
        }
        run(*res);
    });

    std::cin.get();
    return 0;
}
```

  </TabItem>
  <TabItem value="go" label="Go">

```go
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/longbridge/openapi-go/config"
	"github.com/longbridge/openapi-go/oauth"
	"github.com/longbridge/openapi-go/trade"
	"github.com/shopspring/decimal"
)

func main() {
	o := oauth.New("your-client-id").
		OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
	if err := o.Build(context.Background()); err != nil {
		log.Fatal(err)
	}
	conf, err := config.New(config.WithOAuthClient(o))
	if err != nil {
		log.Fatal(err)
	}
	tctx, err := trade.NewFromCfg(conf)
	if err != nil {
		log.Fatal(err)
	}
	defer tctx.Close()
	err = tctx.ReplaceOrder(context.Background(), &trade.ReplaceOrder{
		OrderId:  "701276261045858304",
		Quantity: 400,
		Price:    decimal.NewFromFloat(60),
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("replaced")
}
```

  </TabItem>
</Tabs>

## Response

### Response Headers

- Content-Type: application/json

### Response Example

```json
{
  "code": 0,
  "message": "success",
  "data": {}
}
```

### Response Status

| Status | Description                                                   | Schema |
| ------ | ------------------------------------------------------------- | ------ |
| 200    | The submission was successful and the order was commissioned. | None   |
| 400    | The replace was rejected with an incorrect request parameter. | None   |

<aside className="success">
</aside>