# LongPort OpenAPI Documentation

# Getting Started

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

## Foreword

LongPort OpenAPI SDK is implemented based on Rust we have released SDK for Python, Node.js, Rust, C++/C and Java ..., and support for other languages will be launched in the future.

## API Host

- HTTP API - `https://openapi.longportapp.com`
- WebSocket Quote - `wss://openapi-quote.longportapp.com`
- WebSocket Trade - `wss://openapi-trade.longportapp.com`

:::tip
For access in mainland China, it is recommended to use `openapi.longportapp.cn`, `openapi-quote.longportapp.cn`, `openapi-trade.longportapp.cn` to improve access speed.

If you are use our SDK, the `LONGPORT_REGION=cn` env variable can to use to setup the API region (Current only support: `cn`, `hk`).
:::

## Time Format

All API response are used [Unix Timestamp](https://en.wikipedia.org/wiki/Unix_time), timezone is UTC.

## Environment Requirements

<Tabs groupId="programming-language">
  <TabItem value="python" label="Python" default>
    <li><a href="https://www.python.org/">Python 3</a></li>
    <li>Pip</li>
  </TabItem>
  <TabItem value="javascript" label="JavaScript">
    <li><a href="https://nodejs.org/">Node.js</a></li>
    <li>Yarn</li>
  </TabItem>
  <TabItem value="rust" label="Rust">
    <li><a href="https://www.rust-lang.org/">Rust</a></li>
  </TabItem>
  <TabItem value="java" label="Java">
    <li><a href="https://openjdk.org/">JDK</a></li>
    <li><a href="https://maven.apache.org/">Maven</a></li>
  </TabItem>
  <TabItem value="go" label="Go">
    <li><a href="https://go.dev">Go</a></li>
    <li><a href="https://pkg.go.dev/github.com/longportapp/openapi-go">Go Docs</a></li>
  </TabItem>
</Tabs>

## Install SDK

<Tabs groupId="programming-language">
  <TabItem value="python" label="Python" default>

```bash
pip3 install longport
```

  </TabItem>
  <TabItem value="javascript" label="JavaScript">

```bash
yarn install longport
```

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

```toml
[dependencies]
longport = "3.0.5"
tokio = { version = "1", features = "rt-multi-thread" }
```

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

```xml
<dependencies>
    <dependency>
        <groupId>io.github.longportapp</groupId>
        <artifactId>openapi-sdk</artifactId>
        <version>LATEST</version>
    </dependency>
</dependencies>
```

  </TabItem>

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

```shell
go get github.com/longportapp/openapi-go
```

  </TabItem>

</Tabs>

Let's take obtaining assets as an example to demonstrate how to use the SDK.

## Configuration

1. Download App and open an account.
2. Get App Key, App Secret, Access Token and other information from [LongPort OpenAPI](https://open.longportapp.com) official website

   **_Get App Key, App Secret, Access Token and other information_**

   Login the [LongPort OpenAPI](https://open.longportapp.com) website, and enter the "User Center".

   The "application credential" credential information will be given on the page. After we get it, we will set the environment variable, which is convenient for later development and use.

### Environment Variables

:::caution
Please pay attention to protect your **Access Token** information, anyone who gets it can trade your account through OpenAPI!
:::

| 环境变量                    | 说明                                                               | 值范围          |
| --------------------------- | ------------------------------------------------------------------ | --------------- |
| `LONGPORT_APP_KEY`          | App Key get from developer center                                  |                 |
| `LONGPORT_APP_SECRET`       | App Secret get from developer center                               |                 |
| `LONGPORT_ACCESS_TOKEN`     | Access Token get from developer center                             |                 |
| `LONGPORT_REGION`           | The region of the API, `cn` for mainland China, `hk` for Hong Kong | `cn`, `hk`      |
| `LONGPORT_ENABLE_OVERNIGHT` | Set `true` to enable overnight quote                               | `true`, `false` |

We recommend that you set the environment variables. For the convenience of demonstration, these environment variables will be used in the sample code in the documents in the following chapters.

:::tip About ENV

The ENV variables are **not necessary** conditions, if it is inconvenient to set the ENV variables or encounter problems that are difficult to solve, you can not set the ENV variables, but directly use the parameters in the code to initialize.

The `Config` in LongPort OpenAPI SDK can be directly passed in parameters such as `app_key`, `app_secret`, `access_token` to initialize, pay attention to the comments in the example code below `Init config without ENV`.

:::

#### Set Environment for macOS / Linux

Open the terminal and enter the following command:

```bash
export LONGPORT_APP_KEY="App Key get from user center"
export LONGPORT_APP_SECRET="App Secret get from user center"
export LONGPORT_ACCESS_TOKEN="Access Token get from user center"
```

#### Set Environment for Windows

Windows is a little more complicated, we provide two methods to set the environment variables.

1. **Through the GUI**: Right click on "My Computer" on the desktop, select "Properties", click "Advanced system settings" in the pop-up window.

   - Click "Environment Variables" in the pop-up window.

     <img src="https://assets.lbctrl.com/uploads/82e31e5e-6062-4726-966b-2a72954f4192/windows-env-set.png" width="500" />

   - Click "New" in the pop-up window, then enter the environment variable name, such as `LONGPORT_APP_KEY`, `Value` respectively fill in the App Key, App Secret, Access Token, Region obtained from the page.

2. **Through the CMD**: Press the `Win + R` shortcut keys and enter the `cmd` command to start the command line (it is recommended to use [Windows Terminal](https://apps.microsoft.com/store/detail/windows-terminal/9N0DX20HK701) for a better development experience).

   Enter the following command in the command line to set the environment variable:

   ```bash
   C:\Users\jason> setx LONGPORT_APP_KEY "App Key get from user center"
   Success: the specified value has been saved.

   C:\Users\jason> setx LONGPORT_APP_SECRET "App Secret get from user center"
   Success: the specified value has been saved.

   C:\Users\jason> setx LONGPORT_ACCESS_TOKEN "Access Token get from user center"
   Success: the specified value has been saved.
   ```

   :::caution Windows ENV Restrictions

   Windows ENV Restrictions, when the above commands are executed successfully, you need to restart Windows or log out and log in again before you can read it.

   :::

   After logging out or restarting, open the command line again and enter the following command to verify that the environment variables are set correctly:

   ```bash
   C:\Users\jason> set LONGPORT
   LONGPORT_APP_KEY=xxxxxxx
   LONGPORT_APP_SECRET=xxxxxx
   LONGPORT_ACCESS_TOKEN=xxxxxxx
   ```

   If it prints the value you just set correctly, then the environment variable is right.

## Scene Demonstration

### Get Account Balance

<Tabs groupId="programming-language">
  <TabItem value="python" label="Python" default>

Cteate `account_asset.py` and paste the code below:

```python
from longport.openapi import TradeContext, Config

config = Config.from_env()

# Init config without ENV
# config = Config(app_key = "YOUR_APP_KEY", app_secret = "YOUR_APP_SECRET", access_token = "YOUR_ACCESS_TOKEN")

ctx = TradeContext(config)

resp = ctx.account_balance()
print(resp)
```

Run it

```bash
python account_asset.py
```

  </TabItem>
  <TabItem value="javascript" label="JavaScript">

Cteate `account_asset.js` and paste the code below:

```javascript
const { Config, TradeContext } = require('longport')

let config = Config.fromEnv()

// Init config without ENV
// let config = new Config({ appKey: "YOUR_APP_KEY", appSecret: "YOUR_APP_SECRET", accessToken: "YOUR_ACCESS_TOKEN" })

TradeContext.new(config)
  .then((ctx) => ctx.accountBalance())
  .then((resp) => {
    for (let obj of resp) {
      console.log(obj.toString())
    }
  })
```

Run it

```bash
nodejs account_asset.js
```

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

Cteate `main.rs` and paste the code below:

```rust
use std::sync::Arc;

use longport::{trade::TradeContext, Config};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = Arc::new(Config::from_env()?);

    // Init config without ENV
    // let config = Arc::new(Config::new("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN")?);

    let (ctx, _) = TradeContext::try_new(config).await?;

    let resp = ctx.account_balance().await?;
    println!("{:?}", resp);
    Ok(())
}
```

Run it

```bash
cargo run
```

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

Cteate `Main.java` and paste the code below:

```java
import com.longport.*;
import com.longport.trade.*;

class Main {
    public static void main(String[] args) throws Exception {
        Config config = Config.fromEnv();

        // Init config without ENV
        // https://longportapp.github.io/openapi-sdk/java/com/longport/ConfigBuilder.html
        // Config config = ConfigBuilder("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN").build();

        try (TradeContext ctx = TradeContext.create(config).get()) {
            for (AccountBalance obj : ctx.getAccountBalance().get()) {
                System.out.println(obj);
            }
        }
    }
}
```

Run it

```bash
mvn compile exec:exec
```

  </TabItem>

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

Create `main.go` and paste the code below:

```go
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/longportapp/openapi-go/config"
    "github.com/longportapp/openapi-go/trade"
)

func main() {
    conf, err := config.New()

    // Init config without ENV
    // https://github.com/longportapp/openapi-go/blob/v0.9.2/config/config_test.go#L11
    // conf, err := config.New(config.WithConfigKey("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN"))

    if err != nil {
        log.Fatal(err)
    }
    tradeContext, err := trade.NewFromCfg(conf)
    if err != nil {
        log.Fatal(err)
    }
    defer tradeContext.Close()
    ctx := context.Background()
    // Get AccountBalance infomation
    ab, err := tradeContext.AccountBalance(ctx)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%+v", ab)
}
```

Run:

```shell
go mod tidy
go run ./
```

  </TabItem>

</Tabs>

After running, the output is as follows:

```
[
  AccountBalance {
    total_cash: 503898884.81,
    max_finance_amount: 0.00,
    remaining_finance_amount: 501403229.49,
    risk_level: Some(1),
    margin_call: 0,
    currency: "HKD",
    cash_infos: [
      CashInfo {
        withdraw_cash: 501214985.15,
        available_cash: 501214985.15,
        frozen_cash: 584438.25,
        settling_cash: -3897793.90,
        currency: "HKD",
      },
      CashInfo {
        withdraw_cash: -25546.89,
        available_cash: -25546.89,
        frozen_cash: 295768.57,
        settling_cash: 2326.60,
        currency: "USD",
      }
    ]
  }
]
```

### Subscribe Quote

To subscribe to market data, please check the [Developer Center](https://open.longportapp.com/account) - "Quote authority" is correct

- HK Market - BMP basic quotation is unable to subscribe with WebSocket as it has no real-time quote push.
- US Market - LV1 Nasdaq Basic (Only Open API).

Before running, visit the [Developer Center](https://open.longportapp.com/account) and ensure that the account has the correct quote level.

:::info

If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.

<https://longportapp.com/download>
:::

When you have the correct Quote authority, it might look like this:

<img src="https://pub.pbkrs.com/files/202205/VeSgQksvfu3Q2iPN/SCR-20220510-gkx.png" className="max-w-2xl" />

<Tabs groupId="programming-language">
  <TabItem value="python" label="Python" default>

Create `subscribe_quote.py` and paste the code below:

```python
from time import sleep
from longport.openapi import QuoteContext, Config, SubType, PushQuote


def on_quote(symbol: str, quote: PushQuote):
    print(symbol, quote)


config = Config.from_env()
ctx = QuoteContext(config)
ctx.set_on_quote(on_quote)

symbols = ["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"]
ctx.subscribe(symbols, [SubType.Quote], True)
sleep(30)
```

Run it

```bash
python subscribe_quote.py
```

  </TabItem>
  <TabItem value="javascript" label="JavaScript">

Create `subscribe_quote.js` and paste the code below:

```javascript
const { Config, QuoteContext, SubType } = require('longport')

let config = Config.fromEnv()
QuoteContext.new(config).then((ctx) => {
  ctx.setOnQuote((_, event) => console.log(event.toString()))
  ctx.subscribe(['700.HK', 'AAPL.US', 'TSLA.US', 'NFLX.US'], [SubType.Quote], true)
})
```

Run it

```bash
nodejs subscribe_quote.js
```

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

Create `main.rs` and paste the code below:

```rust
use std::sync::Arc;

use longport::{
    quote::{QuoteContext, SubFlags},
    Config,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = Arc::new(Config::from_env()?);
    let (ctx, mut receiver) = QuoteContext::try_new(config).await?;

    ctx.subscribe(
        ["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"],
        SubFlags::QUOTE,
        true,
    )
    .await?;

    while let Some(event) = receiver.recv().await {
        println!("{:?}", event);
    }
    Ok(())
}
```

Run it

```bash
cargo run
```

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

Create `Main.java` and paste the code below:

```java
import com.longport.*;
import com.longport.quote.*;

class Main {
    public static void main(String[] args) throws Exception {
        try (Config config = Config.fromEnv(); QuoteContext ctx = QuoteContext.create(config).get()) {
            ctx.setOnQuote((symbol, quote) -> {
                System.out.printf("%s\t%s\n", symbol, quote);
            });
            ctx.subscribe(new String[] { "700.HK", "AAPL.US", "TSLA.US", "NFLX.US" }, SubFlags.Quote, true).get();
            Thread.sleep(30000);
        }
    }
}
```

Run it

```bash
mvn compile exec:exec
```

  </TabItem>

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

Create file `main.go` and paste the code below:

```go
package main

import (
    "context"
    "encoding/json"
    "fmt"
    "log"
    "os"
    "os/signal"
    "syscall"
    "time"

    "github.com/longportapp/openapi-go/config"
    "github.com/longportapp/openapi-go/quote"
)

func main() {
 // create quote context from environment variables
    conf, err := config.New()
    if err != nil {
        log.Fatal(err)
    }
    quoteContext, err := quote.NewFromCfg(conf)
    if err != nil {
        log.Fatal(err)
        return
    }
    defer quoteContext.Close()
    ctx := context.Background()
    quoteContext.OnQuote(func(pe *quote.PushQuote) {
        bytes, _ := json.Marshal(pe)
        fmt.Println(string(bytes))
    })
    quoteContext.OnDepth(func(d *quote.PushDepth) {
        bytes, _ := json.Marshal(d)
        if d.Sequence != 0 {
            fmt.Print(time.UnixMicro(d.Sequence/1000).Format(time.RFC3339) + " ")
        }
        fmt.Println(string(bytes))
    })

    // Subscribe some symbols
    err = quoteContext.Subscribe(ctx, []string{"700.HK", "AAPL.US", "NFLX.US"}, []quote.SubType{quote.SubTypeDepth}, true)
    if err != nil {
        log.Fatal(err)
        return
    }

    quitChannel := make(chan os.Signal, 1)
    signal.Notify(quitChannel, syscall.SIGINT, syscall.SIGTERM)
    <-quitChannel
}
```

Run:

```shell
go run ./
```

  </TabItem>

</Tabs>

After running, the output is as follows:

```
700.HK PushQuote {
    last_done: 367.000,
    open: 362.000,
    high: 369.400,
    low: 356.000,
    timestamp: "2022-06-06T08:10:00Z",
    volume: 22377421,
    turnover: 8081883405.000,
    trade_status: Normal,
    trade_session: Normal
  }
AAPL.US PushQuote {
  last_done: 147.350,
  open: 150.700,
  high: 151.000,
  low: 146.190,
  timestamp: "2022-06-06T11:57:36Z",
  volume: 3724407,
  turnover: 550606662.815,
  trade_status: Normal,
  trade_session: Pre
}
NFLX.US PushQuote {
  last_done: 201.250,
  open: 205.990,
  high: 205.990,
  low: 200.110,
  timestamp: "2022-06-06T11:57:26Z",
  volume: 137821,
  turnover: 27888085.590,
  trade_status: Normal,
  trade_session: Pre
}
```

### Submit Order

Next, we will do a [submit order](https://open.longportapp.com/docs/trade/order/submit) action, we assume that to buy `700.HK` at 50 HKD and quantity is `100`.

> NOTE: In order to prevent a successful test buy, the demo here gives a lower price and avoids the transaction. OpenAPI operations are equivalent to online transactions, please operate with caution, and pay attention to parameter details during development and debugging.

<Tabs groupId="programming-language">
  <TabItem value="python" label="Python" default>

Create `submit_order.py` and paste the code below:

```python
from decimal import Decimal
from longport.openapi import TradeContext, Config, OrderSide, OrderType, TimeInForceType

config = Config.from_env()
ctx = TradeContext(config)

resp = ctx.submit_order(
    side=OrderSide.Buy,
    symbol="700.HK",
    order_type=OrderType.LO,
    submitted_price=Decimal(50),
    submitted_quantity=Decimal(200),
    time_in_force=TimeInForceType.Day,
    remark="Hello from Python SDK",
)
print(resp)
```

Run it

```bash
python submit_order.py
```

  </TabItem>
  <TabItem value="javascript" label="JavaScript">

Create `submit_order.js` and paste the code below:

```javascript
const { Config, TradeContext, OrderType, OrderSide, Decimal, TimeInForceType } = require('longport')

let config = Config.fromEnv()
TradeContext.new(config)
  .then((ctx) =>
    ctx.submitOrder({
      symbol: '700.HK',
      orderType: OrderType.LO,
      side: OrderSide.Buy,
      timeInForce: TimeInForceType.Day,
      submittedQuantity: new Decimal(200),
      submittedPrice: new Decimal(300),
    })
  )
  .then((resp) => console.log(resp.toString()))
```

Run it

```bash
nodejs submit_order.js
```

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

Create `main.rs` and paste the code below:

```rust
use std::sync::Arc;

use longport::{
    decimal,
    trade::{OrderSide, OrderType, SubmitOrderOptions, TimeInForceType, TradeContext},
    Config,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = Arc::new(Config::from_env()?);
    let (ctx, _) = TradeContext::try_new(config).await?;

    let opts = SubmitOrderOptions::new(
        "700.HK",
        OrderType::LO,
        OrderSide::Buy,
        decimal!(200i32),
        TimeInForceType::Day,
    )
    .submitted_price(decimal!(50i32));
    let resp = ctx.submit_order(opts).await?;
    println!("{:?}", resp);
    Ok(())
}
```

Run it

```bash
cargo run
```

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

Create `Main.java` and paste the code below:

```java
import com.longport.*;
import com.longport.trade.*;
import java.math.BigDecimal;

public class Main {
    public static void main(String[] args) throws Exception {
        try (Config config = Config.fromEnv(); TradeContext ctx = TradeContext.create(config).get()) {
            SubmitOrderOptions opts = new SubmitOrderOptions("700.HK",
                    OrderType.LO,
                    OrderSide.Buy,
                    new BigDecimal(200),
                    TimeInForceType.Day).setSubmittedPrice(new BigDecimal(50));
            SubmitOrderResponse resp = ctx.submitOrder(opts).get();
            System.out.println(resp);
        }
    }
}
```

Run it

```bash
mvn compile exec:exec
```

  </TabItem>

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

创建 `main.go`，贴入一下内容：

```go
package main

import (
    "context"
    "fmt"
    "log"
    "os"
    "os/signal"
    "syscall"

    "github.com/shopspring/decimal"

    "github.com/longportapp/openapi-go/config"
    "github.com/longportapp/openapi-go/trade"
)

func main() {
    // create trade context from environment variables
    conf, err := config.New()
    if err != nil {
        log.Fatal(err)
    }
    tradeContext, err := trade.NewFromCfg(conf)
    if err != nil {
        log.Fatal(err)
        return
    }


    defer tradeContext.Close()

    // subscribe order status
    tradeContext.OnTrade(func(ev *trade.PushEvent) {
        // handle order changing event
    })

    ctx := context.Background()
    // submit order
    order := &trade.SubmitOrder{
        Symbol:            "700.HK",
        OrderType:         trade.OrderTypeLO,
        Side:              trade.OrderSideBuy,
        SubmittedQuantity: 200,
        TimeInForce:       trade.TimeTypeDay,
        SubmittedPrice:    decimal.NewFromFloat(12),
    }
    orderId, err := tradeContext.SubmitOrder(ctx, order)
    if err != nil {
        log.Fatal(err)
        return
    }
    fmt.Printf("orderId: %v\n", orderId)


    quitChannel := make(chan os.Signal, 1)
    signal.Notify(quitChannel, syscall.SIGINT, syscall.SIGTERM)
    <-quitChannel
}
```

运行：

```shell
go run ./
```

  </TabItem>

</Tabs>

After running, the output is as follows:

```
SubmitOrderResponse { order_id: "718437534753550336" }
```

### Get Today Order

<Tabs groupId="programming-language">
  <TabItem value="python" label="Python" default>

Create `today_orders.py` and paste the code below:

```python
from longport.openapi import TradeContext, Config

config = Config.from_env()
ctx = TradeContext(config)

resp = ctx.today_orders()
print(resp)
```

Run it

```bash
python today_orders.py
```

  </TabItem>
  <TabItem value="javascript" label="JavaScript">

Create `today_orders.js` and paste the code below:

```javascript
const { Config, TradeContext } = require('longport')

let config = Config.fromEnv()
TradeContext.new(config)
  .then((ctx) => ctx.todayOrders())
  .then((resp) => {
    for (let obj of resp) {
      console.log(obj.toString())
    }
  })
```

Run it

```bash
nodejs today_orders.js
```

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

Create `main.rs` and paste the code below:

```rust
use std::sync::Arc;

use longport::{trade::TradeContext, Config};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = Arc::new(Config::from_env()?);
    let (ctx, _) = TradeContext::try_new(config).await?;

    let resp = ctx.today_orders(None).await?;
    for obj in resp {
        println!("{:?}", obj);
    }
    Ok(())
}
```

Run it

```bash
cargo run
```

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

Create `Main.java` and paste the code below:

```java
import com.longport.*;
import com.longport.trade.*;

class Main {
    public static void main(String[] args) throws Exception {
        try (Config config = Config.fromEnv(); TradeContext ctx = TradeContext.create(config).get()) {
            Order[] orders = ctx.getTodayOrders(null).get();
            for (Order order : orders) {
                System.out.println(order);
            }
        }
    }
}
```

Run it

```bash
mvn compile exec:exec
```

  </TabItem>

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

Create file `main.go` and paste the code below:

```go
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/longportapp/openapi-go/config"
    "github.com/longportapp/openapi-go/trade"
)

func main() {
    // create trade context from environment variables
    conf, err := config.New()
    if err != nil {
        log.Fatal(err)
    }
    tradeContext, err := trade.NewFromCfg(conf)
    if err != nil {
        log.Fatal(err)
    }
    defer tradeContext.Close()
    ctx := context.Background()
    // today orders
    orders, err := tradeContext.TodayOrders(ctx, &trade.GetTodayOrders{})
    if err != nil {
        log.Fatal(err)
    }

    for _, order := range orders {
        fmt.Printf("%+v\n", order)
    }
}
```

Run:

```shell
go run ./
```

  </TabItem>

</Tabs>

After running, the output is as follows:

```
Order {
  order_id: "718437534753550336",
  status: NotReported,
  stock_name: "腾讯控股 1",
  quantity: 200,
  executed_quantity: None,
  price: Some(50.000),
  executed_price: None,
  submitted_at: 2022-06-06T12:14:16Z,
  side: Buy,
  symbol: "700.HK",
  order_type: LO,
  last_done: None,
  trigger_price: Some(0.000),
  msg: "",
  tag: Normal,
  time_in_force: Day,
  expire_date: Some(NaiveDate(Date { year: 2022, ordinal: 158 })),
  updated_at: Some(2022-06-06T12:14:16Z),
  trigger_at: None,
  trailing_amount: None,
  trailing_percent: None,
  limit_offset: None,
  trigger_status: None,
  currency: "HKD",
  outside_rth: nonce
}
```

The above example has fully demonstrated how to use the SDK to access the OpenAPI interface. For more interfaces, please read the [LongPort OpenAPI Documentation](https://open.longportapp.com/docs) in detail and use them according to different interfaces.

## More Examples

We provide the complete code of the above examples in the GitHub repository of LongPort OpenAPI Python SDK, and we will continue to add or update it later.

<https://github.com/longportapp/openapi/tree/master/examples>

## SDK API Document

For detailed SDK API document, please visit:

<https://longportapp.github.io/openapi-sdk/>

## Contact & Feedback

If there are any questions or suggestions, please feel free to post an issue on GitHub, we will reply as soon as possible.

Or there have a lot old discussion in the GitHub issue, you can search the issue to find the answer.

- GitHub: https://github.com/longportapp/openapi/issues

# Introduction

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

## Introduction

LongPort OpenAPI provides programmatic quote trading interfaces for investors with research and development capabilities and assists them to build trading or quote strategy analysis tools based on their own investment strategies. The functions fall into the following categories:

- **Trading** - Create, amend, cancel orders, query today's/past orders and transaction details, etc.
- **Quotes** - Real-time quotes, acquisition of historical quotes, etc.
- **Portfolio** - Real-time query of the account assets, positions, funds
- **Real-time subscription** - Provides real-time quotes and push notifications for order status changes

## Interface Type

LongPort provides diversified access methods such as HTTP / WebSockets interfaces for accessing the underlying services and SDK (Python / C++, etc.) encapsulated in the upper layer, allowing flexible choices.

## How to Enable OpenAPI

1. Log in to the [LongPort App](https://longportapp.com/download) to complete the account opening process;

2. Log in to the [longportapp.com](https://longportapp.com) and enter the developer platform, complete the developer verification (OpenAPI permission application), and obtain a token.

## Quote Coverage

<table>
    <thead>
    <tr>
        <th>Market</th>
        <th>Symbol</th>
    </tr>
    </thead>
    <tr>
        <td width="160" rowspan="2">HK Market</td>
        <td>Securities (including equities, ETFs, Warrants, CBBCs)</td>
    </tr>
    <tr>
        <td>Hang Seng Index</td>
    </tr>
    <tr>
        <td rowspan="3">US Market</td>
        <td>Securities (including stocks, ETFs)</td>
    </tr>
    <tr>
        <td>Nasdsaq Index</td>
    </tr>
    <tr>
        <td>OPRA Options</td>
    </tr>
    <tr>
        <td rowspan="2">CN Market</td>
        <td>Securities (including stocks, ETFs)</td>
    </tr>
    <tr>
        <td>Index</td>
    </tr>
</table>

## Trading

Supported trading functions include:

| Market    | Stock and ETF | Warrant & CBBC | Options |
| --------- | ------------- | -------------- | ------- |
| HK Market | ✓             | ✓              |         |
| US Market | ✓             | ✓              | ✓       |

## Rate Limit {#rate-limit}

| Category  | Limitation                                                                                                                                                                                                                            |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Quote API | <ul><li>One account can only create one long link and subscribe to a maximum of 500 symbols at the same time</li><li>No more than 10 calls in a 1-second interval and the number of concurrent requests should not exceed 5</li></ul> |
| Trade API | <ul><li>No more than 30 calls in a 30-second interval, and the interval between two calls should not be less than 0.02 seconds</li></ul>                                                                                              |

:::success

The [OpenAPI SDK](https://open.longportapp.com/sdk) has done effective frequency control internally:

- Quote: The methods under `QuoteContext` will be actively controlled by the SDK according to the server's rate limit. When the request is too fast, the SDK will automatically delay the request. Therefore, you do not need to implement the frequency control details separately.
- Trade: The methods under `TradeContext` are not limited by the SDK. Due to the special nature of the trading order placement scenario, this is left to the user to handle.

:::

## Pricing {#pricing}

LongPort does not charge any additional fees for activating or using interface services. You only need to open a LongPort Integrated A/C and get OpenAPI service permissions to use it for free. For actual transaction fees, please contact the brokerage firm where you have opened your securities account.

## Other

The OpenAPI services are provided by LongPort and the applicable affiliates (subject to the agreement).
openapi-trade.longportapp.com

# Llm

# LLM Components

We provide some components for LLM (Large language models), you can easily access and analyze financial data, real-time market data, even tell AI to submit orders.

<video src="https://pub.lbkrs.com/files/202503/SGozJNWBfYpta73i/longport-mcp.mp4" width="100%" autoplay loop controls  />

Yes, you can do it via LongPort OpenAPI with our LLM components, start today!

## LLMs Text

The OpenAPI Docs follow [LLMs Text](https://llmstxt.org/) to provide [llms.txt](/llms.txt) and Markdown files for each documents.

- [https://open.longportapp.com/llms.txt](https://open.longportapp.com/llms.txt) - About 2104 tokens.

Our each document is also available in Markdown format, when you visit them, just add `.md` suffix to the URL.

For example:

- https://open.longportapp.com/docs/getting-started.md
- https://open.longportapp.com/docs/quote/pull/static.md

## MCP

We in building the [MCP](https://modelcontextprotocol.io/) implementation for LongPort OpenAPI (Based on our SDK), you can use it in every AI platform that supported [MCP](https://modelcontextprotocol.io/).

And is also open source in our GitHub organization.

[https://github.com/longportapp/openapi](https://github.com/longportapp/openapi/tree/main/mcp)

### Installation

Visit [https://github.com/longportapp/openapi/releases](https://github.com/longportapp/openapi/releases) to download the latest release.

### Usage

When you installed successfully, you will have a `longport-mcp` command line tool.

> NOTE: You must follow [Getting Started](/docs/getting-started) to configure your environment.

The environment `LONGPORT_APP_KEY`, `LONGPORT_APP_SECRET` and `LONGPORT_ACCESS_TOKEN` must be set before you start the MCP server.

#### Configuration LongPort MCP in your AI Chat

This part we will show you how to configure LongPort MCP in your AI chat (The screenshot have used [Cherry Studio](https://cherry-studio.com/)).

**Use STDIO mode:**

Ensure you have already configured your environment variables and install the `longport-mcp` command line tool in your system.

![](https://pub.lbkrs.com/files/202503/QdJeE6WUP9VjFSL7/SCR-20250319-smit.png)

**Use SSE mode:**

You must to start SSE server first, you can use the following command:

```bash
longport-mcp --sse
```

And then configure your AI chat to use `http://localhost:8000`.

![](https://pub.lbkrs.com/files/202503/PhUVovCsMqD2w2rL/SCR-20250319-snro.png)

## Api-reference


## Error Codes

### Error Codes

| HTTP Status | Code   | Message                | Description                                                        |
| ----------- | ------ | ---------------------- | ------------------------------------------------------------------ |
| 403         | 403201 | signature invalid      | signature is invalid                                               |
| 403         | 403202 | duplicate request      | Repeat request, same request without replacement `x-timestamp`     |
| 403         | 403203 | apikey illegal         | `App Key` is illegal                                               |
| 403         | 403205 | ip is not allowed      | IP address is not authorized to access                             |
| 401         | 401003 | token expired          | `Access Token` expired, please refresh the Token                   |
| 429         | 429001 | ip request ratelimit   | Too frequent requests as a same IP address, please try again later |
| 429         | 429002 | api request is limited | Too frequent requests on an API, please try again later            |
| 500         | 500000 | internal error         | server internal error, please contact customer support             |

## Overview

This section mainly introduces the basic information of LongPort OpenAPI, including how to access the API, how to use the API, how to obtain the API interface document, etc., the content is relatively primitive.

:::success Tip
It is recommended to directly use the SDK to access the API, the SDK has encapsulated the API call method, which is more convenient to use.

https://open.longportapp.com/sdk
:::

## Notes

| Precautions                                                                                          | Reference Documents                                                             |
| ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| It is recommended to use the SDK of the respective language, instead of calling the native interface | [SDK Quick Start Page](../docs/getting-started)                                 |
| Read the OpenAPI introduction to enable the corresponding service                                    | [How to enable OpenAPI](../docs/#how-to-enable-openapi)                         |
| Read about OpenAPI access and restrictions in OpenAPI Introduction                                   | [OpenAPI's permissions and restrictions](../docs/#permissions-and-restrictions) |
| Common Error Codes for finding errors in interface calls                                             | [Common Error Codes](../docs/error-codes)                                       |

## REST API documentation convention format

The main format of the server REST API documentation is as follows.

```
Request:
    Request Info
    Parameters
    Request Example
Response:
    Response Headers
    Response Example
    Response Status
Response Status
```

### Request Info

This section introduces the request method and path required to call the API.

- HTTP URL: The URL of the server API.
- HTTP Method: The server API only supports HTTP protocol methods, such as GET, POST, etc.

### Parameters

Introduces the request headers, query parameters or request body to be passed to call the API.
:::tip

Parameters are query parameters by default for GET API, parameters are request bodies by default for not GET API, and the request body format is JSON.

:::

### Request Example

Detailed example of calling an interface using the SDK.

### Response

- Response Headers: Returns content header information.
- Response Example: Returns a text example of the content.
- Response Status: Interface returns a specific explanation of the `status` of the content.

## API access process

### 1. Enable OpenAPI service

Refer to [Introduction to OpenAPI](../docs#how-to-enable) to enable the corresponding services.

### 2. Get App Key and Access Token information

Get **Access Token**, **App Key** and **App Secret** on the [Developer Website](https://open.longportapp.com/account).

**Access Token** will expires in three months. Token can be reset in Developer Website after expiration. Also token can be refresh through invoking [Refresh Token](./refresh-token-api) API before token expired.

### 3. Calculate signature

:::tip

Most of the content introduced on this page has been fully implemented in our OpenAPI SDK. If you are an SDK user, you can directly ignore the signature authentication part.

This section is intended as a reference for non-SDK users.

:::

After constructing a request based on an corresponding API documentation, call the API directly through the OpenAPI SDK, which will help generate a signature, or create a signature through the following process.

#### Add `X-Api-Key`、`X-Timestamp`、`Authorization` on headers

Set the request parameter header information, and `X-Api-Key`, `Authorization`, `X-Timestamp` will be used in the signature function.

```python
import time
headers = {}
headers['X-Api-Key'] = '${app_key}'
headers['Authorization'] = '${access_token}'
headers['X-Timestamp' =  str(time.time()) # Unix Timestamp, eg: 1539095200.123
headers['Content-Type'] = 'application/json; charset=utf-8',
```

#### Sign requests

The example of signature function:

```py
# signature function on python3
def sign(method, uri, headers, params, body, secret):
    ts = headers["X-Timestamp"]
    access_token = headers["Authorization"]
    app_key = headers["X-Api-Key"]
    mtd = method.upper()

    canonical_request = mtd + "|" + uri + "|" + params + "|authorization:" + access_token + "\nx-api-key:" + app_key + "\nx-timestamp:" + ts + "\n|authorization;x-api-key;x-timestamp|"

    if body != "":
        payload_hash = hashlib.sha1(body.encode("utf-8")).hexdigest()
        canonical_request = canonical_request + payload_hash

    sign_str = "HMAC-SHA256|" + hashlib.sha1(canonical_request.encode("utf-8")).hexdigest()
    signature = hmac.new(secret.encode('utf-8'), sign_str.encode('utf-8'), digestmod=hashlib.sha256).hexdigest()
    return "HMAC-SHA256 SignedHeaders=authorization;x-api-key;x-timestamp, Signature=" + signature

```

Sign the request and set the signature in the request header `X-Api-Signature`.

```py
# request method
method = "POST"
# request path
uri = "/v1/trade/order/submit"
# request params, for example member_id=1&account_channel=2
params = ""
# request body
body = json.dumps({ "order_id": '683615454870679552' })
# signing requests and set signature it on the X-Api-Signature
headers['X-Api-Signature'] = sign(method, uri, headers, params, body, secret)

```

### 4. Call API

Use the HTTP client to send signed requests.

## API Path

All API paths start with [https://openapi.longportapp.com](https://openapi.longportapp.com).

> TIP: You can also use https://openapi.longportapp.com

## API Request

The call to the server-side interface needs to be in HTTPS protocol, JSON format, and encoded in `UTF-8`.

For a test example:

```bash
curl -v https://openapi.longportapp.com/v1/test \
    -H "X-Api-Signature: {signature}" -H "X-Api-Key: {AppKey}" \
    -H "Authorization: {AccessToken}" -H "X-Timestamp: 1539095200.123"
```

The method of Get Stock Positions interface is `GET` and needs to set query parameters. The example is as follows:

```bash
curl -v https://openapi.longportapp.com/v1/asset/stock?symbol=700.HK&symbol=BABA.US \
    -H "X-Api-Signature: {Signature}" -H "X-Api-Key: {AppKey}" \
    -H "Authorization: {AccessToken}" -H "X-Timestamp: 1539095200.123"
```

The method of Submit Order interface is `POST` and needs to set the request body. The example is as follows:

```bash
curl -v -XPOST https://openapi.longportapp.com/v1/trade/order \
    -d '{ "side": "Buy", symbol": "700.HK", "order_type": "LO", "submitted_price": "50", "submitted_quantity": "200", "time_in_force": " Day", remark": "Hello from Shell"}' \
    -H "X-Api-Signature: {Signature}" -H "X-Api-Key: {AppKey}" \
    -H "Authorization: {AccessToken}" -H "X-Timestamp: 1539095200.123"
    -H "Content-Type: application/json; charset=utf-8"
```

## API Response

All API corresponding body structures consist of `code`, `message`, `data`. `code` is the business code, `message` is the error message, and `data` is the request result.

:::tip
HTTP Status follows [RESTFull style](https://restfulapi.net/http-status-codes) and `code = 0` if the request succeeds, otherwise `code` will describe the specific error code.
:::

### HTTP Status

- 1xx: Informational – Communicates transfer protocol-level information.
- 2xx: Success – Indicates that the client's request was accepted successfully.
- 3xx: Redirection – Indicates that the client must take some additional action in order to complete their request.
- 4xx: Client Error – This category of error status codes points the finger at clients.
- 5xx: Server Error – The server takes responsibility for these error status codes.

For example, the response body of a successful request:

```json
{
  "code": 0,
  "msg": "success",
  "data": {
    // ...
  }
}
```

the response body of a failed request:

```json
{
  "code": 403201,
  "msg": "signature invalid"
}
```

## A code demo to call the API

```py
import requests
import json
import time
import hashlib
import hmac

# request information
# request method
method = "POST"
# request path
uri = "/v1/trade/order/submit"
# request params, for example member_id=1&account_channel=2
params = ""
# request body
body = json.dumps({ "order_id": '683615454870679552' })
# request headers
headers = {}
headers['X-Api-Key'] = '${app_key}'
headers['Authorization'] = '${access_token}'
headers['X-Timestamp'] =  str(time.time()) # Unix TimeStamp, eg. 1539095200.123
headers['Content-Type'] = 'application/json; charset=utf-8'

# App Secret
app_secret = "${app_secret}"

## signature function
def sign(method, uri, headers, params, body, secret):
    ts = headers["X-Timestamp"]
    access_token = headers["Authorization"]
    app_key = headers["X-Api-Key"]
    mtd = method.upper()
    canonical_request = mtd + "|" + uri + "|" + params + "|authorization:" + access_token + "\nx-api-key:" + app_key + "\nx-timestamp:" + ts + "\n|authorization;x-api-key;x-timestamp|"
    if body != "":
        payload_hash = hashlib.sha1(body.encode("utf-8")).hexdigest()
        canonical_request = canonical_request + payload_hash
    sign_str = "HMAC-SHA256|" + hashlib.sha1(canonical_request.encode("utf-8")).hexdigest()

    signature = hmac.new(secret.encode('utf-8'), sign_str.encode('utf-8'), digestmod=hashlib.sha256).hexdigest()
    return "HMAC-SHA256 SignedHeaders=authorization;x-api-key;x-timestamp, Signature=" + signature

# set signature header
headers['X-Api-Signature'] = sign(method,  uri, headers, params, body, app_secret)

# call an API
response = requests.request(method, "https://openapi.longportapp.com" + uri + '?' + params, headers=headers, data=body)

print(response.text)

```

## Refresh Token

# Refresh Access Token

Call this to get a new `access_token` before the old `access_token` expires. The old `access_token` will be invalidated after a successful call.

> Lasted 2022-04-21

## Request

| Basic Information |                   |
| ----------------- | ----------------- |
| HTTP URL          | /v1/token/refresh |
| HTTP Method       | GET               |
| Permission        | Not required      |

### Request Headers

| Name          | Type   | Required | Description |
| ------------- | ------ | -------- | ----------- |
| Authorization | string | Yes      |             |

### Request Parameters

| Name       | Type   | Required | Description                                                                                                  | Example                  |
| ---------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------ | ------------------------ |
| expired_at | string | Yes      | Expiration timestamp, formatted according to [ISO8601](https://en.wikipedia.org/wiki/ISO_8601) specification | 2023-04-14T12:13:57.859Z |

## Response

### Response Body

| Name              | Type   | Description                        |
| ----------------- | ------ | ---------------------------------- |
| code              | int    | Error code, non-zero means failure |
| msg               | string | Error message                      |
| data              | object |                                    |
| ∟token            | string | new access_token                   |
| ∟expired_at       | string | access_token expired time          |
| ∟issued_at        | string | issued time                        |
| ∟account_info     | object | user info                          |
| ∟∟member_id       | string | user id                            |
| ∟∟aaid            | string | aaid                               |
| ∟∟account_channel | string | account_channel                    |

### Response Example

```json
{
  "code": 0,
  "message": "",
  "data": {
    "token": "xxxxxx",
    "expired_at": "2022-05-14T12:13:57.859Z",
    "issued_at": "2022-04-14T12:13:57.859Z",
    "account_info": {
      "member_id": 123,
      "aaid": 13,
      "account_channel": "lb"
    }
  }
}
```

### Socket


### Get Socket OTP (One time password)

# Get OTP (One Time Password) API

Our socket `Token` is one time password, you can use the `Token` to connect to quote or trade gateway. It will be expired after authing.

> Last Update at 2022-04-28

## API

| Info        |                  |
| ----------- | ---------------- |
| HTTP Method | GET              |
| HTTP URL    | /v1/socket/token |

### Request Headers

| Field         | Type   | Required | description                                           |
| ------------- | ------ | -------- | ----------------------------------------------------- |
| Authorization | string | Yes      |                                                       |
| Content-Type  | string | Yes      | **Fixed Contents**："application/json; charset=utf-8" |

### Request Parameters

## Response

### Response Body

| Field | Type   | Description                       |
| ----- | ------ | --------------------------------- |
| code  | int    | error code, failed if not equal 0 |
| msg   | string | error description                 |
| data  | object |                                   |
| ∟otp  | string | token                             |

### Response Example

```json
{
  "code": 0,
  "message": "",
  "data": {
    "otp": "xxxxxxxx"
    }
  }
}
```

#### Protocol


##### Socket


###### Protocol


###### Communication Model

There are three type packet will client and server send to each other:

- handshake - start establish connection
- request - client send request to server
- response - server send response to client
- push - server push real-time data to client

## Handshake

Flow:

```mermaid
sequenceDiagram
client ->> server: 1. handshake
server ->> server: 1.1 check handshake

alt handshake invalid
server --x client: 2. disconnect
else is valid
server -->> client: 2. build connection
end

```

After client sending handshake packet server, the connection has been established. If handshake packet is invalid, server will push a close data to client. If access by `TCP`, client can send handshake packet and first data packet(auth) for accelerating communication.

## Request and Response

`Request <--> Response`: Client send a request packet, server will send back a response packet.

Flow:

```mermaid
sequenceDiagram
autonumber
par request 1
client -->> server: request, req_id: 1
server -->> client: response, req_id: 1
end

par request 100
client -->> server: request, req_id: 100
server -->> client: response: req_id: 100
end

par request n
client -->> server: request, req_id: n
server -->> client: response, req_id: n
end

```

After client and server sucess handshaking, peers can use `Request <--> Response` to communicate. `Request` and `Response` are paired by `request_id`.

> Client and Server can send heartbeat request to each other.

## Push

Push is one peer send data to another peer, and no need response.

```mermaid
sequenceDiagram
server -->> client: push, data 1

server -->> client: push, data 2
```

> Right now, we only support server push data to client.

###### Parse Handshake

Handshake is first thing before client and server establish connection. Handshake negotiate thress things:

- protocol version - right now only version `1`
- data codec type - right now only support `protobuf`, value is `1`
- client platform - value is `9` as `OpenAPI`

So handshake is always fixed contents.

## How `TCP` do handshaking

Client need send two bytes handshake to server.

### Data structure

```
 0 1 2 3 4 5 6 7
+-+-+-+-+-+-+-+-+
|  ver  | codec |
+-+-+-+-+-+-+-+-+
|platfo.|reserve|
+-+-+-+-+-+-+-+-+
```

Fields Explain:

| field    | length in bit | description                               |
| -------- | ------------- | ----------------------------------------- |
| ver      | 4             | protocol version: only value `1`          |
| codec    | 4             | data codec: only value `1` for `protobuf` |
| platform | 4             | client platform: 0b1001 - OpenAPI         |
| reserve  | 4             | reserved                                  |

### Example

- ver - 0b0001
- codec - 0b0001
- platform - 0b1001
- reserve - 0b0000

Two bytes contents:

```
0b00010001,
0b00001001
```

## How `WebSocket` do handshaking

`WebSocket` send handshake info by `URL Query`

### Query Parameters

| Field    | Type | Description                               |
| -------- | ---- | ----------------------------------------- |
| version  | 4    | protocol version: only value `1`          |
| codec    | 4    | data codec: only value `1` for `protobuf` |
| platform | 4    | client platform: `9` - OpenAPI            |

### Example

```
wss://openapi-quote.longportapp.com?version=1&codec=1&platform=9
```

###### Parse Header of Packet

We have three type packet:

- request
- response
- push

The type of packet and some other info can decide the length of packet. Then length of Header is 1 byte.

:::info
The length of Header is 1 byte.
:::

## Structure

```
 0 1 2 3 4 5 6 7
+-+-+-+-+-+-+-+-+
|  type |v|g|re.|
+-+-+-+-+-+-+-+-+
```

| Field   | Length in bit | description                                                       |
| ------- | ------------- | ----------------------------------------------------------------- |
| type    | 4             | packet type:<br/> `1` - request<br/>`2` - resopnse<br/>`3` - push |
| verify  | 1             | if have signature data<br/><br/>`0` - Yes<br/>`1` - No            |
| gzip    | 1             | if use `gzip` to compress data: <br/><br/>`1` - Yes<br/>`0` - No  |
| reserve | 2             | reversed                                                          |

## Example

```
// reserve - 0, gzip - 0, verify - 0,  type - 1
0b 0000 0001

// reserve - 0, gzip - 1, verify - 0, type - 2
0b 0011 0010

// reserve - 0, gzip - 1, verify - 1, type - 3
0b 0001 0011


//  reserve - 3, gzip - 1, verify - 0, type - 3
0b 1110 0011
```

###### Protocol Overview

We use binary format data for communication, protocol support both `WebSocket` and `TCP`.

:::info
Endianness is `BigEndian`
:::

If your are familiar with `Python` or `C++`, we provider [SDK](https://open.longportapp.com/en/sdk) for you.

If you want parse protocol by self, you can check our [Go Implemetation](https://github.com/longportapp/openapi-protocol/tree/main/go).

The endponts of `WebSocket` and `TCP` can be found [here](../hosts).

Before start parse protocol, you should know our [Communication Model](./connect), we split to three type of communication:

- Handshake - For establishing connection
- Request and Response - Pairing data packet for handle api request
- Push - One peer send data to another, no need response

Depends on communication model, there are out typs of packet:

- [Handkeshake](./handshake)
- [Request](./request)
- [Response](./response)
- [Push](./push)

Data is in the `body` of the packet, current we only support [`Protobuf`](https://developers.google.com/protocol-buffers) for codec.

`Protobuf` definition can be found in:

- [Control command](../control-command)
- [Data command](../biz-command)

###### Parse Push Packet

Push is one side send data to another side, no need response.

:::info
Packet `type` value is `3`
:::

```
 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| type=3|v|g|re.|    cmd_code   |            body_len           |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|  body_len     |               body(by body_len)               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
+                        nonce(optional)                        +
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
+                                                               +
|                                                               |
+                      signature(optional)                      +
|                                                               |
+                                                               +
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
```

Fields Descriptions:

| Field     | length in bit                         | Length in byte  | description                                                                                           |
| --------- | ------------------------------------- | --------------- | ----------------------------------------------------------------------------------------------------- |
| cmd_code  | 8                                     | 1               | Comand                                                                                                |
| body_len  | 24(uint32)                            | 3               | Then length of `body` in bytes. <br/> Max: 16 MB<br/> If gzip is enabled, the value is after compress |
| body      | Variable length, decide by `body_len` | variable length | `body`，max size: 16 MB                                                                               |
| nonce     | 64                                    | 8               | exists when `verify` is `1`                                                                           |
| signature | 128                                   | 16              | exists when `verify` is `1`                                                                           |

###### Parse Request Packet

Request packet is used for invoke apis: send api request and get api response.

:::info
Packet type is `1`
:::

Structure：

```
  0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| type=1|v|g|re.|    cmd_code   |           request_id          |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                               |            timeout            |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                    body_len                   |               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+               +
|                       body(by body_len)                       |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
+                        nonce(optional)                        +
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
+                                                               +
|                                                               |
+                      signature(optional)                      +
|                                                               |
+                                                               +
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

```

Fields Descriptions:

| Field      | Length in bit                         | Length in byte  | description                                                                                                |
| ---------- | ------------------------------------- | --------------- | ---------------------------------------------------------------------------------------------------------- |
| cmd_code   | 8                                     | 1               | Command                                                                                                    |
| request_id | 32(uint32)                            | 4               | Request id, it should be unique for one connection.<br/>Can start from 1, when reach 4294967295 start over |
| timeout    | 16(uint16)                            | 2               | `timeout` in millisecond <br/>max: 60000(60s)                                                              |
| body_len   | 24(uint32)                            | 3               | Then length of `body` in bytes. <br/> Max: 16 MB<br/> If gzip is enabled, the value is after compress      |
| body       | Variable length, decide by `body_len` | variable length | `body`，max size: 16 MB                                                                                    |
| nonce      | 64                                    | 8               | exists when `verify` is `1`                                                                                |
| signature  | 128                                   | 16              | exists when `verify` is `1`                                                                                |

:::info
Using specific protobuf defination to encode/decode body data
:::

###### Parse Response Packet

One peer need send back a response packet after receiving and handlding request packet.

:::info
Packet type is `2`
:::

## Structure

```
 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| type=2|v|g|re.|    cmd_code   |           request_id          |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                               |  status_code  |    body_len   |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|            body_len           |                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+                               +
|                       body(by body_len)                       |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
+                        nonce(optional)                        +
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
+                                                               +
|                                                               |
+                      signature(optional)                      +
|                                                               |
+                                                               +
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
```

Fields Descriptions:

| Field      | Length in bit                         | Length in byte  | description                                                                                           |
| ---------- | ------------------------------------- | --------------- | ----------------------------------------------------------------------------------------------------- |
| cmd_code   | 8                                     | 1               | Command                                                                                               |
| request_id | 32(uint32)                            | 4               | Request id, need to be same as request packet for pairing                                             |
| status     | 8(uint8)                              | 1               | status code: `0` - success; others show in [status code table](#status-code-table)                    |
| body_len   | 24(uint32)                            | 3               | Then length of `body` in bytes. <br/> Max: 16 MB<br/> If gzip is enabled, the value is after compress |
| body       | Variable length, decide by `body_len` | variable length | `body`，max size: 16 MB                                                                               |
| nonce      | 64                                    | 8               | exists when `verify` is `1`                                                                           |
| signature  | 128                                   | 16              | exists when `verify` is `1`                                                                           |

## Status Code Table

| value | flag                  | description                   |
| ----- | --------------------- | ----------------------------- |
| 0     | SUCCESS               | Success like HTTP status 200  |
| 1     | SERVER_TIMEOUT        | Timeout like HTTP status 408  |
| 3     | BAD_REQUEST           | Bad Request like HTTP 400     |
| 5     | UNAUTHENTICATED       | Unauthorized like HTTP 401    |
| 7     | SERVER_INTERNAL_ERROR | Internal server like HTTP 500 |

#### Socket


#### Data Commands

Socket Feed providers real-time stock quote data updates and trade updates.

And stock quote and order have difference endpoints, [check here](./hosts).

## Stock Quote Overview

<table>
    <tr>
        <td>Type</td>
        <td>Description</td>
    </tr>
    <tr>
        <td rowspan="20">Pull</td>
        <td><a href="../quote/pull/static">Get Basic Information Of Securities</a></td>
    </tr>
    <tr>
        <td><a href="../quote/pull/quote">Get Real-time Quotes Of Securities</a></td>
    </tr>
    <tr>
        <td><a href="../quote/pull/option-quote">Get Real-time Quotes Of Option Securities</a></td>
    </tr>
    <tr>
        <td><a href="../quote/pull/warrant-quote">Get Real-time Quotes Of Warrant Securities</a></td>
    </tr>
    <tr>
        <td><a href="../quote/pull/depth">Get Security Depth</a></td>
    </tr>
    <tr>
        <td><a href="../quote/pull/brokers">Get Security Brokers</a></td>
    </tr>
    <tr>
        <td><a href="../quote/pull/broker-ids">Get Broker IDs</a></td>
    </tr>
    <tr>
        <td><a href="../quote/pull/trade">Get Security Trades</a></td>
    </tr>
    <tr>
        <td><a href="../quote/pull/intraday">Get Security Intraday</a></td>
    </tr>
    <tr>
        <td><a href="../quote/pull/candlestick">Get Security Candlestick</a></td>
    </tr>
    <tr>
        <td><a href="../quote/pull/optionchain-date">Get Option Chain Expiry Date List</a></td>
    </tr>
    <tr>
        <td><a href="../quote/pull/optionchain-date-strike">Get Option Chain Info By Date</a></td>
    </tr>
    <tr>
        <td><a href="../quote/pull/issuer">Get Warrant Issuer IDs</a></td>
    </tr>
    <tr>
        <td><a href="../quote/pull/warrant-filter">Get Filtered Warrant</a></td>
    </tr>
    <tr>
        <td><a href="../quote/pull/trade-session">Get Trading Session Of The Day</a></td>
    </tr>
    <tr>
        <td><a href="../quote/pull/trade-day">Get Market Trading Days</a></td>
    </tr>
    <tr>
        <td><a href="../quote/pull/capital-flow-intraday">Get Security Capital Flow Intraday</a></td>
    </tr>
    <tr>
        <td><a href="../quote/pull/capital-distribution">Get Security Capital Distribution</a></td>
    </tr>
    <tr>
        <td><a href="../quote/pull/calc-index">Get Calculate Indexes Of Securities</a></td>
    </tr>
    <tr>
        <td><a href="../quote/pull/history-candlestick">Get Security History Candlestick</a></td>
    </tr>
    <tr>
        <td rowspan="3">Subscription</td>
        <td><a href="../quote/subscribe/subscription">Get Subscription Information</a></td>
    </tr>
    <tr>
        <td><a href="../quote/subscribe/subscribe">Subscribe Quote</a></td>
    </tr>
    <tr>
        <td><a href="../quote/subscribe/unsubscribe">Unsubscribe Quote</a></td>
    </tr>
    <tr>
        <td rowspan="4">Push</td>
        <td><a href="../quote/push/quote">Push Real-time Quote</a></td>
    </tr>
    <tr>
        <td><a href="../quote/push/depth">Push Real-time Depth</a></td>
    </tr>
    <tr>
        <td><a href="../quote/push/broker">Push Real-time Brokers</a></td>
    </tr>
    <tr>
        <td><a href="../quote/push/trade">Push Real-time Trades</a></td>
    </tr>
</table>

More detail can check [here](../quote/overview#quote-api-overview)

## Trade

| Type      | Functional                                                                                                     |
| --------- | -------------------------------------------------------------------------------------------------------------- |
| Subscribe | [Subscribe](../trade/trade-push#subscribe) <br/><br/> [Cancel Subscribe](../trade/trade-push#cancel-subscribe) |
| Notify    | [Notification](../trade/trade-push#notification)                                                               |

More detail check [here](../trade/trade-push)

#### Control commands

Control Commands are basic commands, using for create connection and keep connection alive.

Control Commands:

| cmd_code | description                                                                                |
| -------- | ------------------------------------------------------------------------------------------ |
| 0        | close - before server close the connection between client, server will send a close packet |
| 1        | heartbeat - keep connection alive                                                          |
| 2        | auth - auth connection                                                                     |
| 3        | reconnect - use session to auth                                                            |

## Close

:::info
Cmd：`0`
:::

Before server close the connection between client, server will send a close packet.

> close packet is push type packet, no need response

Cases server will close the connection:

1. heartbeat timeout
2. server internal error
3. server shutdown
4. client send invalid packet(can't parse by server)
5. auth failed
6. session expired when reconnect
7. duplicate connection have been created

The reason why server close the connection will send by close packet, protobuf defination:

```protobuf
message Close {
 enum Code {
   HeartbeatTimeout  = 0; // Heartbeat timeout
   ServerError       = 1; // Server internal error
   ServerShutdown    = 2; // Server shutdown
   UnpackError       = 3; // Server can't paser client packet
   AuthError         = 4; // Auth failed
   SessExpired       = 5; // Session expired
   ConnectDuplicate  = 6; // create duplicated connection
  }
  Code code = 1;
  string reason = 2;
}
```

## Heartbeat

:::info
Cmd：`1`
:::

Oner peer and send heartbeat to another peer to known health of another peer. Heartbeat do not limit body structure, one peer receive a heartbeat packet, only need send the `body` back.

> Heartbeat not only can keep connection alive, but also can detect latency of the network between two peers. One peer can set current timestamp in heartbeat body, when receive the response, use current timestamp minus timestamp in the body to get lantency of network.

```mermaid
sequenceDiagram
par peer-a to peer-b
peer-a -->> peer-b: heartbeat request, req_id: 1
peer-b -->> peer-a: heartbeat response, req_id: 1
end

par peer-b to peer-a
peer-b -->> peer-a: heartbeat request, req_id: 1
peer-a -->> peer-b: heartbeat response, req_id: 1
end
```

Example of heartbeat `body` ：

```protobuf
message Heartbeat {
  int64 timestamp = 1;
}
```

## Auth

:::info
Cmd：`2`
:::

Client need prove connection is legal. After handshake with server, client send auth packet as first packet.

```mermaid
sequenceDiagram
Client -->> Server: auth request, req_id: 1, token: xxx
Server -->> Client: auth response, req_id: 1, session: xxx

```

> Auth `token` can be created through [HTTP API](./socket-token-api)

After auth success, server will set session in auth response, client can use the session to reconnect and no need to request a new `token`.

Auth Request and Response protobuf:

```protobuf
message AuthRequest {
  string token = 1;
}

message AuthResponse {
  string session_id = 1;
  int64 expires = 2;
}
```

## Reconnect

:::info
Cmd：`3`
:::

After client disconnect from server, client can use session to reconnect to server when session is not expired. After reconnect success, server will set new session in reconnect response body.

Reconnect Request and Response:

```protobuf
message ReconnectRequest {
    string session_id = 1;
}

message ReconnectResponse {
  string session_id = 1;
  int64 expires = 2;
}
```

## Protobuf

All control command protobuf definations are opensource in [GitHub](https://github.com/longportapp/openapi-protobufs/blob/main/control/control.proto)

#### Access differences between WebSocket and TCP

LongPort support `WebSocket` and `TCP` feed, the differences:

- Data of `TCP` is streaming, so coding client is hard than `WebSocket`.
- `WebSocket` using URL Query to [Handshake](./protocol/handshake#websocket-how-to-handshake)
- `WebSocket` using [ping-pong](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#pings_and_pongs_the_heartbeat_of_websockets) to do Heartbeating, instead of sending heartbeat packet.
- `WebSocket` using `TLS` to secure connection, but `TCP` do not.

User can choice `TCP` or `WebSocket` on self demand.

> Advice: Using `WebSocket` first, it is more simple. If want more quick stock quote real-time pushing, using `TCP` to access stock quote gateway.

#### Endpoints

LongPort split Market Quote and Trading real-time pushing endpoints.

## Market Quote

| Endpoint                                 | Access Type |
| ---------------------------------------- | ----------- |
| tcp://openapi-quote.longportapp.com:2020 | TCP         |
| wss://openapi-quote.longportapp.com      | WebSocket   |

## Trading

| Endpoint                                 | Access Type |
| ---------------------------------------- | ----------- |
| tcp://openapi-trade.longportapp.com:2020 | TCP         |
| wss://openapi-trade.longportapp.com      | WebSocket   |

#### Subscribe Real-Time Market Data

:::success NOTE
Our OpenAPI SDK has fully implemented the function of subscribing to quotes, and you can use the SDK directly.

https://open.longportapp.com/sdk

The documentation in this chapter provides API details for your reference.
:::

Client can access market quote feed by `WebSocket` and `TCP`. After client subscribing stock quote, quote gateway can push real-time quote data to client.

:::info
WebSocket Endpoint: `wss://openapi-quote.longportapp.com`

TCP Endpoint: `openapi-quote.longportapp.com:2020`
:::

Flow：

```mermaid
sequenceDiagram
autonumber
Client ->> Server: Handshake
Server -->> Client: Establish connection
Client -->> Server: Auth request
Server -->> Client: Auth response

par Subscribe Market Quote
Client -->> Server: Subscribe request，req_id: 10, cmd: 6
Server -->> Client: Subscribe response，req_id: 10, cmd: 6

Server -->> Client: price pushing，cmd: 101
Server -->> Client: depth pushing，cmd: 102
Server -->> Client: broker pushing，cmd: 103
Server -->> Client: transaction pushing，cmd: 104

end

```

## Subscribe

Client can subscribe different quote type through subscribe commmand.

Subscribe command [protobuf defination](../quote/subscribe/subscribe)

Example:

```json
{
  "symbol": ["700.HK", "AAPL.US"]
  "sub_type": [1, 2]
  "is_first_push": true
}

```

> Here is `JSON` for easy showing case, actually need using protobuf encoding.

Client can also check quote topics already subscribing, [protobuf defination](../quote/subscribe/subscription).

After client success subscribing quote, server will push real-time quote data to client, data [protobuf defination](../quote/overview).

## Other Quote APIs

All quote all should be fetched by our quote gateway, more details can be found in [quote overview](../quote/overview).

## Feed Protocol

If you want subscribe quote data from socket, you must know more details of our [protocol](./protocol/overview)

#### Subscribe Real-Time Trading Data

Client can access trade feed by `WebSocket` and `TCP`. After client subscribing, trade gateway can push real-time trade changings of user.

:::info
WebSocket Endpoint: `wss://openapi-trade.longportapp.com`

TCP Endpoint: `openapi-trade.longportapp.com`
:::

Flow：

```mermaid
sequenceDiagram
autonumber
Client ->> Server: Handshake
Server -->> Client: Establish Connection
Client -->> Server: Auth Request
Server -->> Client: Auth Response

par Subscribe
Client -->> Server: Subscribe request，req_id: 10, cmd: 16
Server -->> Client: Subscribe response ，req_id: 10, cmd: 16

Server -->> Client: Push order updating，cmd: 18
Server -->> Client: Push order updating，cmd: 18

end

```

## Subscribe

Subscribe [protobuf defination](../trade/trade-push)

Example:

```json
{
  "topics": ["private"]
}
```

> Here is `JSON` for easy showing case, actually need using protobuf encoding.

## Pushing Example

```json
{
  "topic": "private",
  "content_type": 2,
  "dispatch_type": 1,
  "data": "eyJldmVudCI6Im9yZGVyX2NoYW5nZWRfbGIiLCJkYXRhIjp7InNpZGUiOiJCdXkiLCJzdG9ja19uYW1lIjoi6IW+6K6v5o6n6IKhIiwicXVhbnRpdHkiOiIxMDAwIiwic3ltYm9sIjoiNzAwLkhLIiwib3JkZXJfdHlwZSI6IkxPIiwicHJpY2UiOiIyMTMuMiIsImV4ZWN1dGVkX3F1YW50aXR5IjoiMTAwMCIsImV4ZWN1dGVkX3ByaWNlIjoiMjEzLjIiLCJvcmRlcl9pZCI6IjI3IiwiY3VycmVuY3kiOiJIS0QiLCJzdGF0dXMiOiJOZXdTdGF0dXMiLCJzdWJtaXR0ZWRfYXQiOiIxNTYyNzYxODkzIiwidXBkYXRlZF9hdCI6IjE1NjI3NjE4OTMiLCJ0cmlnZ2VyX3ByaWNlIjoiMjEzLjAiLCJtc2ciOiJJbnN1ZmZpY2llbnQgUXR5IC0gMTAwMCIsInRhZyI6IkdUQyIsInRyaWdnZXJfc3RhdHVzIjoiQUNUSVZFIiwidHJpZ2dlcl9hdCI6IjE1NjI3NjE4OTMiLCJ0YWlsaW5nX2Ftb3VudCI6IjUiLCJ0YWlsaW5nX3BlcmNlbnQiOiIxIiwibGltaXRfb2Zmc2V0IjoiMC4wMSIsImFjY291bnRfbm8iOiJISzEyMzQ0NSJ9fQ=="
}
```

:::info
`data` is binary(Base64) content of `JSON` string
:::

The real `JSON` format of `data`:

```json
{
  "event": "order_changed_lb",
  "data": {
    "side": "Buy",
    "stock_name": "Tecent",
    "quantity": "1000",
    "symbol": "700.HK",
    "order_type": "LO",
    "price": "213.2",
    "executed_quantity": "1000",
    "executed_price": "213.2",
    "order_id": "27",
    "currency": "HKD",
    "status": "NewStatus",
    "submitted_at": "1562761893",
    "updated_at": "1562761893",
    "trigger_price": "213.0",
    "msg": "Insufficient Qty - 1000",
    "tag": "GTC",
    "trigger_status": "ACTIVE",
    "trigger_at": "1562761893",
    "trailing_amount": "5",
    "trailing_percent": "1",
    "limit_offset": "0.01",
    "account_no": "HK123445",
    "last_share": "100",
    "last_price": "234",
    "remark": "abc"
  }
}
```

Field description is [here](../trade/trade-definition#websocket-push-notification)

## Feed Protocol

If you want subscribe trading data from socket, you must know more details of our [protocol](./protocol/overview)

## Qa


## Quote Releated

## Q1: How to calculate the subscription quote, is it one or more subscriptions if I both subscribe depth and broker with the same security?

A: The subscription quote is only calculated according to the security dimension, only one subscription will be calculted if you subscribe muilty quote type with one security.

## Q2: What is the specific limit logic for request frequency limit?

A: Use the token bucket to limit request and control the request rate. No more than 10 calls in 1 second, and no more than 5 concurrent requests.

## Q3: What is the available subscribing securities and corresponding symbol formats?

A: The security code uses the `ticker.region` format, `ticker` represents the code. Aavailable subscribing securities are as followes.

<table>
    <tr>
        <td>Market</td>
        <td>Symbol</td>
        <td>Ticker</td>
        <td>Region</td>
    </tr>
    <tr>
        <td rowspan="4">HK Market</td>
        <td>Securities (including equities, ETFs, Warrants, CBBCs)</td>
        <td>The official code of the security on the exchange</td>
        <td>HK</td>
    </tr>
    <tr>
        <td>Hang Seng Index</td>
        <td>HSI</td>
        <td>HK</td>
    </tr>
    <tr>
        <td>Hang Seng China Enterprises Index</td>
        <td>HSCEI</td>
        <td>HK</td>
    </tr>
    <tr>
        <td>Hang Seng TECH Index</td>
        <td>HSTECH</td>
        <td>HK</td>
    </tr>
    <tr>
        <td rowspan="3">US Market</td>
        <td>Securities (including stocks, ETFs)</td>
        <td>The official code of the security on the exchange</td>
        <td>US</td>
    </tr>
    <tr>
        <td>Nasdsaq Index</td>
        <td>.IXIC</td>
        <td>US</td>
    </tr>
    <tr>
        <td>Dow Jones Industrial Average</td>
        <td>.DJI</td>
        <td>US</td>
    </tr>
    <tr>
        <td rowspan="2">CN Market</td>
        <td>Securities (including stocks, ETFs)</td>
        <td>The official code of the security on the exchange</td>
        <td>SH or SZ</td>
    </tr>
    <tr>
        <td>Index</td>
        <td>The official code of the security on the exchange</td>
        <td>SH or SZ</td>
    </tr>
</table>

You can also use LongPort App to find the symbol of security
<img src="https://pub.pbkrs.com/files/202206/7CSoiaDR4wGZPNCT/20220629-180013.jpeg" className="max-w-2xl" />

## Q4: What is the quote authority of OpenAPI? How to buy quote cards?

A:

- Quote Authority
  In accordance with the rules of the exchange, the authority of OpenAPI are independent, and are not shared with App, PC, or Web permissions. For example, the Hong Kong stock Level 2 authority you have on the App cannot be used on the OpenAPI side. LongPort also presents basic market rights to OpenAPI users. If you need a higher-level market, you can activate the high-level quote authority by purchasing a market card through on-line Quote Store of brokers or LongPort.
- How to buy quote cards  
  LongPort users can choose the market cards they want to buy through the "Quote Store" in the LongPort App.

## Q5: Quote Change By Date Time

A:

- US Market: 09:20:00 EDT/EST
- HK Market: 08:50:00 CST
- CN Market: 09:00:00 CST
- SG Market: 08:20:00 CST

## Q6: How to enable Overnight quote

A:

- The night market quotation needs to be actively enabled by filling in the key `need_over_night_quote`, value `true` in the `metadata` field of the authentication interface.

```protobuf
message AuthRequest {
  string token = 1;
  map<string, string> metadata = 2;
}

message ReconnectRequest {
  string session_id = 1;
  map<string, string> metadata = 2;
}
```

- After turning on the night trading quotations, both the pull and push interfaces will be able to obtain the night trading quotations during the night trading period.

## Q7: Enable Overnight quote in OpenApi SDK

A:

- Create `Config` from environment variables

Set environment variable `LONGPORT_ENABLE_OVERNIGHT` to `true`

- Create `Config` object from constructor

```python
config = Config(app_key="your_app_key", app_secret="your_app_secret", access_token="your_access_token", enable_overnight=True)
```

## General

## Q1: Do I need to open a live account to call LongPort OpenAPI?

A: We provide a paper account, you can use it to complete the debugging of the OpenAPI quote and trading interfaces.

## Q2: How to open a paper account for debugging?

A: Please visit [Development Center](https://open.longportapp.com/account/) to enable the paper account and obtain the corresponding App Key & Secret and Access Token.

## Q3: Are the trading permissions for simulation debugging the same as for real accounts?

A: Quote is the same, trading might be different.

Paper accounts and live accounts share the same App Key & Secret, but have different Access Tokens. Quote permissions are associated with the App Key & Secret, while trading permissions are associated with the Access Token. Therefore, under paper accounts and live accounts, quote permissions are the same, but trading permissions are associated with the securities account and may differ.

## Q4: Which markets and types of securities are supported for quote and trading in paper account debugging?

A: Market: Supports real-time market data for Hong Kong stocks, US stocks, and A-share markets. For advanced market data such as full US market data and Hong Kong Level2 data, they can be purchased through the online market store and accessed via OpenAPI.

Trading: Supports trading of Hong Kong and US stocks, ETFs, and Hong Kong warrant trading. Short selling is supported for US stocks. OTC stocks, pre & post market trading, and options trading are not supported in paper accounts.

## Q5: Interface call frequency limits

A: Please visit [Rate Limit](docs/#rate-limit) for specific descriptions.

## Q6: How are interface call frequency limits applied in the case of multiple accounts?

A: If a customer holds multiple securities accounts, such as intraday financing or other sub-accounts, the trading interface call frequency limits are calculated and controlled based on different securities accounts, while quote interface calls are not affected by multiple accounts and are uniformly limited.

## Q7: Are there additional charges for trading operations through LongPort OpenAPI?

A: We do not charge additional fees for accessing market queries, trading, etc., via OpenAPI. For account-related fees such as trading commissions, platform fees, and market permissions, please refer to the information provided by the app and the official website.

## Trade

## Q1: What types of orders are supported?

A: Both paper and live accounts support regular Limit orders, Market orders, and Conditional orders (such as Buy if touched, Sell if touched, etc.), but do not currently support Attached orders and Grid orders.

## Q2: What are the trading hours for paper accounts?

A: Trading hours for paper accounts for Hong Kong stocks are the same as in the real environment. Trading pre & post market is not supported for U.S. stocks in the paper environment, only regular trading hours are supported.

## Q3: How can I trade overnight sessions for U.S. stocks?

A: To place orders for overnight trading, you can specify overnight trading by passing the OVERNIGHT value to the `outside_rth` parameter in the order placement API.

## Q4: What are the trading rules for paper accounts?

A: Paper accounts currently support trading in Hong Kong and U.S. stocks, ETFs, and Hong Kong warrants. Short selling is supported for U.S. stocks. However, OTC trading, pre & post market trading, and options trading are not supported in paper accounts.

Trades in the paper environment are matched based on the bid-ask spread from the real market. If the buy order price is higher than or equal to the ask price and the sell order price is lower than or equal to the bid price, a trade can be executed. Market orders are matched by default.

## Q5: How can I reset the funds in my paper account?

A: Manual resetting of demo funds is not supported at the moment. If needed, please contact your customer service or account manager for offline processing.

## Q6: After placing orders through the OpenAPI, how can I view them?

A: After placing orders through the OpenAPI, you can check the real-time status of orders by calling the order inquiry API. Alternatively, you can receive order update information through WebSocket push. You can also view orders and their statuses directly through the App/PC or other terminal products.

## Q7: How can I know if my account has sufficient funds for trading?

A: You can use the trading API `/v1/trade/estimate/buy_limit` to estimate the available cash & margin buying power, and short selling quantity in your account. Due to the complexity of risk control requirements, it's not recommended to calculate the tradable quantity manually.

## Q8: What does it mean when the order placement API returns "User authentication failed"?

A: This error usually indicates that the user does not have permission for the corresponding trading operation, such as options trading or short selling U.S. stocks. You can complete the permission opening process guided by the order placement in the app. After obtaining the necessary permissions, you can continue trading or performing other operations through OpenAPI.

## Quote


## Permissions

# Quote Permissions and Restrictions

<table>
    <thead>
    <tr>
        <th>Market</th>
        <th>Symbol</th>
    </tr>
    </thead>
    <tr>
        <td width="160" rowspan="2">HK Market</td>
        <td>Securities (including equities, ETFs, Warrants, CBBCs)</td>
    </tr>
    <tr>
        <td>Hang Seng Index</td>
    </tr>
    <tr>
        <td rowspan="3">US Market</td>
        <td>Securities (including stocks, ETFs)</td>
    </tr>
    <tr>
        <td>Nasdsaq Index</td>
    </tr>
    <tr>
        <td>OPRA Options</td>
    </tr>
    <tr>
        <td rowspan="2">CN Market</td>
        <td>Securities (including stocks, ETFs)</td>
    </tr>
    <tr>
        <td>Index</td>
    </tr>
</table>

## Rate Limiting

:::caution

- One account can only create one long link and subscribe to a maximum of 500 symbols at the same time
- No more than 10 calls in a 1-second interval and the number of concurrent requests should not exceed 5

:::

## Definition

## TradeStatus - Security Status

Security Status

| ID  | Description         |
| --- | ------------------- |
| 0   | Normal              |
| 1   | Suspension          |
| 2   | Delisted            |
| 3   | Fuse                |
| 4   | Papare List         |
| 5   | Code Moved          |
| 6   | To Be Opened        |
| 7   | Split Stock Halts   |
| 8   | Expired             |
| 9   | Warrant To BeListed |
| 10  | Suspend             |

### Protobuf

```protobuf
enum TradeStatus {
  NORMAL = 0;
  HALTED = 1;
  DELISTED = 2;
  FUSE = 3;
  PREPARE_LIST = 4;
  CODE_MOVED = 5;
  TO_BE_OPENED = 6;
  SPLIT_STOCK_HALTS = 7;
  EXPIRED = 8;
  WARRANT_PREPARE_LIST = 9;
  SUSPEND_TRADE = 10;
}
```

## TradeSession - Trading Session

Trading Session

| ID  | Description       |
| --- | ----------------- |
| 0   | Trading           |
| 1   | Pre-Tradeing      |
| 2   | Post-Tradeing     |
| 3   | OverNight-Trading |

### Protobuf

```protobuf
enum TradeSession {
  NORMAL_TRADE = 0;
  PRE_TRADE = 1;
  POST_TRADE = 2;
}
```

## Period - Candlestick Period

| ID   | Description        |
| ---- | ------------------ |
| 1    | One Minute         |
| 2    | Two Minutes        |
| 3    | Three Minutes      |
| 5    | Five Minutes       |
| 10   | Ten Minutes        |
| 15   | Fifteen Minutes    |
| 20   | Twenty Minutes     |
| 30   | Thirty Minutes     |
| 45   | Forty-five Minutes |
| 60   | Sixty Minutes      |
| 120  | Two Hours          |
| 180  | Three Hours        |
| 240  | Four Hours         |
| 1000 | One Days           |
| 2000 | One Week           |
| 3000 | One Month          |
| 3500 | One Quarter        |
| 4000 | One Year           |

### Protobuf

```protobuf
enum Period {
  UNKNOWN_PERIOD = 0;
  ONE_MINUTE = 1;
  FIVE_MINUTE = 5;
  FIFTEEN_MINUTE = 15;
  THIRTY_MINUTE = 30;
  SIXTY_MINUTE = 60;
  DAY = 1000;
  WEEK = 2000;
  MONTH = 3000;
  YEAR = 4000;
}
```

## AdjustType - Candlestick Adjustment Type

| ID  | Description    |
| --- | -------------- |
| 0   | Actual         |
| 1   | Adjust forward |

### Protobuf

```protobuf
enum AdjustType {
  NO_ADJUST = 0;
  FORWARD_ADJUST = 1;
}
```

## SubType - Quote Type Of Subscription

| ID  | Description |
| --- | ----------- |
| 1   | Quote       |
| 2   | Depth       |
| 3   | Broker      |
| 4   | Trade       |

### Protobuf

```protobuf
enum SubType {
  UNKNOWN_TYPE = 0;
  QUOTE = 1;
  DEPTH = 2;
  BROKERS = 3;
  TRADE = 4;
}
```

## CalcIndex - Calculate Index

| ID  | Description                        | Applicable Security Type |
| --- | ---------------------------------- | ------------------------ |
| 1   | Latest price                       | All                      |
| 2   | Change value                       | All                      |
| 3   | Change ratio                       | All                      |
| 4   | Volume                             | All                      |
| 5   | Turnover                           | All                      |
| 6   | Year-to-date change ratio          | Except Option, Warrant   |
| 7   | Turnover rate                      | Except Option, Warrant   |
| 8   | Total market value                 | Except Option, Warrant   |
| 9   | Capital flow                       | Except Option, Warrant   |
| 10  | Amplitude                          | Except Option, Warrant   |
| 11  | Volume ratio                       | Except Option, Warrant   |
| 12  | PE (TTM)                           | Except Option, Warrant   |
| 13  | PB                                 | Except Option, Warrant   |
| 14  | Dividend ratio (TTM)               | Except Option, Warrant   |
| 15  | Five days change ratio             | Except Option, Warrant   |
| 16  | Ten days change ratio              | Except Option, Warrant   |
| 17  | Half year change ratio             | Except Option, Warrant   |
| 18  | Five minutes change ratio          | Except Option, Warrant   |
| 19  | Expiry date                        | Only Option, Warrant     |
| 20  | Strike Price                       | Only Option, Warrant     |
| 21  | Upper bound price                  | Only Warrant             |
| 22  | Lower bound price                  | Only Warrant             |
| 23  | Outstanding quantity               | Only Warrant             |
| 24  | Outstanding ratio                  | Only Warrant             |
| 25  | Premium                            | Only Option, Warrant     |
| 26  | In/out of the bound                | Only Warrant             |
| 27  | Implied volatility                 | Only Option, Warrant     |
| 28  | Warrant delta                      | Only Warrant             |
| 29  | Call price                         | Only Warrant             |
| 30  | Price interval from the call price | Only Warrant             |
| 31  | Effective leverage                 | Only Warrant             |
| 32  | Leverage ratio                     | Only Warrant             |
| 33  | Conversion ratio                   | Only Warrant             |
| 34  | Breakeven point                    | Only Warrant             |
| 35  | Open interest                      | Only Option              |
| 36  | Delta                              | Only Option              |
| 37  | Gamma                              | Only Option              |
| 38  | Theta                              | Only Option              |
| 39  | Vega                               | Only Option              |
| 40  | Rho                                | Only Option              |

### Protobuf

```protobuf
enum CalcIndex {
  CALCINDEX_UNKNOWN = 0;
  CALCINDEX_LAST_DONE = 1;
  CALCINDEX_CHANGE_VAL = 2;
  CALCINDEX_CHANGE_RATE = 3;
  CALCINDEX_VOLUME = 4;
  CALCINDEX_TURNOVER = 5;
  CALCINDEX_YTD_CHANGE_RATE = 6;
  CALCINDEX_TURNOVER_RATE = 7;
  CALCINDEX_TOTAL_MARKET_VALUE = 8;
  CALCINDEX_CAPITAL_FLOW = 9;
  CALCINDEX_AMPLITUDE = 10;
  CALCINDEX_VOLUME_RATIO = 11;
  CALCINDEX_PE_TTM_RATIO = 12;
  CALCINDEX_PB_RATIO = 13;
  CALCINDEX_DIVIDEND_RATIO_TTM = 14;
  CALCINDEX_FIVE_DAY_CHANGE_RATE = 15;
  CALCINDEX_TEN_DAY_CHANGE_RATE = 16;
  CALCINDEX_HALF_YEAR_CHANGE_RATE = 17;
  CALCINDEX_FIVE_MINUTES_CHANGE_RATE = 18;
  CALCINDEX_EXPIRY_DATE = 19;
  CALCINDEX_STRIKE_PRICE = 20;
  CALCINDEX_UPPER_STRIKE_PRICE = 21;
  CALCINDEX_LOWER_STRIKE_PRICE = 22;
  CALCINDEX_OUTSTANDING_QTY = 23;
  CALCINDEX_OUTSTANDING_RATIO = 24;
  CALCINDEX_PREMIUM = 25;
  CALCINDEX_ITM_OTM = 26;
  CALCINDEX_IMPLIED_VOLATILITY = 27;
  CALCINDEX_WARRANT_DELTA = 28;
  CALCINDEX_CALL_PRICE = 29;
  CALCINDEX_TO_CALL_PRICE = 30;
  CALCINDEX_EFFECTIVE_LEVERAGE = 31;
  CALCINDEX_LEVERAGE_RATIO = 32;
  CALCINDEX_CONVERSION_RATIO = 33;
  CALCINDEX_BALANCE_POINT = 34;
  CALCINDEX_OPEN_INTEREST = 35;
  CALCINDEX_DELTA = 36;
  CALCINDEX_GAMMA = 37;
  CALCINDEX_THETA = 38;
  CALCINDEX_VEGA = 39;
  CALCINDEX_RHO = 40;
}
```

## Board - Security Board

| Board            | Description                                   |
| ---------------- | --------------------------------------------- |
| USMain           | US Main Board                                 |
| USPink           | US Pink Board                                 |
| USDJI            | Dow Jones Industrial Average                  |
| USNSDQ           | Nasdsaq Index                                 |
| USSector         | US Industry Board                             |
| USOption         | US Option                                     |
| USOptionS        | US Sepecial Option (market closed at 4:15 pm) |
| HKEquity         | Hong Kong Equity Securities                   |
| HKPreIPO         | HK PreIPO Security                            |
| HKWarrant        | HK Warrant                                    |
| HKHS             | Hang Seng Index                               |
| HKSector         | HK Industry Board                             |
| SHMainConnect    | SH Main Board(Connect)                        |
| SHMainNonConnect | SH Main Board(Non Connect)                    |
| SHSTAR           | SH Science and Technology Innovation Board    |
| CNIX             | CN Index                                      |
| CNSector         | CN Industry Board                             |
| SZMainConnect    | SZ Main Board(Connect)                        |
| SZMainNonConnect | SZ Main Board(Non Connect)                    |
| SZGEMConnect     | SZ Gem Board(Connect)                         |
| SZGEMNonConnect  | SZ Gem Board(Non Connect)                     |
| SGMain           | SG Main Board                                 |
| STI              | Singapore Straits Index                       |
| SGSector         | SG Industry Board                             |

## Overview

# Quote API Overview

<table>
    <tr>
        <td>Type</td>
        <td>Description</td>
    </tr>
    <tr>
        <td rowspan="20">Pull</td>
        <td><a href="./pull/static">Get Basic Information Of Securities</a></td>
    </tr>
    <tr>
        <td><a href="./pull/quote">Get Real-time Quotes Of Securities</a></td>
    </tr>
    <tr>
        <td><a href="./pull/option-quote">Get Real-time Quotes Of Option Securities</a></td>
    </tr>
    <tr>
        <td><a href="./pull/warrant-quote">Get Real-time Quotes Of Warrant Securities</a></td>
    </tr>
    <tr>
        <td><a href="./pull/depth">Get Security Depth</a></td>
    </tr>
    <tr>
        <td><a href="./pull/brokers">Get Security Brokers</a></td>
    </tr>
    <tr>
        <td><a href="./pull/broker-ids">Get Broker IDs</a></td>
    </tr>
    <tr>
        <td><a href="./pull/trade">Get Security Trades</a></td>
    </tr>
    <tr>
        <td><a href="./pull/intraday">Get Security Intraday</a></td>
    </tr>
    <tr>
        <td><a href="./pull/candlestick">Get Security Candlestick</a></td>
    </tr>
    <tr>
        <td><a href="./pull/optionchain-date">Get Option Chain Expiry Date List</a></td>
    </tr>
    <tr>
        <td><a href="./pull/optionchain-date-strike">Get Option Chain Info By Date</a></td>
    </tr>
    <tr>
        <td><a href="./pull/issuer">Get Warrant Issuer IDs</a></td>
    </tr>
    <tr>
        <td><a href="./pull/warrant-filter">Get Filtered Warrant</a></td>
    </tr>
    <tr>
        <td><a href="./pull/trade-session">Get Trading Session Of The Day</a></td>
    </tr>
    <tr>
        <td><a href="./pull/trade-day">Get Market Trading Days</a></td>
    </tr>
    <tr>
        <td><a href="./pull/capital-flow-intraday">Get Security Capital Flow Intraday</a></td>
    </tr>
    <tr>
        <td><a href="./pull/capital-distribution">Get Security Capital Distribution</a></td>
    </tr>
    <tr>
        <td><a href="./pull/calc-index">Get Calculate Indexes Of Securities</a></td>
    </tr>
    <tr>
        <td><a href="./pull/history-candlestick">Get Security History Candlestick</a></td>
    </tr>
    <tr>
        <td rowspan="3">Subscription</td>
        <td><a href="./subscribe/subscription">Get Subscription Information</a></td>
    </tr>
    <tr>
        <td><a href="./subscribe/subscribe">Subscribe Quote</a></td>
    </tr>
    <tr>
        <td><a href="./subscribe/unsubscribe">Unsubscribe Quote</a></td>
    </tr>
    <tr>
        <td rowspan="4">Push</td>
        <td><a href="./push/quote">Push Real-time Quote</a></td>
    </tr>
    <tr>
        <td><a href="./push/depth">Push Real-time Depth</a></td>
    </tr>
    <tr>
        <td><a href="./push/broker">Push Real-time Brokers</a></td>
    </tr>
    <tr>
        <td><a href="./push/trade">Push Real-time Trades</a></td>
    </tr>
    <tr>
        <td rowspan="4">Individual</td>
        <td><a href="./individual/watchlist_create_group">Create watched group</a></td>
    </tr>
    <tr>
        <td><a href="./individual/watchlist_delete_group">Delete watched group</a></td>
    </tr>
    <tr>
        <td><a href="./individual/watchlist_groups">Get watched groups</a></td>
    </tr>
    <tr>
        <td><a href="./individual/watchlist_update_group">Update watched group</a></td>
    </tr>
    <tr>
        <td rowspan="1">Security</td>
        <td><a href="./security/security_list">Get Security List</a></td>
    </tr>
</table>

## Description Of Security Code

The security code uses the `ticker.region` format, `ticker` represents the code, and example for each market:

- US Market: `region` is `US`, for example: `AAPL.US`.
- HK Market: `region` is `HK`, for example: `700.HK`.
- CN Market: `region` is `SH` for Shanghai Stock Exchange and `SZ` for Shenzhen Stock Exchange, for example: `399001.SZ`, `600519.SH`.
- SG Market: `region` is `SG`, for example: `D05.SG`.

## Access Method

1. Use private protocol and long connection mode to access, please refer to <a href="../socket/protocol/overview" target="_blank">Binary Communication Protocol</a> for access method.
2. Use SDK for access, [SDK introduction and download address](https://open.longportapp.com/sdk).

## Business Data Serialization

The market request, response and push data are stored as business data in the body part of the data package of the private protocol.
We use the [Protobuf](https://developers.google.cn/protocol-buffers) protocol to serialize business data. Compared with common text protocols (such as JSON, XML, etc.), the Protobuf protocol has the following advantages:

- Faster serialization time.
- Smaller packet size.
- Strongger version forward and backward compatibility.

Quote Protobuf protocol document [download link](https://github.com/longportapp/openapi-protobufs/blob/main/quote/api.proto).

### Individual


### Create watched group

Create watched group


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.create_watchlist_group](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.create_watchlist_group) |
| JavaScript | [QuoteContext.create_watchlist_group](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#create_watchlist_group) |
| Rust | [QuoteContext::create_watchlist_group](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.create_watchlist_group) |
| Go | [QuoteContext.Create_watchlist_group](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Create_watchlist_group) |
| Java | [QuoteContext.getCreate_watchlist_group](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getCreate_watchlist_group) |

## 

## Request

<table className="http-basic">
<tbody>
<tr><td className="http-basic-key">HTTP Method</td><td>POST</td></tr>
<tr><td className="http-basic-key">HTTP URL</td><td>/v1/watchlist/groups 
</td></tr>
</tbody>
</table>

### Parameters

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

| Name | Type | Required | Description |
|---|---|---|---|
| name | string | YES | Group name, for example `Information Technology Group`.  |
| securities | string[] | NO | Security list, for example `["BABA.US", "AAPL.US"]`. Display order of securities in the group, in the same order as this list. If this parameter is not passed, create an empty group.  |

### Request Example

```python
from longport.openapi import QuoteContext, Config

config = Config.from_env()
ctx = QuoteContext(config)
group_id = ctx.create_watchlist_group(name = "Watchlist1", securities = ["700.HK", "AAPL.US"])
print(group_id)
```

## Response

### Response Headers

- Content-Type: application/json

### Response Example

```json
{
  "code": 0,
  "data": {
    "id": 10086
  }
}
```

### Response Status

| Status | Description | Schema |
|---|---|---|
| 200 | Success | [create_group_response](#schemacreate_group_response) |
| 500 | Internal error | None |

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

## Schemas

### create_group_response

<a id="schemacreate_group_response"></a>
<a id="schemacreate_group_response"></a>

|Name|Type|Required|Description|
|---|---|---|---|
|id|integer|false|Group ID|

### Delete watched group

Delete watched group


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.delete_watchlist_group](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.delete_watchlist_group) |
| JavaScript | [QuoteContext.delete_watchlist_group](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#delete_watchlist_group) |
| Rust | [QuoteContext::delete_watchlist_group](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.delete_watchlist_group) |
| Go | [QuoteContext.Delete_watchlist_group](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Delete_watchlist_group) |
| Java | [QuoteContext.getDelete_watchlist_group](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getDelete_watchlist_group) |

## 

## Request

<table className="http-basic">
<tbody>
<tr><td className="http-basic-key">HTTP Method</td><td>DELETE</td></tr>
<tr><td className="http-basic-key">HTTP URL</td><td>/v1/watchlist/groups 
</td></tr>
</tbody>
</table>

### Parameters

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

| Name | Type | Required | Description |
|---|---|---|---|
| id | integer | YES | Group ID, for example `10086`.  |
| purge | boolean | YES | Whether to clear the securities in the group. If set to `true`, the securities in the group will be unfollowed. If set to `false`, the securities in the group will remain in the `All` group.  |

### Request Example

```python
from longport.openapi import QuoteContext, Config

config = Config.from_env()
ctx = QuoteContext(config)
ctx.delete_watchlist_group(10086)
```

## Response

### Response Headers

- Content-Type: application/json

### Response Example

```json
{
  "code": 0
}
```

### Response Status

| Status | Description | Schema |
|---|---|---|
| 200 | Success | None |
| 500 | Internal error | None |

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

### Get watched groups

Get watched groups


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.watchlist](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.watchlist) |
| JavaScript | [QuoteContext.watchlist](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#watchlist) |
| Rust | [QuoteContext::watchlist](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.watchlist) |
| Go | [QuoteContext.Watchlist](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Watchlist) |
| Java | [QuoteContext.getWatchlist](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getWatchlist) |

## 

## Request

<table className="http-basic">
<tbody>
<tr><td className="http-basic-key">HTTP Method</td><td>GET</td></tr>
<tr><td className="http-basic-key">HTTP URL</td><td>/v1/watchlist/groups 
</td></tr>
</tbody>
</table>

### Request Example

```python
from longport.openapi import QuoteContext, Config

config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.watchlist()
print(resp)
```

## Response

### Response Headers

- Content-Type: application/json

### Response Example

```json
{
  "code": 0,
  "data": {
    "groups": [
      {
        "id": 28020,
        "name": "all",
        "securities": [
          {
            "symbol": "700.HK",
            "market": "HK",
            "name": "Tencent",
            "watched_price": "364.4",
            "watched_at": 1652855022
          }
        ]
      }
    ]
  }
}
```

### Response Status

| Status | Description | Schema |
|---|---|---|
| 200 | Success | [groups_response](#schemagroups_response) |
| 500 | Internal error | None |

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

## Schemas

### groups_response

<a id="schemagroups_response"></a>
<a id="schemagroups_response"></a>

|Name|Type|Required|Description|
|---|---|---|---|
|groups|object[]|false|Groups|
|∟ id|integer|true|Group ID|
|∟ name|string|true|Name|
|∟ securities|object[]|true|Security|
|∟∟ symbol|string|true|Symbol|
|∟∟ market|string|true|Market|
|∟∟ name|string|true|Name|
|∟∟ watched_price|string|true|Watched price|
|∟∟ watched_at|integer|true|Watched time|

### Update watched group

Update watched group


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.update_watchlist_group](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.update_watchlist_group) |
| JavaScript | [QuoteContext.update_watchlist_group](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#update_watchlist_group) |
| Rust | [QuoteContext::update_watchlist_group](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.update_watchlist_group) |
| Go | [QuoteContext.Update_watchlist_group](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Update_watchlist_group) |
| Java | [QuoteContext.getUpdate_watchlist_group](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getUpdate_watchlist_group) |

## 

## 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/watchlist/groups 
</td></tr>
</tbody>
</table>

### Parameters

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

| Name | Type | Required | Description |
|---|---|---|---|
| id | integer | YES | Group ID, for example `10086`.  |
| name | string | NO | Group name, for example `Information Technology Group`. <br /> If this parameter is not passed, the group name will not be updated.  |
| securities | string[] | NO | Security list, for example `["BABA.US", "AAPL.US"]`.<br /> Combined with the `mode` parameter below, it can be used to add securities, remove securities, and sort the watchlist.  |
| mode | string | NO | Operation method<br /> **optional values:**<br /> `add` - Add securities<br /> `remove` - Remove securities<br /> `replace` - Update securities<br /><br /> When selecting `add`, the securities in the above list will be added to this group in order.<br /><br /> When selecting `remove`, the securities in the above list will be removed from this group.<br /><br /> When selecting `update`, the securities in the above list will completely replace the securities in this group.<br /> For example, if the original group contains `APPL.US, BABA.US, TSLA.US`, and it is updated with `["BABA.US", "AAPL.US", "MSFT.US"]`, it will become `BABA.US, AAPL.US, MSFT.US`, removing `TSLA.US` and adding `MSFT.US`, while adjusting the order of `BABA.US and AAPL.US`. |

### Request Example

```python
from longport.openapi import QuoteContext, Config, SecuritiesUpdateMode

config = Config.from_env()
ctx = QuoteContext(config)
ctx.update_watchlist_group(10086, name = "Watchlist2", securities = ["700.HK", "AAPL.US"], SecuritiesUpdateMode.Replace)
```

## Response

### Response Headers

- Content-Type: application/json

### Response Example

```json
{
  "code": 0
}
```

### Response Status

| Status | Description | Schema |
|---|---|---|
| 200 | Success | None |
| 500 | Internal error | None |

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

### Pull


### Get Broker IDs

This API is used to obtain participant IDs data (which can be synchronized once a day).


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.participants](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.participants) |
| JavaScript | [QuoteContext.participants](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#participants) |
| Rust | [QuoteContext::participants](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.participants) |
| Go | [QuoteContext.Participants](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Participants) |
| Java | [QuoteContext.getParticipants](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getParticipants) |

:::info
[Business Command](../../socket/biz-command): `16`
:::

## Request

### Request Example

```python
# Get Broker IDs
# https://open.longportapp.com/docs/quote/pull/broker-ids
# Before running, please visit the "Developers to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from longport.openapi import QuoteContext, Config

config = Config.from_env()
ctx = QuoteContext(config)

resp = ctx.participants()
print(resp)
```

## Response

### Response Properties

| Name                       | Type     | Description              |
| -------------------------- | -------- | ------------------------ |
| participant_broker_numbers | object[] | participant data         |
| ∟ broker_ids               | int32[]  | broker IDs               |
| ∟ participant_name_cn      | string   | participant name (zh-CN) |
| ∟ participant_name_en      | string   | participant name (en)    |
| ∟ participant_name_hk      | string   | participant name (zh-HK) |

### Protobuf

```protobuf
message ParticipantBrokerIdsResponse {
  repeated ParticipantInfo participant_broker_numbers = 1;
}

message ParticipantInfo {
  repeated int32 broker_ids = 1;
  string participant_name_cn = 2;
  string participant_name_en = 3;
  string participant_name_hk = 4;
}
```

### Response JSON Example

```json
{
  "participant_broker_numbers": [
    {
      "broker_ids": [7738, 7739],
      "participant_name_cn": "华兴金融 (香港)",
      "participant_name_en": "China Renaissance(HK)",
      "participant_name_hk": "華興金融 (香港)"
    },
    {
      "broker_ids": [6390, 6396, 6398, 6399],
      "participant_name_cn": "国信 (香港)",
      "participant_name_en": "Guosen(HK)",
      "participant_name_hk": "國信 (香港)"
    },
    {
      "broker_ids": [3168, 3169],
      "participant_name_cn": "泰嘉",
      "participant_name_en": "Tiger",
      "participant_name_hk": "泰嘉"
    }
  ]
}
```

## Error Code

| Proto Error Code | Business Error Code | Descrption         | Troubleshooting Suggestions                                   |
| ---------------- | ------------------- | ------------------ | ------------------------------------------------------------- |
| 3                | 301600              | Invalid request    | Invalid request parameters or unpacking request failed        |
| 3                | 301606              | Request rate limit | Reduce the frequency of requests                              |
| 7                | 301602              | Server error       | Please try again or contact a technician to resolve the issue |

### Get Security Brokers

This API is used to obtain the real-time broker queue data of security.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.brokers](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.brokers) |
| JavaScript | [QuoteContext.brokers](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#brokers) |
| Rust | [QuoteContext::brokers](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.brokers) |
| Go | [QuoteContext.Brokers](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Brokers) |
| Java | [QuoteContext.getBrokers](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getBrokers) |

:::info
[Business Command](../../socket/biz-command): `15`
:::

## Request

### Parameters

| Name   | Type   | Required | Description                                                     |
| ------ | ------ | -------- | --------------------------------------------------------------- |
| symbol | string | Yes      | Security code, in `ticker.region` format, for example: `700.HK` |

### Protobuf

```protobuf
message SecurityRequest {
  string symbol = 1;
}
```

### Request Example

```python
# 获取标的经纪队列
# https://open.longportapp.com/docs/quote/pull/brokers
# Before running, please visit the "Developers to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from longport.openapi import QuoteContext, Config

config = Config.from_env()
ctx = QuoteContext(config)

resp = ctx.brokers("700.HK")
print(resp)
```

## Response

### Response Properties

| Name         | Type     | Description                                                        |
| ------------ | -------- | ------------------------------------------------------------------ |
| symbol       | string   | Security code                                                      |
| ask_brokers  | object[] | Ask brokers                                                        |
| ∟ position   | int32    | Position                                                           |
| ∟ broker_ids | int32[]  | Broker IDs, obtained through the[Get Broker IDs ](./broker-ids)API |
| bid_brokers  | object[] | Bid brokers                                                        |
| ∟ position   | int32    | Postition                                                          |
| ∟ broker_ids | int32[]  | Broker IDs, obtained through the[Get Broker IDs ](./broker-ids)API |

### Protobuf

```protobuf
message SecurityBrokersResponse {
  string symbol = 1;
  repeated Brokers ask_brokers = 2;
  repeated Brokers bid_brokers = 3;
}

message Brokers {
  int32 position = 1;
  repeated int32 broker_ids = 2;
}
```

### Response JSON Example

```json
{
  "symbol": "700.HK",
  "ask_brokers": [
    {
      "position": 1,
      "broker_ids": [7358, 9057, 9028, 7364]
    },
    {
      "position": 2,
      "broker_ids": [6968, 3448, 3348, 1049, 4973, 6997, 3448, 5465, 6997]
    }
  ],
  "bid_brokers": [
    {
      "position": 1,
      "broker_ids": [6996, 5465, 8026, 8304, 4978]
    },
    {
      "position": 2
    }
  ]
}
```

## Error Code

| Protocol Error Code | Business Error Code | Description        | Troubleshooting Suggestions                                   |
| ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- |
| 3                   | 301600              | Invalid request    | Invalid request parameters or unpacking request failed        |
| 3                   | 301606              | Request rate limit | Reduce the frequency of requests                              |
| 7                   | 301602              | Server error       | Please try again or contact a technician to resolve the issue |
| 7                   | 301600              | Symbol not found   | Check that the requested `symbol` is correct                  |
| 7                   | 301603              | No quotes          | Security no quote                                             |
| 7                   | 301604              | No access          | No access to security quote                                   |

### Get Calculate Indexes Of Securities

This API is used to obtain the calculate indexes of securities.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.calc_indexes](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.calc_indexes) |
| JavaScript | [QuoteContext.calc_indexes](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#calc_indexes) |
| Rust | [QuoteContext::calc_indexes](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.calc_indexes) |
| Go | [QuoteContext.CalcIndex](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.CalcIndex) |
| Java | [QuoteContext.getCalc_indexes](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getCalc_indexes) |

:::info
[Business Command](../../socket/biz-command)：`26`
:::

## Request

### Parameters

| Name       | Type     | Required | Description                                                                                                                                                     |
| ---------- | -------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbols    | string[] | Yes      | Security code list, in `ticker.region` format, for example: `[700.HK]` <br /><br />**Check rules:**<br />The maximum number of symbols in each request is `500` |
| calc_index | init32[] | Yes      | Calc indexes, for example: `[1,2,3]`, see [CalcIndex](../objects#calcindex---calculate-index)                                                                   |

### Protobuf

```protobuf
message SecurityCalcQuoteRequest {
  repeated string symbols = 1;
  repeated CalcIndex calc_index = 2;
}
```

### Request Example

```python
# Get Security Calc Index
# https://open.longportapp.com/docs/quote/pull/calc-index
# Before running, please visit the "Developers to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
```

## Response

### Response Properties

| Name                       | Type     | Description                                                                              |
| -------------------------- | -------- | ---------------------------------------------------------------------------------------- |
| security_calc_index        | object[] | Security Index Data                                                                      |
| ∟ symbol                   | string   | Security code                                                                            |
| ∟ last_done                | string   | Latest price                                                                             |
| ∟ change_val               | string   | Change value                                                                             |
| ∟ change_rate              | string   | Change ratio (This field is a ratio field, not include symbol `%`)                       |
| ∟ volume                   | int64    | Volume                                                                                   |
| ∟ turnover                 | string   | Turnover                                                                                 |
| ∟ ytd_change_rate          | string   | Year-to-date change ratio (This field is a ratio field, not include symbol `%`)          |
| ∟ turnover_rate            | string   | Turnover rate (This field is a ratio field, not include symbol `%`)                      |
| ∟ total_market_value       | string   | Total market value                                                                       |
| ∟ capital_flow             | string   | Capital flow                                                                             |
| ∟ amplitude                | string   | Amplitude (This field is a ratio field, not include symbol `%`)                          |
| ∟ volume_ratio             | string   | Volume ratio                                                                             |
| ∟ pe_ttm_ratio             | string   | PE (TTM)                                                                                 |
| ∟ pb_ratio                 | string   | PB                                                                                       |
| ∟ dividend_ratio_ttm       | string   | Dividend ratio (TTM)                                                                     |
| ∟ five_day_change_rate     | string   | Five days change ratio (This field is a ratio field, not include symbol `%`)             |
| ∟ ten_day_change_rate      | string   | Ten days change ratio (This field is a ratio field, not include symbol `%`)              |
| ∟ half_year_change_rate    | string   | Half year change ratio (This field is a ratio field, not include symbol `%`)             |
| ∟ five_minutes_change_rate | string   | Five minutes change ratio (This field is a ratio field, not include symbol `%`)          |
| ∟ expiry_date              | string   | Expirt date                                                                              |
| ∟ strike_price             | string   | Strike price                                                                             |
| ∟ upper_strike_price       | string   | Upper bound price                                                                        |
| ∟ lower_strike_price       | string   | Lower bound price                                                                        |
| ∟ outstanding_qty          | int64    | Outstanding quantity                                                                     |
| ∟ outstanding_ratio        | string   | Outstanding ratio (This field is a ratio field, not include symbol `%`)                  |
| ∟ premium                  | string   | Premium (This field is a ratio field, not include symbol `%`)                            |
| ∟ itm_otm                  | string   | In/out of the bound (This field is a ratio field, not include symbol `%`)                |
| ∟ implied_volatility       | string   | Implied volatility (This field is a ratio field, not include symbol `%`)                 |
| ∟ warrant_delta            | string   | Warrant delta                                                                            |
| ∟ call_price               | string   | Call price                                                                               |
| ∟ to_call_price            | string   | Price interval from the call price (This field is a ratio field, not include symbol `%`) |
| ∟ effective_leverage       | string   | Effective leverage                                                                       |
| ∟ leverage_ratio           | string   | Leverage ratio                                                                           |
| ∟ conversion_ratio         | string   | Conversion ratio                                                                         |
| ∟ balance_point            | string   | Breakeven point                                                                          |
| ∟ open_interest            | int64    | Open interest                                                                            |
| ∟ delta                    | string   | Delta                                                                                    |
| ∟ gamma                    | string   | Gamma                                                                                    |
| ∟ theta                    | string   | Theta                                                                                    |
| ∟ vega                     | string   | Vega                                                                                     |
| ∟ rho                      | string   | Rho                                                                                      |

### Protobuf

```protobuf
message SecurityCalcIndex {
  string symbol = 1;
  string last_done = 2;
  string change_val = 3;
  string change_rate = 4;
  int64 volume = 5;
  string turnover = 6;
  string ytd_change_rate = 7;
  string turnover_rate = 8;
  string total_market_value = 9;
  string capital_flow = 10;
  string amplitude = 11;
  string volume_ratio = 12;
  string pe_ttm_ratio = 13;
  string pb_ratio = 14;
  string dividend_ratio_ttm = 15;
  string five_day_change_rate = 16;
  string ten_day_change_rate = 17;
  string half_year_change_rate = 18;
  string five_minutes_change_rate = 19;
  string expiry_date = 20;
  string strike_price = 21;
  string upper_strike_price = 22;
  string lower_strike_price = 23;
  int64  outstanding_qty = 24;
  string outstanding_ratio = 25;
  string premium = 26;
  string itm_otm = 27;
  string implied_volatility = 28;
  string warrant_delta = 29;
  string call_price = 30;
  string to_call_price = 31;
  string effective_leverage = 32;
  string leverage_ratio = 33;
  string conversion_ratio = 34;
  string balance_point = 35;
  int64 open_interest = 36;
  string delta = 37;
  string gamma = 38;
  string theta = 39;
  string vega = 40;
  string rho = 41;
}

message SecurityCalcQuoteResponse {
  repeated SecurityCalcIndex security_calc_index = 1;
}
```

### Response JSON Example

```json
{
  "securityCalcIndex": [
    {
      "symbol": "AAPL.US",
      "lastDone": "131.880",
      "changeVal": "-5.2500",
      "changeRate": "-3.83",
      "volume": "122207099",
      "turnover": "16269088361.000",
      "ytdChangeRate": "-25.63",
      "turnoverRate": "0.76",
      "totalMarketValue": "2134501670280.00",
      "capitalFlow": "14664053535.556",
      "amplitude": "2.74",
      "volumeRatio": "3.22",
      "peTtmRatio": "21.26",
      "pbRatio": "31.71",
      "dividendRatioTtm": "0.64",
      "fiveDayChangeRate": "-9.76",
      "tenDayChangeRate": "-11.87",
      "halfYearChangeRate": "-7.01",
      "fiveMinutesChangeRate": "0.00"
    },
    {
      "symbol": "69672.HK",
      "lastDone": "0.010",
      "changeRate": "0.00",
      "expiryDate": "20221024",
      "strikePrice": "379.880",
      "outstandingQty": "6090000",
      "outstandingRatio": "7.61",
      "premium": "0.67",
      "itmOtm": "0.65",
      "callPrice": "375.880",
      "toCallPrice": "-100.00",
      "leverageRatio": "75.48",
      "balancePoint": "374.880"
    },
    {
      "symbol": "AAPL220617C137000.US",
      "lastDone": "1.17",
      "changeVal": "-2.04",
      "changeRate": "-63.55",
      "volume": "23499",
      "turnover": "3903660.00",
      "expiryDate": "20220617",
      "strikePrice": "137.00",
      "premium": "11709.40",
      "impliedVolatility": "43.54",
      "openInterest": "5210",
      "delta": "0.263",
      "gamma": "0.043",
      "theta": "-1.266",
      "vega": "5.660",
      "rho": "0.580"
    },
    {
      "symbol": "HSI.HK",
      "lastDone": "21119.650",
      "changeVal": "52.070",
      "changeRate": "0.25",
      "volume": "96449546281",
      "turnover": "96449546281.000",
      "ytdChangeRate": "-9.74",
      "amplitude": "1.86",
      "volumeRatio": "0.59",
      "fiveDayChangeRate": "-1.91",
      "tenDayChangeRate": "-0.02",
      "halfYearChangeRate": "-11.83",
      "fiveMinutesChangeRate": "0.00"
    }
  ]
}
```

## Error Code

| Protocol Error Code | Business Error Code | Description              | Troubleshooting Suggestions                                   |
| ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- |
| 3                   | 301600              | Invalid request          | Invalid request parameters or unpacking request failed        |
| 3                   | 301606              | Request rate limit       | Reduce the frequency of requests                              |
| 7                   | 301602              | Server error             | Please try again or contact a technician to resolve the issue |
| 7                   | 301607              | Too many request symbols | Reduce the number of symbols in a request                     |

### Get Security Candlesticks

This API is used to obtain the candlestick data of security.

:::info
Note: This interface can only retrieve the last 1000 candlesticks. To obtain longer historical data, please visit the interface: Get Security History Candlesticks.
:::


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.candlesticks](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.candlesticks) |
| JavaScript | [QuoteContext.candlesticks](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#candlesticks) |
| Rust | [QuoteContext::candlesticks](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.candlesticks) |
| Go | [QuoteContext.Candlesticks](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Candlesticks) |
| Java | [QuoteContext.getCandlesticks](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getCandlesticks) |

:::info

[Business Command](../../socket/biz-command): `19`

:::

## Request

### Parameters

| Name        | Type   | Required | Description                                                                                              |
| ----------- | ------ | -------- | -------------------------------------------------------------------------------------------------------- |
| symbol      | string | Yes      | Security code, in `ticker.region` format, for example:`700.HK`                                           |
| period      | int32  | Yes      | Candlestick period, for example: `1000`, see [Period](../objects#period---candlestick-period)            |
| count       | int32  | Yes      | Count of cancdlestick, for example: `100`<br /><br />**Check rules:** <br />maximum count is `1000`      |
| adjust_type | int32  | Yes      | Adjustment type, for example: `0`, see [AdjustType](../objects#adjusttype---candlestick-adjustment-type) |

### Protobuf

```protobuf
message SecurityCandlestickRequest {
  string symbol = 1;
  Period period = 2;
  int32 count = 3;
  AdjustType adjust_type = 4;
}
```

### Request Example

```python
# Get Security Candlesticks
# https://open.longportapp.com/docs/quote/pull/candlestick
# Before running, please visit the "Developers to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from longport.openapi import QuoteContext, Config, Period, AdjustType

config = Config.from_env()
ctx = QuoteContext(config)

resp = ctx.candlesticks("700.HK", Period.Day, 10, AdjustType.NoAdjust)
print(resp)
```

## Response

### Response Properties

| Name         | Type     | Description                           |
| ------------ | -------- | ------------------------------------- |
| symbol       | string   | Security code, for example: `AAPL.US` |
| candlesticks | object[] | Candlestick data                      |
| ∟ close      | string   | Close price                           |
| ∟ open       | string   | Open price                            |
| ∟ low        | string   | Low price                             |
| ∟ high       | string   | High price                            |
| ∟ volume     | int64    | Volume                                |
| ∟ turnover   | string   | Turnover                              |
| ∟ timestamp  | int64    | Timestamp                             |

### Protobuf

```protobuf
message SecurityCandlestickResponse {
  string symbol = 1;
  repeated Candlestick candlesticks = 2;
}

message Candlestick {
  string close = 1;
  string open = 2;
  string low = 3;
  string high = 4;
  int64 volume = 5;
  string turnover = 6;
  int64 timestamp = 7;
}
```

### Response JSON Example

```json
{
  "symbol": "700.HK",
  "candlesticks": [
    {
      "close": "362.000",
      "open": "364.600",
      "low": "361.600",
      "high": "368.800",
      "volume": 10853604,
      "turnover": "3954556819.000",
      "timestamp": 1650384000
    },
    {
      "close": "348.000",
      "open": "352.000",
      "low": "343.000",
      "high": "356.200",
      "volume": 25738562,
      "turnover": "8981529950.000",
      "timestamp": 1650470400
    },
    {
      "close": "340.600",
      "open": "334.800",
      "low": "334.200",
      "high": "343.000",
      "volume": 28031299,
      "turnover": "9492674293.000",
      "timestamp": 1650556800
    },
    {
      "close": "327.400",
      "open": "332.200",
      "low": "325.200",
      "high": "338.600",
      "volume": 25788422,
      "turnover": "8541441823.000",
      "timestamp": 1650816000
    },
    {
      "close": "335.800",
      "open": "332.200",
      "low": "330.600",
      "high": "341.600",
      "volume": 27288328,
      "turnover": "9166022626.000",
      "timestamp": 1650902400
    }
  ]
}
```

## Error Code

| Protocol Error Code | Business Error Code | Description                    | Troubleshooting Suggestions                                                    |
| ------------------- | ------------------- | ------------------------------ | ------------------------------------------------------------------------------ |
| 3                   | 301600              | Invalid request                | Invalid request parameters or unpacking request failed                         |
| 3                   | 301606              | Request rate limit             | Reduce the frequency of requests                                               |
| 7                   | 301602              | Server error                   | Please try again or contact a technician to resolve the issue                  |
| 7                   | 301600              | Invalue request parameters     | Please check the request parameter: `symbol`, `count`, `adjust_type`, `period` |
| 7                   | 301603              | No quotes                      | Security no quote                                                              |
| 7                   | 301604              | No access                      | No access to security quote                                                    |
| 7                   | 301607              | Too many candlesticks requeted | Reduce the amount of candlestick in each request                               |

### Get Security Capital Distribution

This API is used to obtain the daily capital distribution of security.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.capital_distribution](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.capital_distribution) |
| JavaScript | [QuoteContext.capital_distribution](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#capital_distribution) |
| Rust | [QuoteContext::capital_distribution](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.capital_distribution) |
| Go | [QuoteContext.Capital_distribution](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Capital_distribution) |
| Java | [QuoteContext.getCapital_distribution](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getCapital_distribution) |

:::info
[Business Command](../../socket/biz-command)：`25`
:::

## Request

### Parameters

| Name   | Type   | Required | Description                                                     |
| ------ | ------ | -------- | --------------------------------------------------------------- |
| symbol | string | Yes      | Security code, in `ticker.region` format, for example: `700.HK` |

### Protobuf

```protobuf
message SecurityRequest {
  string symbol = 1;
}
```

### Request Example

```python
# Get Security Capital Distribution
# https://open.longportapp.com/docs/quote/pull/capital-distribution
# Before running, please visit the "Developers to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
```

## Response

### Response Properties

| Name        | Type     | Description          |
| ----------- | -------- | -------------------- |
| symbol      | string   | Security code        |
| timestamp   | int64    | Data update time     |
| capital_in  | object[] | Inflow capital data  |
| ∟ large     | string   | large order          |
| ∟ medium    | string   | medium order         |
| ∟ small     | string   | small order          |
| capital_out | object[] | Outflow capital data |
| ∟ large     | string   | large order          |
| ∟ medium    | string   | medium order         |
| ∟ small     | string   | small order          |

### Protobuf

```protobuf
message CapitalDistributionResponse {
  message CapitalDistribution {
    string large = 1;
    string medium = 2;
    string small = 3;
  }
  string symbol = 1;
  int64 timestamp = 2;
  CapitalDistribution capital_in = 3;
  CapitalDistribution capital_out = 4;
}
```

### Response JSON Example

```json
{
  "symbol": "700.HK",
  "timestamp": "1655107800",
  "capital_in": {
    "large": "935389700.000",
    "medium": "2056032380.000",
    "small": "828715920.000"
  },
  "capital_out": {
    "large": "1175331560.000",
    "medium": "2271829740.000",
    "small": "751648940.000"
  }
}
```

## Error Code

| Protocol Error Code | Business Error Code | Description        | Troubleshooting Suggestions                                   |
| ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- |
| 3                   | 301600              | Invalid request    | Invalid request parameters or unpacking request failed        |
| 3                   | 301606              | Request rate limit | Reduce the frequency of requests                              |
| 7                   | 301602              | Server error       | Please try again or contact a technician to resolve the issue |
| 7                   | 301600              | Symbol not found   | Check that the requested `symbol` is correct                  |
| 7                   | 301603              | No quotes          | Security no quote                                             |
| 7                   | 301604              | No access          | No access to security quote                                   |

### Get Security Capital Flow Intraday

This API is used to obtain the daily capital flow intraday of security.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.capital_flow](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.capital_flow) |
| JavaScript | [QuoteContext.capital_flow](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#capital_flow) |
| Rust | [QuoteContext::capital_flow](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.capital_flow) |
| Go | [QuoteContext.Capital_flow](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Capital_flow) |
| Java | [QuoteContext.getCapital_flow](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getCapital_flow) |

:::info
[Business Command](../../socket/biz-command)：`24`
:::

## Request

### Parameters

| Name   | Type   | Required | Description                                                     |
| ------ | ------ | -------- | --------------------------------------------------------------- |
| symbol | string | Yes      | Security code, in `ticker.region` format, for example: `700.HK` |

### Protobuf

```protobuf
message CapitalFlowIntradayRequest {
  string symbol = 1;
}
```

### Request Example

```python
# Get Security Capital Flow Intraday
# https://open.longportapp.com/docs/quote/pull/capital-flow-intraday
# Before running, please visit the "Developers to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
```

## Response

### Response Properties

| Name               | Type     | Description                    |
| ------------------ | -------- | ------------------------------ |
| symbol             | string   | Security code                  |
| capital_flow_lines | object[] | Capital flow data              |
| ∟ inflow           | string   | Inflow capital data            |
| ∟ timestamp        | int64    | Start time stamp of the minute |

### Protobuf

```protobuf
message CapitalFlowIntradayResponse {
  message CapitalFlowLine {
    string inflow = 1;
    int64 timestamp = 2;
  }
  string symbol = 1;
  repeated CapitalFlowLine capital_flow_lines = 2;
}
```

### Response JSON Example

```json
{
  "symbol": "700.HK",
  "capital_flow_lines": [
    { "inflow": "-310255860.000", "timestamp": "1655106960" },
    { "inflow": "-314011220.000", "timestamp": "1655107020" },
    { "inflow": "-314011220.000", "timestamp": "1655107080" },
    { "inflow": "-314011220.000", "timestamp": "1655107140" },
    { "inflow": "-314011220.000", "timestamp": "1655107200" }
  ]
}
```

## Error Code

| Protocol Error Code | Business Error Code | Description        | Troubleshooting Suggestions                                   |
| ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- |
| 3                   | 301600              | Invalid request    | Invalid request parameters or unpacking request failed        |
| 3                   | 301606              | Request rate limit | Reduce the frequency of requests                              |
| 7                   | 301602              | Server error       | Please try again or contact a technician to resolve the issue |
| 7                   | 301600              | Symbol not found   | Check that the requested `symbol` is correct                  |
| 7                   | 301603              | No quotes          | Security no quote                                             |
| 7                   | 301604              | No access          | No access to security quote                                   |

### Get Security Depth

This API is used to obtain the depth data of security.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.depth](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.depth) |
| JavaScript | [QuoteContext.depth](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#depth) |
| Rust | [QuoteContext::depth](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.depth) |
| Go | [QuoteContext.Depth](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Depth) |
| Java | [QuoteContext.getDepth](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getDepth) |

:::info

[Business Command](../../socket/biz-command): `14`

:::

## Request

### Parameters

| Name   | Type   | Required | Description                                                    |
| ------ | ------ | -------- | -------------------------------------------------------------- |
| symbol | string | Yes      | Security code, in `ticker.region` format, for example:`700.HK` |

### Protobuf

```protobuf
message SecurityRequest {
  string symbol = 1;
}
```

### Request Example

```python
# Get Security Depth
# https://open.longportapp.com/docs/quote/pull/depth
# Before running, please visit the "Developers to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from longport.openapi import QuoteContext, Config

config = Config.from_env()
ctx = QuoteContext(config)

resp = ctx.depth("700.HK")
print(resp)
```

## Response

### Response Properties

| Name        | Type     | Description      |
| ----------- | -------- | ---------------- |
| symbol      | string   | Security code    |
| ask         | object[] | Ask depth        |
| ∟ position  | int32    | Position         |
| ∟ price     | string   | Price            |
| ∟ volume    | int64    | Volume           |
| ∟ order_num | int64    | Number of orders |
| bid         | object[] | Bid depth        |
| ∟ position  | int32    | Position         |
| ∟ price     | string   | Price            |
| ∟ volume    | int64    | Volume           |
| ∟ order_num | int64    | Number of orders |

### Protobuf

```protobuf
message SecurityDepthResponse {
  string symbol = 1;
  repeated Depth ask = 2;
  repeated Depth bid = 3;
}

message Depth {
  int32 position = 1;
  string price = 2;
  int64 volume = 3;
  int64 order_num = 4;
}
```

### Response JSON Example

```json
{
  "symbol": "700.HK",
  "ask": [
    {
      "position": 1,
      "price": "335.000",
      "volume": 500,
      "order_num": 1
    },
    {
      "position": 2,
      "price": "335.200",
      "volume": 400,
      "order_num": 1
    },
    {
      "position": 3,
      "price": "335.400",
      "volume": 500,
      "order_num": 2
    },
    {
      "position": 4,
      "price": "335.600",
      "volume": 1200,
      "order_num": 3
    },
    {
      "position": 5,
      "price": "335.800",
      "volume": 14000,
      "order_num": 8
    }
  ],
  "bid": [
    {
      "position": 1,
      "price": "334.800",
      "volume": 69400,
      "order_num": 13
    },
    {
      "position": 2,
      "price": "334.600",
      "volume": 266600,
      "order_num": 27
    },
    {
      "position": 3,
      "price": "334.400",
      "volume": 61300,
      "order_num": 29
    },
    {
      "position": 4,
      "price": "334.200",
      "volume": 125900,
      "order_num": 31
    },
    {
      "position": 5,
      "price": "334.000",
      "volume": 194600,
      "order_num": 94
    }
  ]
}
```

## Error Code

| Protocol Error Code | Business Error Code | Description        | Troubleshooting Suggestions                                   |
| ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- |
| 3                   | 301600              | Invalid request    | Invalid request parameters or unpacking request failed        |
| 3                   | 301606              | Request rate limit | Reduce the frequency of requests                              |
| 7                   | 301602              | Server error       | Please try again or contact a technician to resolve the issue |
| 7                   | 301600              | Symbol not found   | Check that the requested `symbol` is correct                  |
| 7                   | 301603              | No quotes          | Security no quote                                             |
| 7                   | 301604              | No access          | No access to security quote                                   |

### Get Security History Candlesticks

This API is used to obtain the history candlestick data of security.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.history_candlesticks_by_offset](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.history_candlesticks_by_offset) |
| JavaScript | [QuoteContext.history_candlesticks_by_offset](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#history_candlesticks_by_offset) |
| Rust | [QuoteContext::history_candlesticks_by_offset](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.history_candlesticks_by_offset) |
| Go | [QuoteContext.History_candlesticks_by_offset](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.History_candlesticks_by_offset) |
| Java | [QuoteContext.getHistory_candlesticks_by_offset](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getHistory_candlesticks_by_offset) |

:::info

[Business Command](../../socket/biz-command)：`27`

:::

## Request

### Parameters

| Name           | Type   | Required | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
|----------------|--------|----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| symbol         | string | Yes      | Security code, in `ticker.region` format, for example:`700.HK`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| period         | int32  | Yes      | Candlestick period, for example: `1000`, see [Period](../objects#period---candlestick-period)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| adjust_type    | int32  | Yes      | Adjustment type, for example: `0`, see [AdjustType](../objects#adjusttype---candlestick-adjustment-type)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| query_type     | int32  | Yes      | Type of query <br /><br />**Optional value:**<br />`1` - query by offset <br />`2` - query by date                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| date_request   | object | No       | Required when querying by date                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| ∟ start_date   | string | No       | Date of query begin, in `YYYYMMDD` format, for example: 20231016 <br /><br />**Parameter description:**<br /> 1. Leave both start_date and end_date blank: return the latest 1000 candlesticks; <br />2. Fill only start_date: return the candlesticks between start_date and the latest trading day. If there are more than 1000 candlesticks in this interval, the candlesticks close to start_date will be returned first; <br /> 3. Fill in only end_date: return end_date and the previous 1000 candlesticks; <br /> 4. Fill in both start_date and end_date: return candlesticks data within this interval. If there are more than 1000 candlesticks in the interval, the candlesticks close to end_date will be returned first. |
| ∟ end_date     | string | No       | Date of query end, in `YYYYMMDD` format, for example: 20231016                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| offset_request | object | No       | Required when querying by offset                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| ∟ direction    | int32  | Yes      | Query direction <br /><br />**Optional value:**<br />`0` - query in the direction of historical data <br />`1` - query in the direction of latest data                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| ∟ date         | string | No       | Query date, in `YYYYMMDD` format, for example: 20231016. Default value: latest trading day of the underlying market.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| ∟ minute       | string | No       | Query time, in `HHMM` format, for example: 09:35, only valid when querying minute-level data                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| ∟ count        | int32  | No       | Count of cancdlestick, valid range:`[1,1000]`. Default value: `10`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |

### Protobuf

```protobuf
message SecurityHistoryCandlestickRequest {

  message OffsetQuery {
    Direction direction = 1;
    string date = 2;
    string minute = 3;
    int32 count = 4;
  }

  message DateQuery {
    string start_date = 1;
    string end_date = 2;
  }

  string symbol = 1;
  Period period = 2;
  AdjustType adjust_type = 3;
  HistoryCandlestickQueryType query_type = 4;
  OffsetQuery offset_request = 5;
  DateQuery date_request = 6;
}
```

### Request Example

```python
# Get Security History Candlesticks
# https://open.longportapp.com/docs/quote/pull/candlestick
# Before running, please visit the "Developers to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from datetime import datetime, date
from longport.openapi import QuoteContext, Config, Period, AdjustType

config = Config.from_env()
ctx = QuoteContext(config)

# Query after 2023-01-01
resp = ctx.history_candlesticks_by_offset("700.HK", Period.Day, AdjustType.NoAdjust, True, 10, datetime(2023, 1, 1))
print(resp)

# Query before 2023-01-01
resp = ctx.history_candlesticks_by_offset("700.HK", Period.Day, AdjustType.NoAdjust, False, 10, datetime(2023, 1, 1))
print(resp)

# Query 2023-01-01 to 2023-02-01
resp = ctx.history_candlesticks_by_date("700.HK", Period.Day, AdjustType.NoAdjust, date(2023, 1, 1), date(2023, 2, 1))
print(resp)
```

## Response

### Response Properties

| Name         | Type     | Description                           |
|--------------|----------|---------------------------------------|
| symbol       | string   | Security code, for example: `AAPL.US` |
| candlesticks | object[] | Candlestick data                      |
| ∟ close      | string   | Close price                           |
| ∟ open       | string   | Open price                            |
| ∟ low        | string   | Low price                             |
| ∟ high       | string   | High price                            |
| ∟ volume     | int64    | Volume                                |
| ∟ turnover   | string   | Turnover                              |
| ∟ timestamp  | int64    | Timestamp                             |

### Protobuf

```protobuf
message SecurityCandlestickResponse {
  string symbol = 1;
  repeated Candlestick candlesticks = 2;
}

message Candlestick {
  string close = 1;
  string open = 2;
  string low = 3;
  string high = 4;
  int64 volume = 5;
  string turnover = 6;
  int64 timestamp = 7;
}
```

### Response JSON Example

```json
{
  "symbol": "700.HK",
  "candlesticks": [
    {
      "close": "362.000",
      "open": "364.600",
      "low": "361.600",
      "high": "368.800",
      "volume": 10853604,
      "turnover": "3954556819.000",
      "timestamp": 1650384000
    },
    {
      "close": "348.000",
      "open": "352.000",
      "low": "343.000",
      "high": "356.200",
      "volume": 25738562,
      "turnover": "8981529950.000",
      "timestamp": 1650470400
    },
    {
      "close": "340.600",
      "open": "334.800",
      "low": "334.200",
      "high": "343.000",
      "volume": 28031299,
      "turnover": "9492674293.000",
      "timestamp": 1650556800
    },
    {
      "close": "327.400",
      "open": "332.200",
      "low": "325.200",
      "high": "338.600",
      "volume": 25788422,
      "turnover": "8541441823.000",
      "timestamp": 1650816000
    },
    {
      "close": "335.800",
      "open": "332.200",
      "low": "330.600",
      "high": "341.600",
      "volume": 27288328,
      "turnover": "9166022626.000",
      "timestamp": 1650902400
    }
  ]
}
```

## Permission description

According to the user’s assets and transactions, the number of targets that different types of users can query historical data on each month is as follows:

- The quota is calculated based on the natural month. The quota is topped up at the beginning of each month. The remaining quota from the previous month will not be accumulated to this month. If you repeatedly request the historical K-line of the same target within a natural month, it will only be counted once.
- For newly deposited accounts, the limit will automatically take effect on the next trading day; when the account's total assets or number of transactions increase and reaches a higher level, the limit will take effect on the next trading day.
- Total assets: The total assets of the user's Hong Kong stocks, U.S. stocks, A-shares and other securities accounts are converted into Hong Kong dollars according to the exchange rate. Take the larger value of the user's total assets on the last trading day of the previous calendar month and the total assets on the most recent complete trading day.
- Number of transactions per month: The number of orders that the user has completed. Partial completion of one order, complete completion of multiple transactions, or all transactions at one time are counted as 1 transaction. Take the larger value of the user's number of transactions in the last natural month and the number of transactions in the current natural month.

<table>
  <tr>
    <th>User Type</th>
    <th >The maximum number of targets that can be queried per month</th>
  </tr>
  <tr>
    <td>User account opening</td>
    <td><center>100</center></td>
  </tr>
  <tr>
    <td>Total assets reach HKD 10,000 </td>
    <td><center>400</center></td>
  </tr>
  <tr>
    <td>Total assets reach HKD 80,000</td>
    <td><center>600</center></td>
  </tr>
  <tr>
    <td>Total assets reach 400,000 HKD or the number of transactions per month is greater than 160</td>
    <td><center>1000</center></td>
  </tr>
  <tr>
    <td>Total assets reach 4 million HKD or the number of transactions per month is greater than 1,600</td>
    <td><center>2000</center></td>
  </tr>
  <tr>
    <td>Total assets reach 6 million HKD or the number of transactions per month is greater than 2,500</td>
    <td><center>3000</center></td>
  </tr>
</table>

## Description of historical candlesticks range

| Market             | Daily/Weekly/Monthly/Year period candlesticks | Minute candlesticks   | Description                                                                                                       |
|--------------------|-----------------------------------------------|-----------------------|-------------------------------------------------------------------------------------------------------------------|
| Hong Kong stocks   | 2004-6-1 to present                           | 2022-09-28 to present |                                                                                                                   |
| U.S. stocks        | 2010-6-1 to present                           | 2023-12-4 to present  |                                                                                                                   |
| U.S. stock options | -                                             | -                     | U.S. stock options historical data is currently not supported, and data for longer periods will be released later |
| A shares           | 1999-11-1 to present                          | 2022-08-25 to present |                                                                                                                   |

## Rate limite

:::caution

- The api can be requested up to 60 times every 30 seconds.

:::

## Error Code

| Protocol Error Code | Business Error Code | Description                | Troubleshooting Suggestions                                                               |
|---------------------|---------------------|----------------------------|-------------------------------------------------------------------------------------------|
| 3                   | 301600              | Invalid request            | Invalid request parameters or unpacking request failed                                    |
| 3                   | 301606              | Request rate limit         | Reduce the frequency of requests                                                          |
| 7                   | 301602              | Server error               | Please try again or contact a technician to resolve the issue                             |
| 7                   | 301600              | Invalue request parameters | Please check the request parameter: `symbol`, `count`, `adjust_type`, `period`            |
| 7                   | 301603              | No quotes                  | Security no quote                                                                         |
| 7                   | 301604              | No access                  | No access to security quote                                                               |
| 7                   | 301607              | Permission limit           | Exceeds the upper limit of the number of targets that can be queried in the current month |

### Get Security Intraday

This API is used to obtain the intraday data of security.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.intraday](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.intraday) |
| JavaScript | [QuoteContext.intraday](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#intraday) |
| Rust | [QuoteContext::intraday](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.intraday) |
| Go | [QuoteContext.Intraday](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Intraday) |
| Java | [QuoteContext.getIntraday](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getIntraday) |

:::info

[Business Command](../../socket/biz-command): `18`

:::

## Request

### Parameters

| Name   | Type   | Required | Description                                                    |
| ------ | ------ | -------- | -------------------------------------------------------------- |
| symbol | string | Yes      | Security code, in `ticker.region` format, for example:`700.HK` |

### Protobuf

```protobuf
message SecurityIntradayRequest {
  string symbol = 1;
}
```

### Request Example

```python
# Get Security Intraday
# https://open.longportapp.com/docs/quote/pull/intraday
# Before running, please visit the "Developers to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from longport.openapi import QuoteContext, Config

config = Config.from_env()
ctx = QuoteContext(config)

resp = ctx.intraday("700.HK")
print(resp)
```

## Response

### Response Properties

| Name        | Type     | Description                           |
| ----------- | -------- | ------------------------------------- |
| symbol      | string   | Security code, for example: `AAPL.US` |
| lines       | object[] | Intraday line data                    |
| ∟ price     | string   | Close price of the minute             |
| ∟ timestamp | int64    | Start time stamp of the minute        |
| ∟ volume    | int64    | Volume                                |
| ∟ turnover  | string   | Turnover                              |
| ∟ avg_price | string   | Average price                         |

### Protobuf

```
message SecurityIntradayResponse{
  string symbol = 1;
  repeated Line lines = 2;
}

message Line {
  string price = 1;
  int64 timestamp = 2;
  int64 volume = 3;
  string turnover = 4;
  string avg_price = 5;
}
```

### Response JSON Example

```json
{
  "symbol": "700.HK",
  "lines": [
    {
      "price": "330.400",
      "timestamp": 1651023000,
      "volume": 375870,
      "turnover": "123949699.000",
      "avg_price": "329.767470"
    },
    {
      "price": "331.200",
      "timestamp": 1651023060,
      "volume": 233095,
      "turnover": "77269032.800",
      "avg_price": "330.427416"
    },
    {
      "price": "330.400",
      "timestamp": 1651023120,
      "volume": 192565,
      "turnover": "63711556.000",
      "avg_price": "330.530719"
    },
    {
      "price": "330.800",
      "timestamp": 1651023180,
      "volume": 143397,
      "turnover": "47471072.400",
      "avg_price": "330.608989"
    },
    {
      "price": "330.800",
      "timestamp": 1651023240,
      "volume": 141834,
      "turnover": "46890605.600",
      "avg_price": "330.608078"
    }
  ]
}
```

## Error Code

| Protocol Error Code | Business Error Code | Description        | Troubleshooting Suggestions                                   |
| ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- |
| 3                   | 301600              | Invalid request    | Invalid request parameters or unpacking request failed        |
| 3                   | 301606              | Request rate limit | Reduce the frequency of requests                              |
| 7                   | 301602              | Server error       | Please try again or contact a technician to resolve the issue |
| 7                   | 301600              | Symbol not found   | Check that the requested `symbol` is correct                  |
| 7                   | 301603              | No quotes          | Security no quote                                             |
| 7                   | 301604              | No access          | No access to security quote                                   |

### Get Warrant Issuer IDs

This API is used to obtain the warrant issuer IDs data (which can be synchronized once a day).


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.warrant_issuers](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.warrant_issuers) |
| JavaScript | [QuoteContext.warrant_issuers](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#warrant_issuers) |
| Rust | [QuoteContext::warrant_issuers](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.warrant_issuers) |
| Go | [QuoteContext.Warrant_issuers](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Warrant_issuers) |
| Java | [QuoteContext.getWarrant_issuers](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getWarrant_issuers) |

:::info

[Business Command](../../socket/biz-command): `22`

:::

## Request

### Request Example

```python
# Get Warrant Issuer IDs
# https://open.longportapp.com/docs/quote/pull/issuer
# Before running, please visit the "Developers to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from longport.openapi import QuoteContext, Config

config = Config.from_env()
ctx = QuoteContext(config)

resp = ctx.warrant_issuers()
print(resp)
```

## Response

### Parameters

| Name        | Type     | Description         |
| ----------- | -------- | ------------------- |
| issuer_info | object[] | Issuer information  |
| ∟ id        | int32    | Issuer ID           |
| ∟ name_cn   | string   | Issuer Name (zh-CN) |
| ∟ name_en   | string   | Issuer Name (en)    |
| ∟ name_hk   | string   | Issuer Name (zh-HK) |

### Protobuf

```protobuf
message IssuerInfoResponse {
  repeated IssuerInfo issuer_info = 1;
}

message IssuerInfo {
  int32 id = 1;
  string name_cn = 2;
  string name_en = 3;
  string name_hk = 4;
}
```

### Response JSON Example

```json
{
  "issuer_info": [
    {
      "id": 15,
      "name_cn": "瑞银",
      "name_en": "UB",
      "name_hk": "瑞銀"
    },
    {
      "id": 14,
      "name_cn": "汇丰",
      "name_en": "HS",
      "name_hk": "滙豐"
    },
    {
      "id": 12,
      "name_cn": "花旗",
      "name_en": "CT",
      "name_hk": "花旗"
    }
  ]
}
```

## Error Code

| Protocol Error Code | Business Error Code | Description        | Troubleshooting Suggestions                                   |
| ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- |
| 3                   | 301600              | Invalid request    | Invalid request parameters or unpacking request failed        |
| 3                   | 301606              | Request rate limit | Reduce the frequency of requests                              |
| 7                   | 301602              | Server error       | Please try again or contact a technician to resolve the issue |

### Get Real-time Quotes Of Option Securities

This API is used to obtain the real-time quotes of US stock options, including the option-specific data.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.option_quote](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.option_quote) |
| JavaScript | [QuoteContext.option_quote](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#option_quote) |
| Rust | [QuoteContext::option_quote](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.option_quote) |
| Go | [QuoteContext.Option_quote](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Option_quote) |
| Java | [QuoteContext.getOption_quote](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getOption_quote) |

:::info
[Business Command](../../socket/biz-command): `12`
:::

## Request

### Parameters

| Name   | Type     | Required | Description                                                                                                                                                                                                                                      |
| ------ | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| symbol | string[] | Yes      | Security code list. obtain the symbol of the options through the [optionchain](./optionchain-date-strike.md) API, for example: `[BABA230120C160000.US]` <br /><br />**Check rules:**<br />The maximum number of symbols in each request is `500` |

### Protobuf

```protobuf
message MultiSecurityRequest {
  repeated string symbol = 1;
}
```

### Request Example

```python
# Get Real-time Quotes Of Option Securities
# https://open.longportapp.com/docs/quote/pull/option-quote
# Before running, please visit the "Developers to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from longport.openapi import QuoteContext, Config

config = Config.from_env()
ctx = QuoteContext(config)

resp = ctx.option_quote(["AAPL230317P160000.US"])
print(resp)
```

## Response

### Response Properties

| Name                     | Type     | Description                                                                          |
| ------------------------ | -------- | ------------------------------------------------------------------------------------ |
| secu_quote               | object[] | Options quote                                                                        |
| ∟ symbol                 | string   | Security code                                                                        |
| ∟ last_done              | string   | Latest price                                                                         |
| ∟ prev_close             | string   | Yesterday's close                                                                    |
| ∟ open                   | string   | Open                                                                                 |
| ∟ high                   | string   | High                                                                                 |
| ∟ low                    | string   | Low                                                                                  |
| ∟ timestamp              | int64    | Time of latest price                                                                 |
| ∟ volume                 | int64    | Volume                                                                               |
| ∟ turnover               | string   | Turnover                                                                             |
| ∟ trade_status           | int32    | Security trading status, see [TradeStatus](../objects#tradestatus---security-status) |
| ∟ option_extend          | object   | Option extend quote                                                                  |
| ∟∟ implied_volatility    | string   | Implied volatility                                                                   |
| ∟∟ open_interest         | int64    | Number of open positions                                                             |
| ∟∟ expiry_date           | string   | Exprity date, in `YYMMDD` format                                                     |
| ∟∟ strike_price          | string   | Strike price                                                                         |
| ∟∟ contract_multiplier   | string   | Contract multiplier                                                                  |
| ∟∟ contract_type         | string   | Option type <br /><br />**Optional value:**<br />`A` - American <br />`U` - Europe   |
| ∟∟ contract_size         | string   | Contract size                                                                        |
| ∟∟ direction             | string   | Direction <br /><br />**Optional value:**<br />`P` - put <br />`C` - call            |
| ∟∟ historical_volatility | string   | Underlying security historical volatility of the optionn                             |
| ∟∟ underlying_symbol     | string   | Underlying security symbol of the option                                             |

### Protobuf

```protobuf
message OptionQuoteResponse {
  repeated OptionQuote secu_quote = 1;
}

message OptionQuote {
  string symbol = 1;
  string last_done = 2;
  string prev_close = 3;
  string open = 4;
  string high = 5;
  string low = 6;
  int64 timestamp = 7;
  int64 volume = 8;
  string turnover = 9;
  TradeStatus trade_status = 10;
  OptionExtend option_extend = 11;
}

message OptionExtend {
  string implied_volatility = 1;
  int64 open_interest = 2;
  string expiry_date = 3;
  string strike_price = 4;
  string contract_multiplier = 5;
  string contract_type = 6;
  string contract_size = 7;
  string direction = 8;
  string historical_volatility = 9;
  string underlying_symbol = 10;
}
```

### Response JSON Example

```json
{
  "secu_quote": [
    {
      "symbol": "AAPL220429P162500.US",
      "last_done": "7.78",
      "prev_close": "4.13",
      "open": "4.43",
      "high": "7.80",
      "low": "4.43",
      "timestamp": 1651003200,
      "volume": 3082,
      "turnover": "1813434.00",
      "option_extend": {
        "implied_volatility": "0.592",
        "open_interest": 11463,
        "expiry_date": "20220429",
        "strike_price": "162.50",
        "contract_multiplier": "100",
        "contract_type": "A",
        "contract_size": "100",
        "direction": "P",
        "historical_volatility": "0.2750",
        "underlying_symbol": "AAPL.US"
      }
    },
    {
      "symbol": "AAPL220429C150000.US",
      "last_done": "9.25",
      "prev_close": "13.87",
      "open": "13.80",
      "high": "13.80",
      "low": "9.15",
      "timestamp": 1651003200,
      "volume": 413,
      "turnover": "436835.00",
      "option_extend": {
        "implied_volatility": "0.702",
        "open_interest": 800,
        "expiry_date": "20220429",
        "strike_price": "150.00",
        "contract_multiplier": "100",
        "contract_type": "A",
        "contract_size": "100",
        "direction": "C",
        "historical_volatility": "0.2750",
        "underlying_symbol": "AAPL.US"
      }
    }
  ]
}
```

## Error Code

| Protocol Error Code | Business Error Code | Description              | Troubleshooting Suggestions                                   |
| ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- |
| 3                   | 301600              | Invalid request          | Invalid request parameters or unpacking request failed        |
| 3                   | 301606              | Request rate limit       | Reduce the frequency of requests                              |
| 7                   | 301602              | Server error             | Please try again or contact a technician to resolve the issue |
| 7                   | 301607              | Too many request symbols | Reduce the number of symbols in a request                     |

### Get Option Chain Info By Date

This API is used to obtain a list of option securities by the option chain expiry date.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.option_chain_info_by_date](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.option_chain_info_by_date) |
| JavaScript | [QuoteContext.option_chain_info_by_date](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#option_chain_info_by_date) |
| Rust | [QuoteContext::option_chain_info_by_date](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.option_chain_info_by_date) |
| Go | [QuoteContext.Option_chain_info_by_date](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Option_chain_info_by_date) |
| Java | [QuoteContext.getOption_chain_info_by_date](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getOption_chain_info_by_date) |

:::info

[Business Command](../../socket/biz-command): `21`

:::

## Request

### Parameters

| Name        | Type   | Required | Description                                                                                                                  |
| ----------- | ------ | -------- | ---------------------------------------------------------------------------------------------------------------------------- |
| symbol      | string | Yes      | Security code, in `ticker.region` format, for example:`700.HK`                                                               |
| expiry_date | string | Yes      | Option expiry date，in `YYMMDD` format, for example: `20220429`, obtained by [Option Expiry Date](./optionchain_date.md) API |

### Protobuf

```protobuf
message OptionChainDateStrikeInfoRequest {
  string symbol = 1;
  string expiry_date = 2;
}
```

### Request Example

```python
# Get Option Chain Info By Date
# https://open.longportapp.com/docs/quote/pull/optionchain-date-strike
# Before running, please visit the "Developers to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from datetime import date
from longport.openapi import QuoteContext, Config

config = Config.from_env()
ctx = QuoteContext(config)

resp = ctx.option_chain_info_by_date("AAPL.US", date(2023, 1, 20))
print(resp)
```

## Response

### Response Properties

| Name              | Type     | Description                  |
| ----------------- | -------- | ---------------------------- |
| strike_price_info | object[] | Option security info         |
| ∟ price           | string   | Strike price                 |
| ∟ call_symbol     | string   | Security code of call option |
| ∟ put_symbol      | string   | Security code of put option  |
| ∟ standard        | bool     | Is standard                  |

### Protobuf

```protobuf
message OptionChainDateStrikeInfoResponse {
  repeated StrikePriceInfo strike_price_info = 1;
}

message StrikePriceInfo {
  string price = 1;
  string call_symbol = 2;
  string put_symbol = 3;
  bool  standard = 4;
}
```

### Response JSON Example

```json
{
  "strike_price_info": [
    {
      "price": "100",
      "call_symbol": "AAPL220429C100000.US",
      "put_symbol": "AAPL220429P100000.US",
      "standard": true
    },
    {
      "price": "105",
      "call_symbol": "AAPL220429C105000.US",
      "put_symbol": "AAPL220429P105000.US",
      "standard": true
    },
    {
      "price": "110",
      "call_symbol": "AAPL220429C110000.US",
      "put_symbol": "AAPL220429P110000.US",
      "standard": true
    },
    {
      "price": "115",
      "call_symbol": "AAPL220429C115000.US",
      "put_symbol": "AAPL220429P115000.US",
      "standard": true
    }
  ]
}
```

## Error Code

| Protocol Error Code | Business Error Code | Description                | Troubleshooting Suggestions                                   |
| ------------------- | ------------------- | -------------------------- | ------------------------------------------------------------- |
| 3                   | 301600              | Invalid request            | Invalid request parameters or unpacking request failed        |
| 3                   | 301606              | Request rate limit         | Reduce the frequency of requests                              |
| 7                   | 301602              | Server error               | Please try again or contact a technician to resolve the issue |
| 7                   | 301600              | Invalue request parameters | Please check the request parameter: `symbol`，`expiry_date`   |

### Get Option Chain Expiry Date List

This API is used to obtain the the list of expiration dates of option chain


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.option_chain_expiry_date_list](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.option_chain_expiry_date_list) |
| JavaScript | [QuoteContext.option_chain_expiry_date_list](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#option_chain_expiry_date_list) |
| Rust | [QuoteContext::option_chain_expiry_date_list](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.option_chain_expiry_date_list) |
| Go | [QuoteContext.Option_chain_expiry_date_list](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Option_chain_expiry_date_list) |
| Java | [QuoteContext.getOption_chain_expiry_date_list](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getOption_chain_expiry_date_list) |

:::info

[Business Command](../../socket/biz-command): `20`

:::

## Request

### Parameters

| Name   | Type   | Required | Description                                                    |
| ------ | ------ | -------- | -------------------------------------------------------------- |
| symbol | string | Yes      | Security code, in `ticker.region` format, for example:`700.HK` |

### Protobuf

```protobuf
message SecurityRequest {
  string symbol = 1;
}
```

### Request Example

```python
# Get Option Chain Expiry Date List
# https://open.longportapp.com/docs/quote/pull/optionchain-date
# Before running, please visit the "Developers to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from longport.openapi import QuoteContext, Config

config = Config.from_env()
ctx = QuoteContext(config)

resp = ctx.option_chain_expiry_date_list("AAPL.US")
print(resp)
```

## Response

### Response Properties

| Name        | Type     | Description                                        |
| ----------- | -------- | -------------------------------------------------- |
| expiry_date | string[] | option chain expiry dates list，in `YYMMDD` format |

### Protobuf

```protobuf
message OptionChainDateListResponse {
  repeated string expiry_date = 1;
}
```

### Response JSON Example

```json
{
  "expiry_date": [
    "20220422",
    "20220429",
    "20220506",
    "20220513",
    "20220520",
    "20220527",
    "20220603",
    "20220617",
    "20220715",
    "20220819",
    "20220916",
    "20221021",
    "20221118",
    "20230120",
    "20230317",
    "20230616",
    "20230915",
    "20240119",
    "20240621"
  ]
}
```

## Error Code

| Protocol Error Code | Business Error Code | Description        | Troubleshooting Suggestions                                   |
| ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- |
| 3                   | 301600              | Invalid request    | Invalid request parameters or unpacking request failed        |
| 3                   | 301606              | Request rate limit | Reduce the frequency of requests                              |
| 7                   | 301602              | Server error       | Please try again or contact a technician to resolve the issue |
| 7                   | 301600              | Symbol not found   | Check that the requested `symbol` is correct                  |

### Get Real-time Quotes Of Securities

This API is used to obtain the real-time quotes of securities, and supports all types of securities.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.quote](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.quote) |
| JavaScript | [QuoteContext.quote](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#quote) |
| Rust | [QuoteContext::quote](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.quote) |
| Go | [QuoteContext.Quote](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Quote) |
| Java | [QuoteContext.getQuote](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getQuote) |

:::info
[Business Command](../../socket/biz-command): `11`
:::

## Request

### Parameters

| Name   | Type     | Required | Description                                                                                                                                                     |
| ------ | -------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbol | string[] | Yes      | Security code list, in `ticker.region` format, for example: `[700.HK]` <br /><br />**Check rules:**<br />The maximum number of symbols in each request is `500` |

### Protobuf

```protobuf
message MultiSecurityRequest {
  repeated string symbol = 1;
}
```

### Request Example

```python
# Get Real-time Quotes Of Securities
# https://open.longportapp.com/docs/quote/pull/quote
# Before running, please visit the "Developers to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from longport.openapi import QuoteContext, Config

config = Config.from_env()
ctx = QuoteContext(config)

resp = ctx.quote(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"])
print(resp)
```

## Response

### Response Properties

| Name                | Type     | Description                                                                          |
| ------------------- | -------- | ------------------------------------------------------------------------------------ |
| secu_quote          | object[] | Securities quote                                                                     |
| ∟ symbol            | string   | Security code                                                                        |
| ∟ last_done         | string   | Latest price                                                                         |
| ∟ prev_close        | string   | Yesterday's close                                                                    |
| ∟ open              | string   | Open                                                                                 |
| ∟ high              | string   | High                                                                                 |
| ∟ low               | string   | Low                                                                                  |
| ∟ timestamp         | int64    | Time of latest price                                                                 |
| ∟ volume            | int64    | Volume                                                                               |
| ∟ turnover          | string   | Turnover                                                                             |
| ∟ trade_status      | int32    | Security trading status, see [TradeStatus](../objects#tradestatus---security-status) |
| ∟ pre_market_quote  | object   | Quote of US pre market                                                               |
| ∟∟ last_done        | string   | Latest price                                                                         |
| ∟∟ timestamp        | int64    | Time of latest price                                                                 |
| ∟∟ volume           | int64    | Volume                                                                               |
| ∟∟ turnover         | string   | Turnover                                                                             |
| ∟∟ high             | string   | High                                                                                 |
| ∟∟ low              | string   | Low                                                                                  |
| ∟∟ prev_close       | string   | Close of the last trade session                                                      |
| ∟ post_market_quote | object   | Quote of US post market                                                              |
| ∟∟ last_done        | string   | Latest price                                                                         |
| ∟∟ timestamp        | int64    | Time of latest price                                                                 |
| ∟∟ volume           | int64    | Volume                                                                               |
| ∟∟ turnover         | string   | Turnover                                                                             |
| ∟∟ high             | string   | High                                                                                 |
| ∟∟ low              | string   | Low                                                                                  |
| ∟∟ prev_close       | string   | Close of the last trade session                                                      |
| ∟ over_night_quote  | object   | Quote of US overnight market                                                         |
| ∟∟ last_done        | string   | Latest price                                                                         |
| ∟∟ timestamp        | int64    | Time of latest price                                                                 |
| ∟∟ volume           | int64    | Volume                                                                               |
| ∟∟ turnover         | string   | Turnover                                                                             |
| ∟∟ high             | string   | High                                                                                 |
| ∟∟ low              | string   | Low                                                                                  |
| ∟∟ prev_close       | string   | Close of the last trade session                                                      |

### Protobuf

```protobuf
message SecurityQuoteResponse {
  repeated SecurityQuote secu_quote = 1;
}

message SecurityQuote {
  string symbol = 1;
  string last_done = 2;
  string prev_close = 3;
  string open = 4;
  string high = 5;
  string low = 6;
  int64 timestamp = 7;
  int64 volume = 8;
  string turnover = 9;
  TradeStatus trade_status = 10;
  PrePostQuote pre_market_quote = 11;
  PrePostQuote post_market_quote = 12;
}

message PrePostQuote {
  string last_done = 1;
  int64 timestamp = 2;
  int64 volume = 3;
  string turnover = 4;
  string high = 5;
  string low = 6;
  string prev_close = 7;
}
```

### Response JSON Example

```json
{
  "secu_quote": [
    {
      "symbol": "700.HK",
      "last_done": "338.000",
      "prev_close": "334.800",
      "open": "340.600",
      "high": "340.600",
      "low": "333.000",
      "timestamp": 1651115955,
      "volume": 7310881,
      "turnover": "2461463161.000"
    },
    {
      "symbol": "AAPL.US",
      "last_done": "156.570",
      "prev_close": "156.800",
      "open": "155.910",
      "high": "159.790",
      "low": "155.380",
      "timestamp": 1651089600,
      "volume": 88063191,
      "turnover": "13865092584.000",
      "pre_market_quote": {
        "last_done": "155.880",
        "timestamp": 1651066201,
        "volume": 1575504,
        "turnover": "246653442.000",
        "high": "158.400",
        "low": "155.100",
        "prev_close": "156.800"
      },
      "post_market_quote": {
        "last_done": "158.770",
        "timestamp": 1651103995,
        "volume": 6188441,
        "turnover": "970874184.759",
        "high": "159.400",
        "low": "156.400",
        "prev_close": "156.570"
      }
    }
  ]
}
```

## API Restrictions

:::caution

- The HK stocks quotation beyond the 20th will be delayed if the quote level is BMP.

:::

## Error Code

| Protocol Error Code | Business Error Code | Description              | Troubleshooting Suggestions                                   |
| ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- |
| 3                   | 301600              | Invalid request          | Invalid request parameters or unpacking request failed        |
| 3                   | 301606              | Request rate limit       | Reduce the frequency of requests                              |
| 7                   | 301602              | Server error             | Please try again or contact a technician to resolve the issue |
| 7                   | 301607              | Too many request symbols | Reduce the number of symbols in a request                     |

### Get Basic Information Of Securities

This API is used to obtain the basic information of securities.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.static_info](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.static_info) |
| JavaScript | [QuoteContext.static_info](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#static_info) |
| Rust | [QuoteContext::static_info](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.static_info) |
| Go | [QuoteContext.Static_info](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Static_info) |
| Java | [QuoteContext.getStatic_info](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getStatic_info) |

:::info
[Business Command](../../socket/biz-command): `10`
:::

## Request

### Parameters

| Name   | Type     | Required | Description                                                                                                                                                     |
| ------ | -------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbol | string[] | Yes      | Security code list, in `ticker.region` format, for example: `[700.HK]` <br /><br />**Check rules:**<br />The maximum number of symbols in each request is `500` |

### Protobuf

```protobuf
message MultiSecurityRequest {
  repeated string symbol = 1;
}
```

### Request Example

```python
# Get Basic Information Of Securities
# https://open.longportapp.com/docs/quote/pull/static
# Before running, please visit the "Developers to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from longport.openapi import QuoteContext, Config

config = Config.from_env()
ctx = QuoteContext(config)

resp = ctx.static_info(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"])
print(resp)
```

## Response

### Response Properties

| Name                 | Type     | Description                                                                                          |
| -------------------- | -------- | ---------------------------------------------------------------------------------------------------- |
| secu_static_info     | object[] | Securities Basic Information                                                                         |
| ∟ symbol             | string   | Security code                                                                                        |
| ∟ name_cn            | string   | Security name (zh-CN)                                                                                |
| ∟ name_en            | string   | Security name (en)                                                                                   |
| ∟ name_hk            | string   | Security name (zh-HK)                                                                                |
| ∟ exchange           | string   | Exchange which the security belongs to                                                               |
| ∟ currency           | string   | Trading currency <br /><br />**Optional value: **<br />`CNY` <br />`USD` <br />`SGD` <br />`HKD`     |
| ∟ lot_size           | int32    | Lot size                                                                                             |
| ∟ total_shares       | int64    | Total shares                                                                                         |
| ∟ circulating_shares | int64    | Circulating shares                                                                                   |
| ∟ hk_shares          | int64    | HK shares (only HK stocks)                                                                           |
| ∟ eps                | string   | Earnings per share                                                                                   |
| ∟ eps_ttm            | string   | Earnings per share (TTM)                                                                             |
| ∟ bps                | string   | Net assets per share                                                                                 |
| ∟ dividend_yield     | string   | Dividend yield                                                                                       |
| ∟ stock_derivatives  | int32[]  | Types of supported derivatives <br /><br />**Optional value:**<br />`1` - Option <br />`2` - Warrant |
| ∟ board              | string   | The board to whitch the security belongs, see [Board](../objects#board---security-board) for details |

### Protobuf

```protobuf
message SecurityStaticInfoResponse {
  repeated StaticInfo secu_static_info = 1;
}

message StaticInfo {
  string symbol = 1;
  string name_cn = 2;
  string name_en = 3;
  string name_hk = 4;
  string listing_date = 5;
  string exchange = 6;
  string currency = 7;
  int32 lot_size = 8;
  int64 total_shares = 9;
  int64 circulating_shares = 10;
  int64 hk_shares = 11;
  string eps = 12;
  string eps_ttm = 13;
  string bps = 14;
  string dividend_yield = 15;
  repeated int32 stock_derivatives = 16;
  string board = 17;
}
```

### Response JSON Example

```json
{
  "secu_static_info": [
    {
      "symbol": "700.HK",
      "name_cn": "腾讯控股",
      "name_en": "TENCENT",
      "name_hk": "騰訊控股",
      "exchange": "SEHK",
      "currency": "HKD",
      "lot_size": 100,
      "total_shares": 9612464038,
      "circulating_shares": 9612464038,
      "hk_shares": 9612464038,
      "eps": "28.4394",
      "eps_ttm": "28.4394",
      "bps": "103.40413",
      "dividend_yield": "1.6",
      "stock_derivatives": [2],
      "board": "HKEquity"
    },
    {
      "symbol": "AAPL.US",
      "name_cn": "苹果",
      "name_en": "Apple Inc.",
      "exchange": "NASD",
      "currency": "USD",
      "lot_size": 1,
      "total_shares": 1631944100,
      "circulating_shares": 16302661350,
      "eps": "5.669",
      "eps_ttm": "6.0771",
      "bps": "4.40197",
      "dividend_yield": "0.85",
      "stock_derivatives": [1],
      "board": "USMain"
    }
  ]
}
```

## Error Code

| Protocol Error Code | Business Error Code | Description              | Troubleshooting Suggestions                                   |
| ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- |
| 3                   | 301600              | Invalid request          | Invalid request parameters or unpacking request failed        |
| 3                   | 301606              | Request rate limit       | Reduce the frequency of requests                              |
| 7                   | 301602              | Server error             | Please try again or contact a technician to resolve the issue |
| 7                   | 301607              | Too many request symbols | Reduce the number of symbols in a request                     |

### Get Market Trading Days

This API is used to obtain the trading days of the market.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.trading_days](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.trading_days) |
| JavaScript | [QuoteContext.trading_days](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#trading_days) |
| Rust | [QuoteContext::trading_days](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.trading_days) |
| Go | [QuoteContext.Trading_days](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Trading_days) |
| Java | [QuoteContext.getTrading_days](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getTrading_days) |

:::info

[Business Command](../../socket/biz-command): `9`

:::

## Request

### Parameters

| Name    | Type   | Required | Description                                                                                                                                                                                 |
| ------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| market  | string | Yes      | Market <br /><br />**Optional value:**<br/>`US` - US market<br/>`HK` - HK market<br/>`CN` - CN market<br/>`SG` - SG market                                                                  |
| beg_day | string | Yes      | begin day, in `YYMMDD` format, for example: `20220401`                                                                                                                                      |
| end_day | string | Yes      | begin day, in `YYMMDD` format, for example: `20220420` <br/><br/>**Check rules:**<br/> The interval cannot be greater than one month <br/> Only supports query data of the most recent year |

### Protobuf

```protobuf
message MarketTradeDayRequest {
  string market = 1;
  string beg_day = 2;
  string end_day = 3;
}
```

### Request Example

```python
# Get Market Trading Days
# https://open.longportapp.com/docs/quote/pull/trade-day
# Before running, please visit the "Developers to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from datetime import date
from longport.openapi import QuoteContext, Config, Market

config = Config.from_env()
ctx = QuoteContext(config)

resp = ctx.trading_days(Market.HK, date(2022, 1, 1), date(2022, 2, 1))
print(resp)
```

## Response

### Response Properties

| Name           | Type     | Description                           |
| -------------- | -------- | ------------------------------------- |
| trade_day      | string[] | Trading days, in `YYMMDD` format      |
| half_trade_day | string[] | Half trading days, in `YYMMDD` format |

### Protobuf

```protobuf
message MarketTradeDayResponse {
  repeated string trade_day = 1;
  repeated string half_trade_day = 2;
}
```

### Response JSON Example

```json
{
  "trade_day": [
    "20220120",
    "20220121",
    "20220124",
    "20220125",
    "20220126",
    "20220127",
    "20220128",
    "20220204",
    "20220207",
    "20220208",
    "20220209",
    "20220210"
  ],
  "half_trade_day": ["20220131"]
}
```

## Error Code

| Protocol Error Code | Business Error Code | Description                | Troubleshooting Suggestions                                        |
| ------------------- | ------------------- | -------------------------- | ------------------------------------------------------------------ |
| 3                   | 301600              | Invalid request            | Invalid request parameters or unpacking request failed             |
| 3                   | 301606              | Request rate limit         | Reduce the frequency of requests                                   |
| 7                   | 301602              | Server error               | Please try again or contact a technician to resolve the issue      |
| 7                   | 301600              | Invalue request parameters | Please check the request parameter: `market`, `beg_day`, `end_day` |

### Get Trading Session Of The Day

This API is used to obtain the daily trading hours of each market.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.trading_session](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.trading_session) |
| JavaScript | [QuoteContext.trading_session](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#trading_session) |
| Rust | [QuoteContext::trading_session](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.trading_session) |
| Go | [QuoteContext.Trading_session](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Trading_session) |
| Java | [QuoteContext.getTrading_session](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getTrading_session) |

:::info

[Business Command](../../socket/biz-command): `8`

:::

## Request

### Request Example

```python
# Get Trading Session Of The Day
# https://open.longportapp.com/docs/quote/pull/trade-session
# Before running, please visit the "Developers to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from longport.openapi import QuoteContext, Config

config = Config.from_env()
ctx = QuoteContext(config)

resp = ctx.trading_session()
print(resp)
```

## Response

### Response Properties

| Name                 | Type     | Description                                                                                     |
| -------------------- | -------- | ----------------------------------------------------------------------------------------------- |
| market_trade_session | object[] | Trading session data                                                                            |
| ∟ market             | string   | Market<br/><br/>`US` - US market<br/>`HK` - HK market<br/>`CN` - CN market<br/>`SG` - SG market |
| ∟ trade_session      | object[] | Trading session                                                                                 |
| ∟∟ beg_time          | int32    | Being trading time, in `hhmm` format, for example: `900`                                        |
| ∟∟ end_time          | int32    | End trading time, in `hhmm` format, for example: `1400`                                         |
| ∟∟ trade_session     | int32    | Trading session, see [TradeSession](../objects#tradesession---trading-session)                  |

### Protobuf

```protobuf
message MarketTradePeriodResponse {
  repeated MarketTradePeriod market_trade_session = 1;
}

message MarketTradePeriod {
  string market = 1;
  repeated TradePeriod trade_session = 2;
}

message TradePeriod {
  int32 beg_time = 1;
  int32 end_time = 2;
  TradeSession trade_session = 3;
}
```

### Response JSON Example

```json
{
  "market_trade_session": [
    {
      "market": "US",
      "trade_session": [
        {
          "beg_time": 930,
          "end_time": 1600
        },
        {
          "beg_time": 400,
          "end_time": 930,
          "trade_session": 1
        },
        {
          "beg_time": 1600,
          "end_time": 2000,
          "trade_session": 2
        }
      ]
    },
    {
      "market": "HK",
      "trade_session": [
        {
          "beg_time": 930,
          "end_time": 1200
        },
        {
          "beg_time": 1300,
          "end_time": 1600
        }
      ]
    },
    {
      "market": "CN",
      "trade_session": [
        {
          "beg_time": 930,
          "end_time": 1130
        },
        {
          "beg_time": 1300,
          "end_time": 1457
        }
      ]
    },
    {
      "market": "SG",
      "trade_session": [
        {
          "beg_time": 900,
          "end_time": 1200
        },
        {
          "beg_time": 1300,
          "end_time": 1700
        }
      ]
    }
  ]
}
```

## Error Code

| Protocol Error Code | Business Error Code | Description        | Troubleshooting Suggestions                                   |
| ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- |
| 3                   | 301600              | Invalid request    | Invalid request parameters or unpacking request failed        |
| 3                   | 301606              | Request rate limit | Reduce the frequency of requests                              |
| 7                   | 301602              | Server error       | Please try again or contact a technician to resolve the issue |

### Get Security Trades

This API is used to obtain the trades data of security.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.trades](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.trades) |
| JavaScript | [QuoteContext.trades](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#trades) |
| Rust | [QuoteContext::trades](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.trades) |
| Go | [QuoteContext.Trades](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Trades) |
| Java | [QuoteContext.getTrades](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getTrades) |

:::info

[Business Command](../../socket/biz-command): `17`

:::

## Request

### Parameters

| Name   | Type   | Required | Description                                                                                              |
| ------ | ------ | -------- | -------------------------------------------------------------------------------------------------------- |
| symbol | string | Yes      | Security code, in `ticker.region` format, for example:`700.HK`                                           |
| count  | int32  | Yes      | Count of trades <br /><br />**Check rules:**<br />The maximum number of trades in each request is `1000` |

### Protobuf

```protobuf
message SecurityTradeRequest {
  string symbol = 1;
  int32 count = 2;
}
```

### Request Example

```python
# Get Security Trades
# https://open.longportapp.com/docs/quote/pull/trade
# Before running, please visit the "Developers to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from longport.openapi import QuoteContext, Config

config = Config.from_env()
ctx = QuoteContext(config)

resp = ctx.trades("700.HK", 10)
print(resp)
```

## Response

### Response Properties

| Name            | Type     | Description                                                                                      |
| --------------- | -------- | ------------------------------------------------------------------------------------------------ |
| symbol          | string   | Security code                                                                                    |
| trades          | object[] | Trades data                                                                                      |
| ∟ price         | string   | Price                                                                                            |
| ∟ volume        | int64    | Volume                                                                                           |
| ∟ timestamp     | int64    | Time of trading                                                                                  |
| ∟ trade_type    | string   | [Trade type](#trade-type)                                                                        |
| ∟ direction     | int32    | Trade direction <br /><br />**Optional value:**<br />`0` - neutral<br />`1` - down<br />`2` - up |
| ∟ trade_session | int32    | Trade session, see [TradeSession](../objects#tradesession---trading-session)                     |

#### Trade Type

HK

- `*` - Overseas trade
- `D` - Odd-lot trade
- `M` - Non-direct off-exchange trade
- `P` - Late trade (Off-exchange previous day)
- `U` - Auction trade
- `X` - Direct off-exchange trade
- `Y` - Automatch internalized
- ` ` - Automatch normal

US

- ` ` - Regular sale
- `A` - Acquisition
- `B` - Bunched trade
- `D` - Distribution
- `F` - Intermarket sweep
- `G` - Bunched sold trades
- `H` - Price variation trade
- `I` - Odd lot trade
- `K` - Rule 155 trde(NYSE MKT)
- `M` - Market center close price
- `P` - Prior reference price
- `Q` - Market center open price
- `S` - Split trade
- `V` - Contingent trade
- `W` - Average price trade
- `X` - Cross trade
- `1` - Stopped stock(Regular trade)

### Protobuf

```protobuf
message SecurityTradeResponse {
  string symbol = 1;
  repeated Trade trades = 2;
}

message Trade {
  string price = 1;
  int64 volume = 2;
  int64 timestamp = 3;
  string trade_type = 4;
  int32 direction = 5;
  TradeSession trade_session = 6;
}
```

### Response JSON Example

```json
{
  "symbol": "AAPL.US",
  "trades": [
    {
      "price": "158.760",
      "volume": 1,
      "timestamp": 1651103979,
      "trade_type": "I",
      "direction": 0,
      "trade_session": 2
    },
    {
      "price": "158.745",
      "volume": 1,
      "timestamp": 1651103985,
      "trade_type": "I",
      "direction": 0,
      "trade_session": 2
    },
    {
      "price": "158.800",
      "volume": 1,
      "timestamp": 1651103995,
      "trade_type": "I",
      "direction": 0,
      "trade_session": 2
    }
  ]
}
```

## Error Code

| Protocol Error Code | Business Error Code | Description              | Troubleshooting Suggestions                                   |
| ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- |
| 3                   | 301600              | Invalid request          | Invalid request parameters or unpacking request failed        |
| 3                   | 301606              | Request rate limit       | Reduce the frequency of requests                              |
| 7                   | 301602              | Server error             | Please try again or contact a technician to resolve the issue |
| 7                   | 301600              | Symbol not found         | Check that the requested `symbol` is correct                  |
| 7                   | 301603              | No quotes                | Security no quote                                             |
| 7                   | 301604              | No access                | No access to security quote                                   |
| 7                   | 301607              | Too many trades requeted | Reduce the amount of trades in each request                   |

### Get Filtered Warrant

This API is used to obtain the quotes of HK warrants, and supports sorting and filtering.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.warrant_list](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.warrant_list) |
| JavaScript | [QuoteContext.warrant_list](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#warrant_list) |
| Rust | [QuoteContext::warrant_list](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.warrant_list) |
| Go | [QuoteContext.Warrant_list](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Warrant_list) |
| Java | [QuoteContext.getWarrant_list](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getWarrant_list) |

:::info

[Business Command](../../socket/biz-command): `23`

:::

## Request

### Parameters

| Name          | Type    | Required | Description                                                                                                                                                                         |
| ------------- | ------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbol        | string  | Yes      | Security code, in `ticker.region` format, for example:`700.HK`                                                                                                                      |
| filter_config | object  | Yes      | Filter conditions                                                                                                                                                                   |
| ∟ sort_by     | int32   | Yes      | Which data to sort by, for example: `0`, see the `OrderSequence` field of the response data for the sequence number.                                                                |
| ∟ sort_order  | int32   | Yes      | Order, for example: `1` <br /><br />**Optional value:**<br />`0` - Ascending<br />`1` - Descending                                                                                  |
| ∟ sort_offset | int32   | Yes      | The first data offset of paging, for example: `0`                                                                                                                                   |
| ∟ sort_count  | int32   | Yes      | Number of paginated pages per page, for example: `20`, no pagination when filling in `0`                                                                                            |
| ∟ type        | int32[] | No       | Filter warrant type, for example: `[0,1]` <br /><br />**Optional value:**<br />`0` - Call<br />`1` - Put<br />`2` - Bull<br />`3` - Bear<br />`4` - Inline                          |
| ∟ issuer      | int32[] | No       | Filter issuer example: `[12,14]`, obtain [Issuer ID](./issuer) through API                                                                                                          |
| ∟ expiry_date | int32[] | No       | Filter expiry date, example: `[1]` <br /><br />**Optional value:**<br />`1` - Less than 3 months<br />`2` - 3 - 6 months<br />`3` - 6 - 12 months<br />`4` - greater than 12 months |
| ∟ price_type  | int32[] | No       | Filter in/out of bounds, for example: `[2]` <br /><br />**Optional value:**<br />`1` - In bounds<br />`2` - Out bounds                                                              |
| ∟ status      | int32[] | No       | Filter status, for example: `[2]` <br /><br />**Optional value:**<br />`2`- Suspend trading<br />`3` - Papare List<br />`4` - Normal                                                |
| language      | int32   | Yes      | Language, for example: `[1]` <br /><br />**Optional value:**<br />`0` - zh-CN<br />`1` - en<br />`2` - zh-HK                                                                        |

### Protobuf

```protobuf
message WarrantFilterListRequest {
  string symbol = 1;
  FilterConfig filter_config = 2;
  int32 language = 3;
}

message FilterConfig {
  int32 sort_by = 1;
  int32 sort_order = 2;
  int32 sort_offset = 3;
  int32 sort_count = 4;
  repeated int32 type = 5;
  repeated int32 issuer = 6;
  repeated int32 expiry_date = 7;
  repeated int32 price_type = 8;
  repeated int32 status = 9;
}
```

### Request Example

```python
from longport.openapi import QuoteContext, Config, WarrantSortBy, SortOrderType

config = Config.from_env()
ctx = QuoteContext(config)

resp = ctx.warrant_list("700.HK", WarrantSortBy.LastDone, SortOrderType.Ascending)
print(resp)
```

## Response

### Response Properties

| Name                 | Type     | Description                                                                                                | OrderSequence | Support_Call/Put | Support_Bull/Bear | Support_Inline |
| -------------------- | -------- | ---------------------------------------------------------------------------------------------------------- | ------------- | ---------------- | ----------------- | -------------- |
| warrant_list         | object[] | Filted warrant data list                                                                                   |               |                  |                   |                |
| ∟ symbol             | string   | Security code                                                                                              |               | true             | true              | true           |
| ∟ name               | string   | Security name                                                                                              |               | true             | true              | true           |
| ∟ last_done          | string   | Latest price                                                                                               | 0             | true             | true              | true           |
| ∟ change_rate        | string   | Quote change rate                                                                                          | 1             | true             | true              | true           |
| ∟ change_val         | string   | Quote change                                                                                               | 2             | true             | true              | true           |
| ∟ volume             | int64    | Volume                                                                                                     | 3             | true             | true              | true           |
| ∟ turnover           | string   | Turnover                                                                                                   | 4             | true             | true              | true           |
| ∟ expiry_date        | string   | Expiry date, in `YYMMDD` format                                                                            | 5             | true             | true              | true           |
| ∟ strike_price       | string   | Strike price                                                                                               | 6             | true             | true              | false          |
| ∟ upper_strike_price | string   | Upper bound price                                                                                          | 7             | false            | false             | true           |
| ∟ lower_strike_price | string   | Lower bound price                                                                                          | 8             | false            | false             | true           |
| ∟ outstanding_qty    | string   | Outstanding quantity                                                                                       | 9             | true             | true              | true           |
| ∟ outstanding_ratio  | string   | Outstanding ratio                                                                                          | 10            | true             | true              | true           |
| ∟ premium            | string   | Premium                                                                                                    | 11            | true             | true              | true           |
| ∟ itm_otm            | string   | In/out of the bound                                                                                        | 12            | true             | true              | false          |
| ∟ implied_volatility | string   | Implied volatility                                                                                         | 13            | true             | false             | false          |
| ∟ delta              | string   | Greek value Delta                                                                                          | 14            | true             | false             | false          |
| ∟ call_price         | string   | Call price                                                                                                 | 15            | false            | true              | false          |
| ∟ to_call_price      | string   | Price interval from the call price                                                                         | 16            | false            | true              | false          |
| ∟ effective_leverage | string   | Effective leverage                                                                                         | 17            | true             | false             | false          |
| ∟ leverage_ratio     | string   | Leverage ratio                                                                                             | 18            | true             | true              | true           |
| ∟ conversion_ratio   | string   | Conversion ratio                                                                                           | 19            | true             | true              | false          |
| ∟ balance_point      | string   | Breakeven point                                                                                            | 20            | true             | true              | false          |
| ∟ status             | int32    | Status, <br /><br />**Optional value:**<br />`2`- Suspend trading<br />`3` - Papare List<br />`4` - Normal | 21            | true             | true              | true           |
| total_count          | int32    | Total number of eligible                                                                                   |               |                  |                   |                |

### Protobuf

```protobuf
message WarrantFilterListResponse {
  repeated FilterWarrant warrant_list = 1;
  int32 total_count = 2;
}

message FilterWarrant {
  string symbol = 1;
  string name = 2;
  string last_done = 3;
  string change_rate = 4;
  string change_val = 5;
  int64 volume = 6;
  string turnover = 7;
  string expiry_date = 8;
  string strike_price = 9;
  string upper_strike_price = 10;
  string lower_strike_price = 11;
  string outstanding_qty = 12;
  string outstanding_ratio = 13;
  string premium = 14;
  string itm_otm = 15;
  string implied_volatility = 16;
  string delta = 17;
  string call_price = 18;
  string to_call_price = 19;
  string effective_leverage = 20;
  string leverage_ratio = 21;
  string conversion_ratio = 22;
  string balance_point = 23;
  int32 status = 24;
}
```

### Response JSON Example

```json
{
  "warrant_list": [
    {
      "symbol": "13157.HK",
      "name": "MBTENCT@EP2207A",
      "last_done": "2.26",
      "change_rate": "-0.0216450216450218",
      "change_val": "-0.050000000000000266",
      "turnover": "0",
      "expiry_date": "20220705",
      "strike_price": "442.233",
      "upper_strike_price": "0",
      "lower_strike_price": "0",
      "outstanding_qty": "5000",
      "outstanding_ratio": "0.0003",
      "premium": "0.016784269662921222",
      "itm_otm": "0.23524476916014864",
      "implied_volatility": "0.5275",
      "delta": "-0.8524",
      "call_price": "0",
      "effective_leverage": "-2.627683451852457",
      "leverage_ratio": "3.0826882353970637",
      "conversion_ratio": "48.544",
      "balance_point": "332.52356000000003",
      "status": 4
    },
    {
      "symbol": "13649.HK",
      "name": "MBTENCT@EP2205A",
      "last_done": "1.14",
      "change_rate": "0",
      "change_val": "0",
      "turnover": "0",
      "expiry_date": "20220518",
      "strike_price": "445.223",
      "upper_strike_price": "0",
      "lower_strike_price": "0",
      "outstanding_qty": "80000",
      "outstanding_ratio": "0.0004",
      "premium": "0.010810703725606",
      "itm_otm": "0.24038066317328624",
      "implied_volatility": "0.5997",
      "delta": "-0.7964",
      "call_price": "0",
      "effective_leverage": "-2.4335424241487873",
      "leverage_ratio": "3.055678583813144",
      "conversion_ratio": "97.087",
      "balance_point": "334.54382000000004",
      "status": 4
    }
  ],
  "total_count": 1197
}
```

## Error Code

| Protocol Error Code | Business Error Code | Description                  | Troubleshooting Suggestions                                   |
| ------------------- | ------------------- | ---------------------------- | ------------------------------------------------------------- |
| 3                   | 301600              | Invalid request              | Invalid request parameters or unpacking request failed        |
| 3                   | 301606              | Request rate limit           | Reduce the frequency of requests                              |
| 7                   | 301602              | Server error                 | Please try again or contact a technician to resolve the issue |
| 7                   | 301600              | Symbol not found             | Check that the requested `symbol` is correct                  |
| 7                   | 301603              | No quotes                    | Security no quote                                             |
| 7                   | 301604              | No access                    | No access to security quote                                   |
| 7                   | 301607              | Too many symbols in one page | Reduce the number of symbols in a page of request             |

### Get Real-time Quotes Of Warrant Securities

This API is used to obtain the real-time quotes of HK warrants, including the warrant-specific data.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.warrant_quote](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.warrant_quote) |
| JavaScript | [QuoteContext.warrant_quote](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#warrant_quote) |
| Rust | [QuoteContext::warrant_quote](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.warrant_quote) |
| Go | [QuoteContext.Warrant_quote](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Warrant_quote) |
| Java | [QuoteContext.getWarrant_quote](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getWarrant_quote) |

:::info

[Business Command](../../socket/biz-command): `13`

:::

## Request

### Parameters

| Name   | Type     | Required | Description                                                                                                                                                       |
| ------ | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbol | string[] | Yes      | Security code list, in `ticker.region` format, for example: `[13447.HK]` <br /><br />**Check rules:**<br />The maximum number of symbols in each request is `500` |

### Protobuf

```protobuf
message MultiSecurityRequest {
  repeated string symbol = 1;
}
```

### Request Example

```python
# Get Real-time Quotes Of Warrant Securities
# https://open.longportapp.com/docs/quote/pull/warrant-quote
# Before running, please visit the "Developers to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from longport.openapi import QuoteContext, Config

config = Config.from_env()
ctx = QuoteContext(config)

resp = ctx.warrant_quote(["21125.HK"])
print(resp)
```

## Response

### Response Properties

| Name                  | Type     | Description                                                                                                    |
| --------------------- | -------- | -------------------------------------------------------------------------------------------------------------- |
| secu_quote            | object[] | Warrants quote                                                                                                 |
| ∟ symbol              | string   | Security code                                                                                                  |
| ∟ last_done           | string   | Latest price                                                                                                   |
| ∟ prev_close          | string   | Yesterday's close                                                                                              |
| ∟ open                | string   | Open                                                                                                           |
| ∟ high                | string   | High                                                                                                           |
| ∟ low                 | string   | Low                                                                                                            |
| ∟ timestamp           | int64    | Time of latest price                                                                                           |
| ∟ volume              | int64    | Volume                                                                                                         |
| ∟ turnover            | string   | Turnover                                                                                                       |
| ∟ trade_status        | int32    | Security trading status, see [TradeStatus](../objects#tradestatus---security-status)                           |
| ∟ warrant_extend      | object   | Warrant extend quote                                                                                           |
| ∟∟ implied_volatility | string   | Implied volatility                                                                                             |
| ∟∟ expiry_date        | string   | Exprity date, in `YYMMDD` format                                                                               |
| ∟∟ last_trade_date    | string   | Last tradalbe date, in `YYMMDD` format                                                                         |
| ∟∟ outstanding_ratio  | string   | Outstanding ratio                                                                                              |
| ∟∟ outstanding_qty    | int64    | Outstanding quantity                                                                                           |
| ∟∟ conversion_ratio   | string   | Conversion ratio                                                                                               |
| ∟∟ category           | string   | Warrant type <br /><br />**Optional value: **<br />`Call` <br />`Put` <br />`Bull` <br />`Bear` <br />`Inline` |
| ∟∟ strike_price       | string   | Strike price                                                                                                   |
| ∟∟ upper_strike_price | string   | Upper bound price                                                                                              |
| ∟∟ lower_strike_price | string   | Lower bound price                                                                                              |
| ∟∟ call_price         | string   | Call price                                                                                                     |
| ∟∟ underlying_symbol  | string   | Underlying security symbol of the option                                                                       |

### Protobuf

```protobuf
message WarrantQuoteResponse {
  repeated WarrantQuote secu_quote = 2;
}

message WarrantQuote {
  string symbol = 1;
  string last_done = 2;
  string prev_close = 3;
  string open = 4;
  string high = 5;
  string low = 6;
  int64 timestamp = 7;
  int64 volume = 8;
  string turnover = 9;
  TradeStatus trade_status = 10;
  WarrantExtend warrant_extend = 11;
}

message WarrantExtend {
  string implied_volatility = 1;
  string expiry_date = 2;
  string last_trade_date = 3;
  string outstanding_ratio = 4;
  int64  outstanding_qty = 5;
  string conversion_ratio = 6;
  string category = 7;
  string strike_price = 8;
  string upper_strike_price = 9;
  string lower_strike_price = 10;
  string call_price = 11;
  string underlying_symbol = 12;
}
```

### Response JSON Example

```json
{
  "secu_quote": [
    {
      "symbol": "66642.HK",
      "last_done": "0.345",
      "prev_close": "0.365",
      "open": "0.345",
      "high": "0.345",
      "low": "0.345",
      "timestamp": 1651130421,
      "volume": 200000,
      "turnover": "69000.000",
      "warrant_extend": {
        "implied_volatility": "0.319",
        "expiry_date": "20220830",
        "last_trade_date": "20220829",
        "outstanding_ratio": "0.0001",
        "outstanding_qty": 20000,
        "conversion_ratio": "10000",
        "category": "Bear",
        "strike_price": "23200.000",
        "upper_strike_price": "0.000",
        "lower_strike_price": "0.000",
        "call_price": "23100.000",
        "underlying_symbol": "HSI.HK"
      }
    },
    {
      "symbol": "14993.HK",
      "last_done": "0.073",
      "prev_close": "0.066",
      "open": "0.069",
      "high": "0.076",
      "low": "0.069",
      "timestamp": 1651130930,
      "volume": 320825000,
      "turnover": "23401125.000",
      "warrant_extend": {
        "implied_volatility": "0.404",
        "expiry_date": "20220927",
        "last_trade_date": "20220921",
        "outstanding_ratio": "0.0247",
        "outstanding_qty": 2465000,
        "conversion_ratio": "10",
        "category": "Call",
        "strike_price": "70.050",
        "upper_strike_price": "0.000",
        "lower_strike_price": "0.000",
        "call_price": "0.000",
        "underlying_symbol": "2318.HK"
      }
    }
  ]
}
```

## API Restrictions

:::caution

- The HK stocks quotation beyond the 20th will be delayed if the quote level is BMP.

:::

## Error Code

| Protocol Error Code | Business Error Code | Description              | Troubleshooting Suggestions                                   |
| ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- |
| 3                   | 301600              | Invalid request          | Invalid request parameters or unpacking request failed        |
| 3                   | 301606              | Request rate limit       | Reduce the frequency of requests                              |
| 7                   | 301602              | Server error             | Please try again or contact a technician to resolve the issue |
| 7                   | 301607              | Too many request symbols | Reduce the number of symbols in a request                     |

### Push


### Push Real-time Brokers

Real-time brokers data push of the subscribed security.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.set_on_brokers](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.set_on_brokers) |
| JavaScript | [QuoteContext.set_on_brokers](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#set_on_brokers) |
| Rust | [QuoteContext::set_on_brokers](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.set_on_brokers) |
| Go | [QuoteContext.OnBrokers](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.OnBrokers) |
| Java | [QuoteContext.getSet_on_brokers](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getSet_on_brokers) |

:::info

[Business Command](../../socket/protocol/push): `103`

:::

## Data Format

### Properties

| Name         | Type     | Description                           |
| ------------ | -------- | ------------------------------------- |
| symbol       | string   | Security code, for example: `AAPL.US` |
| sequence     | int64    | Sequence number                       |
| ask_brokers  | object[] | Ask brokers                           |
| ∟ position   | int32    | Position                              |
| ∟ broker_ids | int32[]  | [Broker ID](../pull/broker-ids)       |
| bid_brokers  | object[] | Bid brokers                           |
| ∟ position   | int32    | Position                              |
| ∟ broker_ids | int32[]  | [Broker ID](../pull/broker-ids)       |

### Protobuf

```protobuf
message PushBrokers {
  string symbol = 1;
  int64 sequence = 2;
  repeated Brokers ask_brokers = 3;
  repeated Brokers bid_brokers = 4;
}

message Brokers {
  int32 position = 1;
  repeated int32 broker_ids = 2;
}
```

### Example

```python
# Push Real-time Brokers
# https://open.longportapp.com/docs/quote/push/push-brokers
# To subscribe quotes data, please check whether "Developers" - "Quote authority" is correct.
# https://open.longportapp.com/account
#
# - HK Market - BMP basic quotation is unable to subscribe with WebSocket as it has no real-time quote push.
# - US Market - LV1 Nasdaq Basic (Only Open API).
#
# Before running, please visit the "Developers" to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from time import sleep
from longport.openapi import QuoteContext, Config, SubType, PushBrokers

def on_brokers(symbol: str, event: PushBrokers):
    print(symbol, event)

config = Config.from_env()
ctx = QuoteContext(config)
ctx.set_on_brokers(on_brokers)

ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Brokers], is_first_push=True)
sleep(30)
```

### JSON Example

```json
{
  "symbol": "700.HK",
  "sequence": 160808750000000,
  "ask_brokers": [
    {
      "position": 1,
      "broker_ids": [7358, 9057, 9028, 7364]
    },
    {
      "position": 2,
      "broker_ids": [6968, 3448, 3348, 1049, 4973, 6997, 3448, 5465, 6997]
    }
  ],
  "bid_brokers": [
    {
      "position": 1,
      "broker_ids": [6996, 5465, 8026, 8304, 4978]
    },
    {
      "position": 2,
      "broker_ids": [7358, 9057, 9028, 7364]
    }
  ]
}
```

### Push Real-time Depth

Real-time depth data push of the subscribed security.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.set_on_depth](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.set_on_depth) |
| JavaScript | [QuoteContext.set_on_depth](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#set_on_depth) |
| Rust | [QuoteContext::set_on_depth](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.set_on_depth) |
| Go | [QuoteContext.OnDepth](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.OnDepth) |
| Java | [QuoteContext.getSet_on_depth](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getSet_on_depth) |

:::info

[Business Command](../../socket/protocol/push): `102`

:::

## Data Format

### Properties

| Name        | Type     | Description                           |
| ----------- | -------- | ------------------------------------- |
| symbol      | string   | Security code, for example: `AAPL.US` |
| sequence    | int64    | Sequence number                       |
| ask         | object[] | Ask depth                             |
| ∟ position  | int32    | Position                              |
| ∟ price     | string   | Price                                 |
| ∟ volume    | int64    | Volume                                |
| ∟ order_num | int64    | Number of orders                      |
| bid         | object[] | Bid depth                             |
| ∟ position  | int32    | Position                              |
| ∟ price     | string   | Price                                 |
| ∟ volume    | int64    | Volume                                |
| ∟ order_num | int64    | Number of orders                      |

### Protobuf

```protobuf
message PushDepth {
  string symbol = 1;
  int64 sequence = 2;
  repeated Depth ask = 3;
  repeated Depth bid = 4;
}

message Depth {
  int32 position = 1;
  string price = 2;
  int64 volume = 3;
  int64 order_num = 4;
}
```

### Example

```python
# Push Real-time Depth
# https://open.longportapp.com/docs/quote/push/push-depth
# To subscribe quotes data, please check whether "Developers" - "Quote authority" is correct.
# https://open.longportapp.com/account
#
# - HK Market - BMP basic quotation is unable to subscribe with WebSocket as it has no real-time quote push.
# - US Market - LV1 Nasdaq Basic (Only Open API).
#
# Before running, please visit the "Developers" to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from time import sleep
from longport.openapi import QuoteContext, Config, SubType, PushDepth

def on_depth(symbol: str, event: PushDepth):
    print(symbol, event)

config = Config.from_env()
ctx = QuoteContext(config)
ctx.set_on_depth(on_depth)

ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Depth], is_first_push=True)
sleep(30)
```

### JSON Example

```json
{
  "symbol": "700.HK",
  "sequence": 160808750000000,
  "ask": [
    {
      "position": 1,
      "price": "335.000",
      "volume": 500,
      "order_num": 1
    },
    {
      "position": 2,
      "price": "335.200",
      "volume": 400,
      "order_num": 1
    },
    {
      "position": 3,
      "price": "335.400",
      "volume": 500,
      "order_num": 2
    },
    {
      "position": 4,
      "price": "335.600",
      "volume": 1200,
      "order_num": 3
    },
    {
      "position": 5,
      "price": "335.800",
      "volume": 14000,
      "order_num": 8
    }
  ],
  "bid": [
    {
      "position": 1,
      "price": "334.800",
      "volume": 69400,
      "order_num": 13
    },
    {
      "position": 2,
      "price": "334.600",
      "volume": 266600,
      "order_num": 27
    },
    {
      "position": 3,
      "price": "334.400",
      "volume": 61300,
      "order_num": 29
    },
    {
      "position": 4,
      "price": "334.200",
      "volume": 125900,
      "order_num": 31
    },
    {
      "position": 5,
      "price": "334.000",
      "volume": 194600,
      "order_num": 94
    }
  ]
}
```

### Push Real-time Quote

Real-time quote push of the subscribed security. In the pushed data structure, only the fields that have changed will be filled with data.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.set_on_quote](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.set_on_quote) |
| JavaScript | [QuoteContext.set_on_quote](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#set_on_quote) |
| Rust | [QuoteContext::set_on_quote](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.set_on_quote) |
| Go | [QuoteContext.OnQuote](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.OnQuote) |
| Java | [QuoteContext.getSet_on_quote](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getSet_on_quote) |

:::info

[Business Command](../../socket/protocol/push): `101`

:::

## Data Format

### Properties

| Name             | Type   | Description                                                                                                     |
| ---------------- | ------ | --------------------------------------------------------------------------------------------------------------- |
| symbol           | string | Security code, for example: `AAPL.US`                                                                           |
| sequence         | int64  | Sequence number                                                                                                 |
| last_done        | string | Latest price                                                                                                    |
| open             | string | Open                                                                                                            |
| high             | string | High                                                                                                            |
| low              | string | Low                                                                                                             |
| timestamp        | int64  | Time of latest price                                                                                            |
| volume           | int64  | Volume                                                                                                          |
| turnover         | string | Turnover                                                                                                        |
| trade_status     | int32  | Security trading status, see [TradeStatus](../objects#tradestatus---security-status)                            |
| trade_session    | int32  | Trade session, see [TradeSession](../objects#tradesession---trading-session)                                    |
| current_volume   | int32  | Increase volume between pushes                                                                                  |
| current_turnover | string | Increase turnover between pushes                                                                                |
| tag              | int32  | Price tag <br /><br />**Optional value:**<br />`0` - Real-time quote<br />`1` - Revised data after market close |

### Protobuf

```protobuf
message PushQuote {
  string symbol = 1;
  int64 sequence = 2;
  string last_done = 3;
  string open = 4;
  string high = 5;
  string low = 6;
  int64 timestamp = 7;
  int64 volume = 8;
  string turnover = 9;
  TradeStatus trade_status = 10;
  TradeSession trade_session = 11;
}
```

### Example

```python
# Push Real-time Quote
# https://open.longportapp.com/docs/quote/push/push-quote
# To subscribe quotes data, please check whether "Developers" - "Quote authority" is correct.
# https://open.longportapp.com/account
#
# - HK Market - BMP basic quotation is unable to subscribe with WebSocket as it has no real-time quote push.
# - US Market - LV1 Nasdaq Basic (Only Open API).
#
# Before running, please visit the "Developers" to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from time import sleep
from longport.openapi import QuoteContext, Config, SubType, PushQuote

def on_quote(symbol: str, event: PushQuote):
    print(symbol, event)

config = Config.from_env()
ctx = QuoteContext(config)
ctx.set_on_quote(on_quote)

ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote], is_first_push=True)
sleep(30)
```

### JSON Example

```json
{
  "symbol": "AAPL.US",
  "sequence": 160808750000000,
  "last_done": "156.570",
  "open": "155.910",
  "high": "159.790",
  "low": "155.380",
  "timestamp": 1651089600,
  "volume": 88063191,
  "turnover": "13865092584.000",
  "trade_status": 0,
  "trade_session": 0,
  "current_volume": 111234,
  "current_turnover": "23234343454.000",
  "tag": 0
}
```

### Push Real-time Trades

Real-time trades data push of the subscribed security.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.set_on_trades](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.set_on_trades) |
| JavaScript | [QuoteContext.set_on_trades](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#set_on_trades) |
| Rust | [QuoteContext::set_on_trades](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.set_on_trades) |
| Go | [QuoteContext.OnTrade](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.OnTrade) |
| Java | [QuoteContext.getSet_on_trades](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getSet_on_trades) |

:::info

[Business Command](../../socket/protocol/push): `104`

:::

## Data Format

### Properties

| Name            | Type     | Description                                                                                      |
| --------------- | -------- | ------------------------------------------------------------------------------------------------ |
| symbol          | string   | Security code, for example: `AAPL.US`                                                            |
| sequence        | int64    | Sequence number                                                                                  |
| trades          | object[] | Trades data                                                                                      |
| ∟ price         | string   | Price                                                                                            |
| ∟ volume        | int64    | Volume                                                                                           |
| ∟ timestamp     | int64    | Time of trading                                                                                  |
| ∟ trade_type    | string   | [Trade type](#trade-type)                                                                        |
| ∟ direction     | int32    | Trade direction <br /><br />**Optional value:**<br />`0` - neutral<br />`1` - down<br />`2` - up |
| ∟ trade_session | int32    | Trade session, see [TradeSession](../objects#tradesession---trading-session)                     |

#### Trade Type

HK

- `*` - Overseas trade
- `D` - Odd-lot trade
- `M` - Non-direct off-exchange trade
- `P` - Late trade (Off-exchange previous day)
- `U` - Auction trade
- `X` - Direct off-exchange trade
- `Y` - Automatch internalized
- ` ` - Automatch normal

US

- ` ` - Regular sale
- `A` - Acquisition
- `B` - Bunched trade
- `D` - Distribution
- `F` - Intermarket sweep
- `G` - Bunched sold trades
- `H` - Price variation trade
- `I` - Odd lot trade
- `K` - Rule 155 trde(NYSE MKT)
- `M` - Market center close price
- `P` - Prior reference price
- `Q` - Market center open price
- `S` - Split trade
- `V` - Contingent trade
- `W` - Average price trade
- `X` - Cross trade
- `1` - Stopped stock(Regular trade)

### Protobuf

```protobuf
message PushTrade {
  string symbol = 1;
  int64 sequence = 2;
  repeated Trade trade = 3;
}

message Trade {
  string price = 1;
  int64 volume = 2;
  int64 timestamp = 3;
  string trade_type = 4;
  int32 direction = 5;
  TradeSession trade_session = 6;
}
```

### Example

```python
# Push Real-time Trades
# https://open.longportapp.com/docs/quote/push/push-trade
# To subscribe quotes data, please check whether "Developers" - "Quote authority" is correct.
# https://open.longportapp.com/account
#
# - HK Market - BMP basic quotation is unable to subscribe with WebSocket as it has no real-time quote push.
# - US Market - LV1 Nasdaq Basic (Only Open API).
#
# Before running, please visit the "Developers" to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from time import sleep
from longport.openapi import QuoteContext, Config, SubType, PushTrades

def on_trades(symbol: str, event: PushTrades):
    print(symbol, event)

config = Config.from_env()
ctx = QuoteContext(config)
ctx.set_on_trades(on_trade)

ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Trade])
sleep(30)
```

### JSON Example

```json
{
  "symbol": "700.HK",
  "sequence": 160808750000000,
  "trades": [
    {
      "price": "158.760",
      "volume": 1,
      "timestamp": 1651103979,
      "trade_type": "I",
      "direction": 0,
      "trade_session": 2
    },
    {
      "price": "158.745",
      "volume": 1,
      "timestamp": 1651103985,
      "trade_type": "I",
      "direction": 0,
      "trade_session": 2
    },
    {
      "price": "158.800",
      "volume": 1,
      "timestamp": 1651103995,
      "trade_type": "I",
      "direction": 0,
      "trade_session": 2
    }
  ]
}
```

### Security


### Retrieve the List of Securities

Retrieve the List of Securities


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.security_list](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.security_list) |
| JavaScript | [QuoteContext.security_list](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#security_list) |
| Rust | [QuoteContext::security_list](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.security_list) |
| Go | [QuoteContext.Security_list](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Security_list) |
| Java | [QuoteContext.getSecurity_list](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getSecurity_list) |

##

### Request

<table className="http-basic">
<tbody>
<tr><td className="http-basic-key">HTTP Method</td><td>GET</td></tr>
<tr><td className="http-basic-key">HTTP URL</td><td>/v1/quote/get_security_list
</td></tr>
</tbody>
</table>

#### Parameters

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

| Name     | Type   | Required | Description                                 |
| -------- | ------ | -------- | ------------------------------------------- |
| market   | string | YES      | Market, currently only supports US          |
| category | string | YES      | Market subcategory, only supports Overnight |

#### Request Example

```python
from longport.openapi import QuoteContext, Config, Market, SecurityListCategory

config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.security_list(Market.US, SecurityListCategory.Overnight)
print(resp)
```

### Response

#### Response Headers

- Content-Type: application/json

#### Response Example

```json
{
  "code": 0,
  "data": {
    "list": [
      {
        "symbol": "BAC.US",
        "name_cn": "美国银行",
        "name_hk": "美國銀行",
        "name_en": "Bank of America"
      },
      {
        "symbol": "RDDT.US",
        "name_cn": "REDDIT INC",
        "name_hk": "REDDIT INC",
        "name_en": "REDDIT INC"
      },
      {
        "symbol": "GOOGL.US",
        "name_cn": "谷歌-A",
        "name_hk": "谷歌-A",
        "name_en": "Alphabet"
      }
    ]
  }
}
```

#### Response Status

| Status | Description       | Schema                                      |
| ------ | ----------------- | ------------------------------------------- |
| 200    | Successful return | [security_response](#get_security_list_rsp) |
| 400    | Parameter error   | None                                        |

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

## Schemas

### security_response

<a id="get_security_list_rsp"></a>

| Name      | Type     | Required | Description              |
| --------- | -------- | -------- | ------------------------ |
| list      | object[] | false    | List                     |
| ∟ symbol  | integer  | true     | Security code            |
| ∟ name_cn | string   | true     | Chinese name             |
| ∟ name_hk | string   | true     | Traditional Chinese name |
| ∟ name_en | string   | true     | English name             |

## Error Code

| Business Error Code | Description           | Troubleshooting Suggestion                |
| ------------------- | --------------------- | ----------------------------------------- |
| 310010              | Invalid request       | Check the request parameters              |
| 310011              | Internal server error | Please retry or contact technical support |

### Subscribe


### Subscribe Quote

This API is used to subscribe quote.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.subscriptions](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.subscriptions) |
| JavaScript | [QuoteContext.subscriptions](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#subscriptions) |
| Rust | [QuoteContext::subscriptions](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.subscriptions) |
| Go | [QuoteContext.Subscriptions](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Subscriptions) |
| Java | [QuoteContext.getSubscriptions](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getSubscriptions) |

:::info

[Business Command](../../socket/biz-command): `6`

:::

## Request

### Parameters

| Name          | Type     | Required | Description                                                                                                                                                                                                          |
| ------------- | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbol        | string[] | Yes      | Security code list, for example: `[700.HK]` <br /><br />**Check rules:**<br />The maximum number of symbols that can be passed in each request is `500` <br /> The maximum number of subscriptions per user is `500` |
| sub_type      | int32[]  | Yes      | Subscription type, for example: `[1,2]`, see [SubType](../objects#subtype---quote-type-of-subscription)                                                                                                              |
| is_first_push | bool     | Yes      | Whether to perform a data push immediately after subscribing. (trade not supported)                                                                                                                                  |

### Protobuf

```protobuf
message SubscribeRequest {
  repeated string symbol = 1;
  repeated SubType sub_type = 2;
  bool is_first_push = 3;
}
```

### Request Example

```python
# Subscribe Quote
#
# To subscribe quotes data, please check whether "Developers" - "Quote authority" is correct.
# https://open.longportapp.com/account
#
# - HK Market - BMP basic quotation is unable to subscribe with WebSocket as it has no real-time quote push.
# - US Market - LV1 Nasdaq Basic (Only Open API).
#
# Before running, please visit the "Developers" to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from time import sleep
from longport.openapi import QuoteContext, Config, SubType, PushQuote

def on_quote(symbol: str, event: PushQuote):
    print(symbol, event)

config = Config.from_env()
ctx = QuoteContext(config)
ctx.set_on_quote(on_quote)

ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote], is_first_push=True)
sleep(30)
```

## Response

### Response Properties

Returns the securities and types of the successful subscription of this request.

| Name       | Type     | Description                                                                       |
| ---------- | -------- | --------------------------------------------------------------------------------- |
| sub_list   | object[] | Subscription list                                                                 |
| ∟ symbol   | string   | Seurity code                                                                      |
| ∟ sub_type | int32[]  | Subscription type, see [SubType](../objects#subtype---quote-type-of-subscription) |

### Protobuf

```protobuf
message SubscriptionResponse {
  repeated SubTypeList sub_list = 1;
}

message SubTypeList {
  string symbol = 1;
  repeated SubType sub_type = 2;
}
```

### Response JSON Example

```json
{
  "sub_list": [
    {
      "symbol": "700.HK",
      "sub_type": [1, 2, 3]
    },
    {
      "symbol": "AAPL.US",
      "sub_type": [2]
    }
  ]
}
```

## API Restrictions

:::caution

- HK BMP quote level does not support quote push.

:::

## Error Code

| Protocol Error Code | Business Error Code | Description                | Troubleshooting Suggestions                                   |
| ------------------- | ------------------- | -------------------------- | ------------------------------------------------------------- |
| 3                   | 301600              | Invalid request            | Invalid request parameters or unpacking request failed        |
| 3                   | 301606              | Request rate limit         | Reduce the frequency of requests                              |
| 7                   | 301602              | Server error               | Please try again or contact a technician to resolve the issue |
| 7                   | 301605              | Too many subscriptons      | Unsubscribe some subscribed securities                        |
| 7                   | 301600              | Invalue request parameters | Please check the request parameter: `sub_type`                |

### Get Subscription Information

This API is used to obtain the subscription information.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.subscriptions](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.subscriptions) |
| JavaScript | [QuoteContext.subscriptions](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#subscriptions) |
| Rust | [QuoteContext::subscriptions](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.subscriptions) |
| Go | [QuoteContext.Subscriptions](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Subscriptions) |
| Java | [QuoteContext.getSubscriptions](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getSubscriptions) |

:::info

[Business Command](../../socket/biz-command): `5`

:::

## Request

### Protobuf

```protobuf
message SubscriptionRequest {
}
```

### Request Example

```python
from longport.openapi import QuoteContext, Config, SubType
config = Config.from_env()
ctx = QuoteContext(config)

ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
resp = ctx.subscriptions()
print(resp)
```

## Response

### Response Properties

| Name       | Type     | Description                                                                       |
| ---------- | -------- | --------------------------------------------------------------------------------- |
| sub_list   | object[] | Subscribed data                                                                   |
| ∟ symbol   | string   | Security code                                                                     |
| ∟ sub_type | []int32  | Subscription type, see [SubType](../objects#subtype---quote-type-of-subscription) |

### Protobuf

```protobuf
message SubscriptionResponse {
  repeated SubTypeList sub_list = 1;
}

message SubTypeList {
  string symbol = 1;
  repeated SubType sub_type = 2;
}
```

### Response JSON Example

```json
{
  "sub_list": [
    {
      "symbol": "700.HK",
      "sub_type": [1, 2, 3]
    },
    {
      "symbol": "AAPL.US",
      "sub_type": [2]
    }
  ]
}
```

## Error Code

| Protocol Error Code | Business Error Code | Description        | Troubleshooting Suggestions                                   |
| ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- |
| 3                   | 301600              | Invalid request    | Invalid request parameters or unpacking request failed        |
| 3                   | 301606              | Request rate limit | Reduce the frequency of requests                              |
| 7                   | 301602              | Server error       | Please try again or contact a technician to resolve the issue |

### Unsubscribe Quote

This API is used to unsubscribe quote.


## SDK

| Language | Link |
|---|---|
| Python | [QuoteContext.unsubscribe](https://longportapp.github.io/openapi-sdk/python/quote_context/#longport.openapi.QuoteContext.unsubscribe) |
| JavaScript | [QuoteContext.unsubscribe](https://longportapp.github.io/openapi-sdk/js/classes/quote.quotecontext.html#unsubscribe) |
| Rust | [QuoteContext::unsubscribe](https://longportapp.github.io/openapi-sdk/rust/longport/quote/struct.QuoteContext.html#method.unsubscribe) |
| Go | [QuoteContext.Unsubscribe](https://pkg.go.dev/github.com/longportapp/openapi-go/quote#QuoteContext.Unsubscribe) |
| Java | [QuoteContext.getUnsubscribe](https://longportapp.github.io/openapi-sdk/java/com/longport/quote/QuoteContext.html#getUnsubscribe) |

:::info

[Business Command](../../socket/biz-command): `7`

:::

## Request

### Parameters

| Name      | Type     | Required | Description                                                                                                                                                               |
| --------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbol    | string[] | Yes      | Security code list, for example: `[700.HK]` <br /><br />**Check rules:**<br />The maximum number of symbols that can be passed in each request is `500`                   |
| sub_type  | int32[]  | Yes      | Subscription type list, for example: `[1,2]`, see [SubType](../objects#subtype---quote-type-of-subscription)                                                              |
| unsub_all | bool     | Yes      | Is unsubscribe all. <br />- When `symbol` is empty, unsubscribe all subscriptions<br />- When `symbol` is not empty, unsubscribe these all subscriptions of these symbols |

### Protobuf

```protobuf
message UnsubscribeRequest {
  repeated string symbol = 1;
  repeated SubType sub_type = 2;
  bool unsub_all = 3;
}
```

### Request Example

```python
# Unsubscribe Quote
#
# To subscribe quotes data, please check whether "Developers" - "Quote authority" is correct.
# https://open.longportapp.com/account
#
# - HK Market - BMP basic quotation is unable to subscribe with WebSocket as it has no real-time quote push.
# - US Market - LV1 Nasdaq Basic (Only Open API).
#
# Before running, please visit the "Developers" to ensure that the account has the correct quotes authority.
# If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.
from longport.openapi import QuoteContext, Config, SubType
config = Config.from_env()
ctx = QuoteContext(config)

ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
ctx.unsubscribe(["AAPL.US"], [SubType.Quote])
```

## Response

### Protobuf

```protobuf
message UnsubscribeResponse{
}
```

## Error Code

| Protocol Error Code | Business Error Code | Description                | Troubleshooting Suggestions                                   |
| ------------------- | ------------------- | -------------------------- | ------------------------------------------------------------- |
| 3                   | 301600              | Invalid request            | Invalid request parameters or unpacking request failed        |
| 3                   | 301606              | Request rate limit         | Reduce the frequency of requests                              |
| 7                   | 301602              | Server error               | Please try again or contact a technician to resolve the issue |
| 7                   | 301600              | Invalue request parameters | Please check the request parameter: `sub_type`                |

## Trade


## Definition

## OrderType

- Description: HongKong stock support order type

| Enum    | Description                                     |
| ------- | ----------------------------------------------- |
| LO      | Limit Order                                     |
| ELO     | Enhanced Limit Order                            |
| MO      | Market Order                                    |
| AO      | At-auction Order                                |
| ALO     | At-auction Limit Order                          |
| ODD     | Odd Lots Order                                  |
| LIT     | Limit If Touched                                |
| MIT     | Market If Touched                               |
| TSLPAMT | Trailing Limit If Touched (Trailing Amount)     |
| TSLPPCT | Trailing Limit If Touched (Trailing Percent)    |
| SLO     | Special Limit Order. Not Support Replace Order. |

- Description: US stock support order type

| Enum    | Description                                   |
| ------- | --------------------------------------------- |
| LO      | Limit Order                                   |
| MO      | Market Order                                  |
| LIT     | Limit If Touched                              |
| MIT     | Market If Touched                             |
| TSLPAMT | Trailing Limit If Touched (Trailing Amount)   |
| TSLPPCT | Trailing Limit If Touched (Trailing Percent)  |

## OrderStatus

- Description: Order Status

| Enum                 | Description                     |
| -------------------- | ------------------------------- |
| NotReported          | NotReported                     |
| ReplacedNotReported  | NotReported (Replaced Order)    |
| ProtectedNotReported | NotReported (Protected Order)   |
| VarietiesNotReported | NotReported (Conditional Order) |
| FilledStatus         | Filled                          |
| WaitToNew            | Wait To New                     |
| NewStatus            | New                             |
| WaitToReplace        | Wait To Replace                 |
| PendingReplaceStatus | Pending Replace                 |
| ReplacedStatus       | Replaced                        |
| PartialFilledStatus  | Partial Filled                  |
| WaitToCancel         | Wait To Cancel                  |
| PendingCancelStatus  | Pending Cancel                  |
| RejectedStatus       | Rejected                        |
| CanceledStatus       | Canceled                        |
| ExpiredStatus        | Expired                         |
| PartialWithdrawal    | Partial Withdrawal              |

## Market

- Description: Market

| Enum | Description                     |
| ---- | ------------------------------- |
| HK   | Hong Kong Market                |
| US   | United States of America Market |

## WebSocket Notification

- Description: Push notification field description

| field              | type   | Description                                                                                                           |
| ------------------ | ------ | --------------------------------------------------------------------------------------------------------------------- |
| side               | string | order side<br/><br/>**Enum Value**<br/>`Buy`<br />`Sell`                                                              |
| stock_name         | string | stock name                                                                                                            |
| submitted_quantity | string | submitted quantity                                                                                                    |
| symbol             | string | order symbol                                                                                                          |
| order_type         | string | [Order Type](./trade-definition#ordertype)                                                                            |
| submitted_price    | string | submitted price                                                                                                       |
| executed_quantity  | string | executed quantity                                                                                                     |
| executed_price     | string | executed price                                                                                                        |
| order_id           | string | order id                                                                                                              |
| currency           | string | currency                                                                                                              |
| status             | string | [order status](./trade-definition#orderstatus)                                                                        |
| submitted_at       | string | submitted time，formatted as a timestamp (second)                                                                     |
| updated_at         | string | last updated time ，formatted as a timestamp (second)                                                                 |
| trigger_price      | string | "`LIT` / `MIT` order trigger price"                                                                                   |
| msg                | string | rejected message or remark                                                                                            |
| tag                | string | order tag<br/><br/>**Enum Value**<br/>`Normal` - Normal Order<br />`GTC` - Long term Order<br />`Grey` - Grey Order   |
| trigger_status     | string | conditional order trigger status<br/><br/>**Enum Value**<br/>`NOT_USED`<br />`DEACTIVE`<br />`ACTIVE`<br />`RELEASED` |
| trigger_at         | string | conditional order trigger time. formatted as a timestamp (second)                                                     |
| trailing_amount    | string | "`TSLPAMT` order trailing amount"                                                                          |
| trailing_percent   | string | "`TSLPPCT` order trailing percent"                                                                         |
| limit_offset       | string | "`TSLPAMT` / `TSLPPCT` order limit offset amount"                                                                     |
| account_no         | string | account no                                                                                                            |
| remark         | string | remark message                                                                                                           |
| last_share         | string | last share |
| last_price         | string | last price |

### example

```JSON
{
	"event": "order_changed_lb",
	"data": {
		"side": "Buy",
		"stock_name": "Tencent Holdings Ltd.",
		"submitted_quantity": "1000",
		"symbol": "700.HK",
		"order_type": "LO",
		"submitted_price": "213.2",
		"executed_quantity": "1000",
		"executed_price": "213.2",
		"order_id": "27",
		"currency": "HKD",
		"status": "NewStatus",
		"submitted_at": "1562761893",
		"updated_at": "1562761893",
		"trigger_price": "213.0",
		"msg": "Insufficient Qty - 1000",
		"tag": "GTC",
		"trigger_status": "ACTIVE",
		"trigger_at": "1562761893",
		"trailing_amount": "5",
		"trailing_percent": "1",
		"limit_offset": "0.01",
		"account_no": "HK123445",
		"last_share": "100",
		"last_price": "234",
		"remark": "abc"
	}
}
```

## Overview

# Trade Overview

<table>
    <tr>
        <td>Type</td>
        <td>Introduction</td>
    </tr>
    <tr>
        <td rowspan="7">Trade</td>
        <td><a href="./order/submit">Submit Order</a></td>
    </tr>
    <tr>
        <td><a href="./order/replace">Replace Order</a></td>
    </tr>
    <tr>
        <td><a href="./order/withdraw">Withdraw Order</a></td>
    </tr>
    <tr>
        <td><a href="./order/today_orders">Get Today Orders</a></td>
    </tr>
    <tr>
        <td><a href="./order/history_orders">Get History Orders</a></td>
    </tr>
    <tr>
        <td><a href="./execution/today_executions">Get Today Executions</a></td>
    </tr>
    <tr>
        <td><a href="./execution/history_executions">Get History Executions</a></td>
    </tr>
<tr>
        <td rowspan="4">Asset</td>
        <td><a href="./asset/account">Get Account Balance </a></td>
    </tr>
    <tr>
        <td><a href="./asset/cashflow">Get Cash Flow </a></td>
    </tr>
<tr>
        <td><a href="./asset/fund">Get Fund Positions </a></td>
    </tr>
<tr>
        <td><a href="./asset/stock">Get Stock Positions </a></td>
    </tr>
</table>

## Trade Push

Client can get real-time trade updates from trade gateway.

## Example

```python
from time import sleep
from decimal import Decimal
from longport.openapi import TradeContext, Config, OrderSide, OrderType, TimeInForceType, PushOrderChanged, TopicType

def on_order_changed(event: PushOrderChanged):
    print(event)

config = Config.from_env()
ctx = TradeContext(config)
ctx.set_on_order_changed(on_order_changed)
ctx.subscribe([TopicType.Private])

resp = ctx.submit_order(
    side=OrderSide.Buy,
    symbol="700.HK",
    order_type=OrderType.LO,
    submitted_price=Decimal(50),
    submitted_quantity=Decimal(200),
    time_in_force=TimeInForceType.Day,
    remark="Hello from Python SDK",
)
print(resp)
sleep(5)  # waiting for push event

# Finally, unsubscribe
ctx.unsubscribe([TopicType.Private])
```

## Subscribe

<SDKLinks title={false} module="trade" klass="TradeContext" method="subscribe" />

:::info
Cmd: `16`
:::

Protobuf definition:

```protobuf
// Sub is Sub command content, command is 16
message Sub {
  repeated string topics = 1;
}

// SubResponse is response of Sub Request
message SubResponse {
  message Fail {
    string topic = 1;
    string reason = 2;
  }
  repeated string success = 1; // success topics
  repeated Fail fail = 2; // failed topics
  repeated string current = 3;  // curent subscriptions after subscribe
}
```

Current support topics:

- private - private notification for trade

## Cancel Subscribe

<SDKLinks title={false} module="trade" klass="TradeContext" method="unsubscribe" />

:::info
Cmd: `17`
:::

Protobuf defination:

```protobuf
// Unsub is Unsub command content, command is 17
message Unsub {
  repeated string topics = 1;
}

// UnsubResponse is response of Unsub request
message UnsubResponse {
  repeated string current = 3; // current subscriptions after cancel subscribe
}
```

## Push Notification

After we `subscribe` to the trade gateway, we can get real-time trade updates from the trade gateway. The trade gateway will push the corresponding push message to the client. The SDK's `set_on_order_changed` (In Go is: `OnTrade`) can set the callback function of the push message. When the client receives the trade push message, the callback function will be called.

<SDKLinks title={false} module="trade" klass="TradeContext" method="set_on_order_changed" go="OnTrade" />

:::info
Cmd: `18`
:::

Protobuf defination:

```protobuf
// Dispatch type
enum DispatchType {
  DISPATCH_UNDEFINED = 0;
  DISPATCH_DIRECT = 1;
  DISPATCH_BROADCAST = 2;
}

enum ContentType {
  CONTENT_UNDEFINED = 0;
  CONTENT_JSON = 1;
  CONTENT_PROTO = 2;
}

// Notification is push message, command is 18
message Notification {
  string topic = 1;
  ContentType content_type = 2;
  DispatchType dispatch_type = 3;
  bytes data = 4;
}
```

### Asset


### Get Account Balance

The API is used to obtain the available, desirable, frozen, to-be-settled, and in-transit
funds (fund purchase and redemption) information for each currency of the user.


## SDK

| Language | Link |
|---|---|
| Python | [TradeContext.account_balance](https://longportapp.github.io/openapi-sdk/python/trade_context/#longport.openapi.TradeContext.account_balance) |
| JavaScript | [TradeContext.account_balance](https://longportapp.github.io/openapi-sdk/js/classes/trade.tradecontext.html#account_balance) |
| Rust | [TradeContext::account_balance](https://longportapp.github.io/openapi-sdk/rust/longport/trade/struct.TradeContext.html#method.account_balance) |
| Go | [TradeContext.Account_balance](https://pkg.go.dev/github.com/longportapp/openapi-go/trade#TradeContext.Account_balance) |
| Java | [TradeContext.getAccount_balance](https://longportapp.github.io/openapi-sdk/java/com/longport/trade/TradeContext.html#getAccount_balance) |

## 

## Request

<table className="http-basic">
<tbody>
<tr><td className="http-basic-key">HTTP Method</td><td>GET</td></tr>
<tr><td className="http-basic-key">HTTP URL</td><td>/v1/asset/account 
</td></tr>
</tbody>
</table>

### Parameters

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

| Name | Type | Required | Description |
|---|---|---|---|
| currency | string | NO | Currency (HKD, USD, CNH) |

### Request Example

```python
# Get Account Balance
# https://open.longportapp.com/docs/trade/asset/account
from longport.openapi import TradeContext, Config

config = Config.from_env()
ctx = TradeContext(config)
resp = ctx.account_balance()
print(resp)
```

## Response

### Response Headers

- Content-Type: application/json

### Response Example

```json
{
  "code": 0,
  "data": {
    "list": [
      {
        "total_cash": "1759070010.72",
        "max_finance_amount": "977582000",
        "remaining_finance_amount": "0",
        "risk_level": "1",
        "margin_call": "2598051051.50",
        "currency": "HKD",
        "net_assets": "24145.90",
        "init_margin": "1540.09",
        "maintenance_margin": "1540.09",
        "buy_power": "1759070.12",
        "cash_infos": [
          {
            "withdraw_cash": "97592.30",
            "available_cash": "195902464.37",
            "frozen_cash": "11579339.13",
            "settling_cash": "207288537.81",
            "currency": "HKD"
          },
          {
            "withdraw_cash": "199893416.74",
            "available_cash": "199893416.74",
            "frozen_cash": "28723.76",
            "settling_cash": "-276806.51",
            "currency": "USD"
          }
        ]
      }
    ]
  }
}
```

### Response Status

| Status | Description | Schema |
|---|---|---|
| 200 | Success | [accountcash_rsp](#schemaaccountcash_rsp) |
| 400 | Internal Error | None |

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

## Schemas

### accountcash_rsp

<a id="schemaaccountcash_rsp"></a>
<a id="schemaaccountcash_rsp"></a>

|Name|Type|Required|Description|
|---|---|---|---|
|list|object[]|false|Account Balance|
|∟ total_cash|string|true|Total Cash|
|∟ max_finance_amount|string|true|Maximum Financing Amount|
|∟ remaining_finance_amount|string|true|Remaining Financing Amount|
|∟ risk_level|string|true|Risk control level  <br/> <br/> <b>Option:</b><br/> `0` - safe <br/> `1` - medium risk<br/> `2` - early warning<br/> `3` - danger|
|∟ margin_call|string|true|Margin Call|
|∟ net_assets|string|true|net asset|
|∟ init_margin|string|true|initial margin|
|∟ maintenance_margin|string|true|maintenance margin|
|∟ currency|string|true|Currency|
|∟ buy_power|string|true|Buy Power|
|∟ cash_infos|object[]|false|Cash Details|
|∟∟ withdraw_cash|string|true|Withdraw Cash|
|∟∟ available_cash|string|true|Available Cash|
|∟∟ frozen_cash|string|true|Frozen Cash|
|∟∟ settling_cash|string|true|Cash to be Settled|
|∟∟ currency|string|true|Currency|

### Get Cash Flow

The API is used to obtain capital inflow/outflow direction, capital type, capital amount, occurrence time,
associated stock code and capital flow description information.


## SDK

| Language | Link |
|---|---|
| Python | [TradeContext.cash_flow](https://longportapp.github.io/openapi-sdk/python/trade_context/#longport.openapi.TradeContext.cash_flow) |
| JavaScript | [TradeContext.cash_flow](https://longportapp.github.io/openapi-sdk/js/classes/trade.tradecontext.html#cash_flow) |
| Rust | [TradeContext::cash_flow](https://longportapp.github.io/openapi-sdk/rust/longport/trade/struct.TradeContext.html#method.cash_flow) |
| Go | [TradeContext.Cash_flow](https://pkg.go.dev/github.com/longportapp/openapi-go/trade#TradeContext.Cash_flow) |
| Java | [TradeContext.getCash_flow](https://longportapp.github.io/openapi-sdk/java/com/longport/trade/TradeContext.html#getCash_flow) |

## 

## Request

<table className="http-basic">
<tbody>
<tr><td className="http-basic-key">HTTP Method</td><td>GET</td></tr>
<tr><td className="http-basic-key">HTTP URL</td><td>/v1/asset/cashflow 
</td></tr>
</tbody>
</table>

### Parameters

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

| Name | Type | Required | Description |
|---|---|---|---|
| start_time | string | YES | start time timestamp, in `seconds`, E.g:`1650037563` |
| end_time | string | YES | end time timestamp, in `seconds`, E.g:`1650747581` |
| business_type | string | NO | Balance type<br/><br/> <b>Option:</b> <br/>`1` - cash <br/>`2` - stock<br/> `3` - fund |
| symbol | string | NO | Target code, E.g:`AAPL.US` |
| page | string | NO | start page <br/><br/><b>Default value:</b> `1`  <br/><b>Data validation rules:</b><br/> <b>Ranges:</b> `>=1` |
| size | string | NO | page size <br/><br/><b>Default value:</b> `50` <br/><b>Data validation rules:</b> `1~10000` |

### Request Example

```python
# Get Cash Flow
# https://open.longportapp.com/docs/trade/asset/cashflow
from datetime import datetime
from longport.openapi import TradeContext, Config

config = Config.from_env()
ctx = TradeContext(config)
resp = ctx.cash_flow(
    start_at = datetime(2022, 5, 9),
    end_at = datetime(2022, 5, 12),
)
print(resp)
```

## Response

### Response Headers

- Content-Type: application/json

### Response Example

```json
{
  "code": 0,
  "data": {
    "list": [
      {
        "transaction_flow_name": "BuyContract-Stocks",
        "direction": 1,
        "balance": "-248.60",
        "currency": "USD",
        "business_time": "1621507957",
        "symbol": "AAPL.US",
        "description": "AAPL"
      },
      {
        "transaction_flow_name": "BuyContract-Stocks",
        "direction": 1,
        "balance": "-125.16",
        "currency": "USD",
        "business_time": "1621504824",
        "symbol": "AAPL.US",
        "description": "AAPL"
      }
    ]
  }
}
```

### Response Status

| Status | Description | Schema |
|---|---|---|
| 200 | Success | [cashflow_rsp](#schemacashflow_rsp) |
| 400 | Internal Error | None |

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

## Schemas

### cashflow_rsp

<a id="schemacashflow_rsp"></a>
<a id="schemacashflow_rsp"></a>

|Name|Type|Required|Description|
|---|---|---|---|
|list|object[]|false|Cash flow info|
|∟ transaction_flow_name|string|true|Cash flow name|
|∟ direction|string|true|outflow direction <br/><br/><b>Option:</b> <br/>`1` - outflow <br/>  `2` - inflow|
|∟ business_type|string|true|Funding Category <br/><br/><b>Option:</b> <br/>`1` - cash <br/> `2` - stock <br/> `3` - fund|
|∟ balance|string|true|Cash amount|
|∟ currency|string|true|Cash Currency|
|∟ business_time|string|true|business time|
|∟ symbol|string|false|associated Stock code information|
|∟ description|string|false|Cash flow description|

### Get Fund Positions

The API is used to obtain fund position information including account, fund code, holding share, cost net worth,
current net worth, and currency.


## SDK

| Language | Link |
|---|---|
| Python | [TradeContext.fund_positions](https://longportapp.github.io/openapi-sdk/python/trade_context/#longport.openapi.TradeContext.fund_positions) |
| JavaScript | [TradeContext.fund_positions](https://longportapp.github.io/openapi-sdk/js/classes/trade.tradecontext.html#fund_positions) |
| Rust | [TradeContext::fund_positions](https://longportapp.github.io/openapi-sdk/rust/longport/trade/struct.TradeContext.html#method.fund_positions) |
| Go | [TradeContext.Fund_positions](https://pkg.go.dev/github.com/longportapp/openapi-go/trade#TradeContext.Fund_positions) |
| Java | [TradeContext.getFund_positions](https://longportapp.github.io/openapi-sdk/java/com/longport/trade/TradeContext.html#getFund_positions) |

## 

## Request

<table className="http-basic">
<tbody>
<tr><td className="http-basic-key">HTTP Method</td><td>GET</td></tr>
<tr><td className="http-basic-key">HTTP URL</td><td>/v1/asset/fund 
</td></tr>
</tbody>
</table>

### Parameters

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

| Name | Type | Required | Description |
|---|---|---|---|
| symbol | string[] | NO | Fund code, in `ISIN` format, E.g:`HK0000676327` <a href="https://en.wikipedia.org/wiki/International_Securities_Identification_Number">ISIN explain</a> |

### Request Example

```python
# Get Fund Position
# https://open.longportapp.com/docs/trade/asset/fund
from longport.openapi import TradeContext, Config

config = Config.from_env()
ctx = TradeContext(config)
resp = ctx.fund_positions()
print(resp)
```

## Response

### Response Headers

- Content-Type: application/json

### Response Example

```json
{
  "code": 0,
  "data": {
    "list": [
      {
        "account_channel": "lb",
        "fund_info": [
          {
            "symbol": "HK0000447943",
            "symbol_name": "GAOTENG EMERGING MARKETS PLUS  LONG/SHORT FIXED INCOME ALPHA FUND",
            "currency": "USD",
            "holding_units": "5.000",
            "current_net_asset_value": "0",
            "cost_net_asset_value": "0.00",
            "net_asset_value_day": "1649865600"
          }
        ]
      }
    ]
  }
}
```

### Response Status

| Status | Description | Schema |
|---|---|---|
| 200 | Success | [fund_rsp](#schemafund_rsp) |
| 400 | Internal Error | None |

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

## Schemas

### fund_rsp

<a id="schemafund_rsp"></a>
<a id="schemafund_rsp"></a>

|Name|Type|Required|Description|
|---|---|---|---|
|list|object[]|false|stock holding information|
|∟ account_channel|string|true|account type|
|∟ fund_info|object[]|false|Fund Details|
|∟∟ symbol|string|true|Fund ISIN code|
|∟∟ current_net_asset_value|string|true|current Equity|
|∟∟ net_asset_value_day|string|true|current Equity time|
|∟∟ symbol_name|string|true|Fund name|
|∟∟ currency|string|true|Currency|
|∟∟ cost_net_asset_value|string|true|Net Cost|

### Get margin ratio

This API is used to obtain the initial margin ratio, maintain the margin ratio and strengthen the
margin ratio of stocks.


## SDK

| Language | Link |
|---|---|
| Python | [TradeContext.margin_ratio](https://longportapp.github.io/openapi-sdk/python/trade_context/#longport.openapi.TradeContext.margin_ratio) |
| JavaScript | [TradeContext.margin_ratio](https://longportapp.github.io/openapi-sdk/js/classes/trade.tradecontext.html#margin_ratio) |
| Rust | [TradeContext::margin_ratio](https://longportapp.github.io/openapi-sdk/rust/longport/trade/struct.TradeContext.html#method.margin_ratio) |
| Go | [TradeContext.Margin_ratio](https://pkg.go.dev/github.com/longportapp/openapi-go/trade#TradeContext.Margin_ratio) |
| Java | [TradeContext.getMargin_ratio](https://longportapp.github.io/openapi-sdk/java/com/longport/trade/TradeContext.html#getMargin_ratio) |

## 

## Request

<table className="http-basic">
<tbody>
<tr><td className="http-basic-key">HTTP Method</td><td>GET</td></tr>
<tr><td className="http-basic-key">HTTP URL</td><td>/v1/risk/margin-ratio 
</td></tr>
</tbody>
</table>

### Parameters

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

| Name | Type | Required | Description |
|---|---|---|---|
| symbol | string | YES | Stock symbol, using the format `ticker.region`, for example: `AAPL.US` |

### Request Example

```python
from datetime import datetime
from longport.openapi import TradeContext, Config

config = Config.from_env()
ctx = TradeContext(config)
resp = ctx.margin_ratio("700.HK")
print(resp)
```

## Response

### Response Headers

- Content-Type: application/json

### Response Example

```json
{
  "code": 0,
  "data": {
    "im_factor": "0.1",
    "mm_factor": "0.1",
    "fm_factor": "0.1"
  }
}
```

### Response Status

| Status | Description | Schema |
|---|---|---|
| 200 | Success | [margin_ratio_rsp](#schemamargin_ratio_rsp) |
| 400 | Internal Error | None |

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

## Schemas

### margin_ratio_rsp

<a id="schemamargin_ratio_rsp"></a>
<a id="schemamargin_ratio_rsp"></a>

|Name|Type|Required|Description|
|---|---|---|---|
|im_factor|string|true|Initial margin ratio|
|mm_factor|string|true|Maintain the initial margin ratio|
|fm_factor|string|true|Forced close-out margin ratio|

### Get Stock Positions

The API is used to obtain stock position information including account, stock code, number of shares held,
number of available shares, average position price (calculated according to account settings), and currency.


## SDK

| Language | Link |
|---|---|
| Python | [TradeContext.stock_positions](https://longportapp.github.io/openapi-sdk/python/trade_context/#longport.openapi.TradeContext.stock_positions) |
| JavaScript | [TradeContext.stock_positions](https://longportapp.github.io/openapi-sdk/js/classes/trade.tradecontext.html#stock_positions) |
| Rust | [TradeContext::stock_positions](https://longportapp.github.io/openapi-sdk/rust/longport/trade/struct.TradeContext.html#method.stock_positions) |
| Go | [TradeContext.Stock_positions](https://pkg.go.dev/github.com/longportapp/openapi-go/trade#TradeContext.Stock_positions) |
| Java | [TradeContext.getStock_positions](https://longportapp.github.io/openapi-sdk/java/com/longport/trade/TradeContext.html#getStock_positions) |

## 

## Request

<table className="http-basic">
<tbody>
<tr><td className="http-basic-key">HTTP Method</td><td>GET</td></tr>
<tr><td className="http-basic-key">HTTP URL</td><td>/v1/asset/stock 
</td></tr>
</tbody>
</table>

### Parameters

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

| Name | Type | Required | Description |
|---|---|---|---|
| symbol | string[] | NO | Stock code, use `ticker.region` format, E.g:`AAPL.US` |

### Request Example

```python
# Get Stock Positions
# https://open.longportapp.com/docs/trade/asset/stock
from longport.openapi import TradeContext, Config

config = Config.from_env()
ctx = TradeContext(config)
resp = ctx.stock_positions()
print(resp)
```

## Response

### Response Headers

- Content-Type: application/json

### Response Example

```json
{
  "code": 0,
  "data": {
    "list": [
      {
        "account_channel": "lb",
        "stock_info": [
          {
            "symbol": "700.HK",
            "symbol_name": "TENCENT",
            "currency": "HKD",
            "quantity": "650",
            "market": "HK",
            "available_quantity": "-450",
            "cost_price": "457.53",
            "init_quantity": "214"
          },
          {
            "symbol": "9991.HK",
            "symbol_name": "BAOZUN-SW",
            "currency": "HKD",
            "market": "HK",
            "quantity": "200",
            "available_quantity": "0",
            "cost_price": "32.25",
            "init_quantity": "214"
          },
          {
            "symbol": "TCEHY.US",
            "symbol_name": "Tencent (ADR)",
            "currency": "USD",
            "market": "US",
            "quantity": "10",
            "available_quantity": "10",
            "init_quantity": "18"
          },
          {
            "symbol": "2628.HK",
            "symbol_name": "CHINA LIFE",
            "currency": "HKD",
            "market": "HK",
            "quantity": "9000",
            "available_quantity": "0",
            "init_quantity": "8000"
          },
          {
            "symbol": "5.HK",
            "symbol_name": "HSBC HOLDINGS",
            "currency": "HKD",
            "market": "HK",
            "quantity": "2400",
            "available_quantity": "2000",
            "init_quantity": "2000"
          },
          {
            "symbol": "BABA.US",
            "symbol_name": "Alibaba",
            "currency": "USD",
            "market": "US",
            "quantity": "2000209",
            "available_quantity": "2000209",
            "init_quantity": "214"
          },
          {
            "symbol": "2.HK",
            "symbol_name": "CLP HOLDINGS",
            "currency": "HKD",
            "market": "HK",
            "quantity": "2000",
            "available_quantity": "2000",
            "init_quantity": "2000"
          },
          {
            "symbol": "NOK.US",
            "symbol_name": "Nokia",
            "currency": "USD",
            "market": "US",
            "quantity": "1",
            "available_quantity": "0",
            "init_quantity": "1"
          }
        ]
      }
    ]
  }
}
```

### Response Status

| Status | Description | Schema |
|---|---|---|
| 200 | Success | [stock_rsp](#schemastock_rsp) |
| 400 | Internal Error | None |

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

## Schemas

### stock_rsp

<a id="schemastock_rsp"></a>
<a id="schemastock_rsp"></a>

|Name|Type|Required|Description|
|---|---|---|---|
|list|object[]|false|Stock holding information|
|∟ account_channel|string|true|Account type|
|∟ stock_info|object[]|false|Stock list|
|∟∟ symbol|string|true|Stock code|
|∟∟ symbol_name|string|true|Stock name|
|∟∟ quantity|string|true|The number of holdings|
|∟∟ available_quantity|string|false|Available quantity|
|∟∟ currency|string|true|Currency|
|∟∟ market|string|true|market|
|∟∟ cost_price|string|true|Cost Price(According to the client's choice of average purchase or diluted cost)|
|∟∟ init_quantity|string|false|Initial position before market opening|

### Execution


### Get History Executions

This API is used to get history executions, including the sell and buy records.


## SDK

| Language | Link |
|---|---|
| Python | [TradeContext.history_executions](https://longportapp.github.io/openapi-sdk/python/trade_context/#longport.openapi.TradeContext.history_executions) |
| JavaScript | [TradeContext.history_executions](https://longportapp.github.io/openapi-sdk/js/classes/trade.tradecontext.html#history_executions) |
| Rust | [TradeContext::history_executions](https://longportapp.github.io/openapi-sdk/rust/longport/trade/struct.TradeContext.html#method.history_executions) |
| Go | [TradeContext.History_executions](https://pkg.go.dev/github.com/longportapp/openapi-go/trade#TradeContext.History_executions) |
| Java | [TradeContext.getHistory_executions](https://longportapp.github.io/openapi-sdk/java/com/longport/trade/TradeContext.html#getHistory_executions) |

## 

## Request

<table className="http-basic">
<tbody>
<tr><td className="http-basic-key">HTTP Method</td><td>GET</td></tr>
<tr><td className="http-basic-key">HTTP URL</td><td>/v1/trade/execution/history 
</td></tr>
</tbody>
</table>

### Parameters

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

| Name | Type | Required | Description |
|---|---|---|---|
| symbol | string | NO | Stock symbol, use `ticker.region` format, example: `AAPL.US` |
| start_at | string | NO | Start time, formatted as a timestamp (second), example: `1650410999`.<br/><br/> If the start time is null, the default is the 90 days before of the end time or 90 days before of the current time. |
| end_at | string | NO | End time, formatted as a timestamp (second), example: `1650410999`. <br/><br/> If the end time is null, the default is the current time or 90 days after of the start time. |

### Request Example

```python
from datetime import datetime
from longport.openapi import TradeContext, Config

config = Config.from_env()
ctx = TradeContext(config)

resp = ctx.history_executions(
    symbol = "700.HK",
    start_at = datetime(2022, 5, 9),
    end_at = datetime(2022, 5, 12),
)
print(resp)
```

## Response

### Response Headers

- Content-Type: application/json

### Response Example

```json
{
  "code": 0,
  "message": "success",
  "data": {
    "has_more": false,
    "trades": [
      {
        "order_id": "693664675163312128",
        "price": "388",
        "quantity": "100",
        "symbol": "700.HK",
        "trade_done_at": "1648611351",
        "trade_id": "693664675163312128-1648611351433741210"
      }
    ]
  }
}
```

### Response Status

| Status | Description | Schema |
|---|---|---|
| 200 | Get History Executions Success | [history_executions_rsp](#schemahistory_executions_rsp) |
| 400 | The query failed with an error in the request parameter. | None |

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

## Schemas

### history_executions_rsp

<a id="schemahistory_executions_rsp"></a>
<a id="schemahistory_executions_rsp"></a>

|Name|Type|Required|Description|
|---|---|---|---|
|has_more|boolean|true|has more orders record.<br/><br/>The maximum number of orders per query is 1000, if the number of results exceeds 1000, then has_more will be true|
|trades|object[]|false|Execution Detail|
|∟ order_id|string|true|Order ID|
|∟ trade_id|string|true|Execution ID|
|∟ symbol|string|true|Stock symbol, use `ticker.region` format,example: `AAPL.US`|
|∟ trade_done_at|string|true|Trade done time, formatted as a timestamp (second)|
|∟ quantity|string|true|Executed quantity|
|∟ price|string|true|Executed price|

### Get Today Executions

This API is used to get today executions.


## SDK

| Language | Link |
|---|---|
| Python | [TradeContext.today_executions](https://longportapp.github.io/openapi-sdk/python/trade_context/#longport.openapi.TradeContext.today_executions) |
| JavaScript | [TradeContext.today_executions](https://longportapp.github.io/openapi-sdk/js/classes/trade.tradecontext.html#today_executions) |
| Rust | [TradeContext::today_executions](https://longportapp.github.io/openapi-sdk/rust/longport/trade/struct.TradeContext.html#method.today_executions) |
| Go | [TradeContext.Today_executions](https://pkg.go.dev/github.com/longportapp/openapi-go/trade#TradeContext.Today_executions) |
| Java | [TradeContext.getToday_executions](https://longportapp.github.io/openapi-sdk/java/com/longport/trade/TradeContext.html#getToday_executions) |

## 

## Request

<table className="http-basic">
<tbody>
<tr><td className="http-basic-key">HTTP Method</td><td>GET</td></tr>
<tr><td className="http-basic-key">HTTP URL</td><td>/v1/trade/execution/today 
</td></tr>
</tbody>
</table>

### Parameters

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

| Name | Type | Required | Description |
|---|---|---|---|
| symbol | string | NO | Stock symbol, use `ticker.region` format, example: `AAPL.US` |
| order_id | string | NO | Order ID, example: `701276261045858304` |

### Request Example

```python
from longport.openapi import TradeContext, Config

config = Config.from_env()
ctx = TradeContext(config)

resp = ctx.today_executions(symbol = "700.HK")
print(resp)
```

## Response

### Response Headers

- Content-Type: application/json

### Response Example

```json
{
  "code": 0,
  "message": "success",
  "data": {
    "trades": [
      {
        "order_id": "693664675163312128",
        "price": "388",
        "quantity": "100",
        "symbol": "700.HK",
        "trade_done_at": "1648611351",
        "trade_id": "693664675163312128-1648611351433741210"
      }
    ]
  }
}
```

### Response Status

| Status | Description | Schema |
|---|---|---|
| 200 | Get Today Executions Success | None |
| 400 | The query failed with an error in the request parameter. | None |

### Response Schema

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

## Schemas

### today_executions_rsp

<a id="schematoday_executions_rsp"></a>
<a id="schematoday_executions_rsp"></a>

|Name|Type|Required|Description|
|---|---|---|---|
|trades|object[]|false|Execution Detail|
|∟ order_id|string|true|Order ID|
|∟ trade_id|string|true|Execution ID|
|∟ symbol|string|true|Stock symbol, use `ticker.region` format, example: `AAPL.US`|
|∟ trade_done_at|string|true|Trade done time, formatted as a timestamp (second)|
|∟ quantity|string|true|Executed quantity|
|∟ price|string|true|Executed price|

### Order


### Estimate Maximum Purchase Quantity

This API is used for estimating the maximum purchase quantity for Hong Kong and US stocks, warrants, and options.


## SDK

| Language | Link |
|---|---|
| Python | [TradeContext.estimate_max_purchase_quantity](https://longportapp.github.io/openapi-sdk/python/trade_context/#longport.openapi.TradeContext.estimate_max_purchase_quantity) |
| JavaScript | [TradeContext.estimate_max_purchase_quantity](https://longportapp.github.io/openapi-sdk/js/classes/trade.tradecontext.html#estimate_max_purchase_quantity) |
| Rust | [TradeContext::estimate_max_purchase_quantity](https://longportapp.github.io/openapi-sdk/rust/longport/trade/struct.TradeContext.html#method.estimate_max_purchase_quantity) |
| Go | [TradeContext.Estimate_max_purchase_quantity](https://pkg.go.dev/github.com/longportapp/openapi-go/trade#TradeContext.Estimate_max_purchase_quantity) |
| Java | [TradeContext.getEstimate_max_purchase_quantity](https://longportapp.github.io/openapi-sdk/java/com/longport/trade/TradeContext.html#getEstimate_max_purchase_quantity) |

## 

## Request

<table className="http-basic">
<tbody>
<tr><td className="http-basic-key">HTTP Method</td><td>GET</td></tr>
<tr><td className="http-basic-key">HTTP URL</td><td>/v1/trade/estimate/buy_limit 
</td></tr>
</tbody>
</table>

### Parameters

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

| Name | Type | Required | Description |
|---|---|---|---|
| symbol | string | YES | Stock code, using ticker.region format, for example: `AAPL.US` |
| order_type | string | YES | [Order Type](../trade-definition#ordertype) |
| price | string | NO | Estimated order price, for example: `388.5` |
| side | string | YES | Order side<br/><br/> **Enum Value**<br/> `Buy` - Buy<br/> `Sell` - Sell (Short selling is only supported for US stocks) |
| currency | string | NO | Settlement currency |
| order_id | string | NO | Order ID, required when estimating the maximum purchase quantity for a modified order |

### Request Example

```python
from longport.openapi import TradeContext, Config, OrderStatus, OrderType, OrderSide

config = Config.from_env()
ctx = TradeContext(config)

resp = ctx.estimate_max_purchase_quantity(
    symbol = "700.HK",
    order_type = OrderType.LO,
    side = OrderSide.Buy,
)
print(resp)
```

## Response

### Response Headers

- Content-Type: application/json

### Response Example

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

### Response Status

| Status | Description | Schema |
|---|---|---|
| 200 | Estimate Maximum Purchase Quantity Success | [estimate_available_buy_limit_rsp](#schemaestimate_available_buy_limit_rsp) |
| 400 | The query failed with an error in the request parameter. | None |

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

## Schemas

### estimate_available_buy_limit_rsp

<a id="schemaestimate_available_buy_limit_rsp"></a>
<a id="schemaestimate_available_buy_limit_rsp"></a>

Estimated Maximum Purchase Quantity

|Name|Type|Required|Description|
|---|---|---|---|
|cash_max_qty|string|true|Cash available quantity, default value is empty string.|
|margin_max_qty|string|true|Margin available quantity, default value is empty string.|

### Get History Deals



### Get History Order

This API is used to get history order.


## SDK

| Language | Link |
|---|---|
| Python | [TradeContext.history_orders](https://longportapp.github.io/openapi-sdk/python/trade_context/#longport.openapi.TradeContext.history_orders) |
| JavaScript | [TradeContext.history_orders](https://longportapp.github.io/openapi-sdk/js/classes/trade.tradecontext.html#history_orders) |
| Rust | [TradeContext::history_orders](https://longportapp.github.io/openapi-sdk/rust/longport/trade/struct.TradeContext.html#method.history_orders) |
| Go | [TradeContext.History_orders](https://pkg.go.dev/github.com/longportapp/openapi-go/trade#TradeContext.History_orders) |
| Java | [TradeContext.getHistory_orders](https://longportapp.github.io/openapi-sdk/java/com/longport/trade/TradeContext.html#getHistory_orders) |

## 

## Request

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

### Parameters

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

| Name | Type | Required | Description |
|---|---|---|---|
| symbol | string | NO | Stock symbol, use `ticker.region` format, example: `AAPL.US` |
| status | string[] | NO | [Order status](../trade-definition#orderstatus)<br/><br/>example: `status=FilledStatus&status=NewStatus` |
| side | string | NO | Order side<br/><br/> **Enum Value:**<br/> `Buy`<br/> `Sell` |
| market | string | NO | Market<br/><br/> **Enum Value:**<br/> `US` - United States of America Market<br/> `HK` - Hong Kong Market |
| start_at | string | NO | Start time, formatted as a timestamp (second), example: `1650410999`.<br/><br/> If the start time is null, the default is the 90 days before of the end time or 90 days before of the current time. |
| end_at | string | NO | End time, formatted as a timestamp (second), example: `1650410999`. <br/><br/> If the end time is null, the default is the current time or 90 days after of the start time. |

### Request Example

```python
from datetime import datetime
from longport.openapi import TradeContext, Config, OrderStatus, OrderSide, Market

config = Config.from_env()
ctx = TradeContext(config)

resp = ctx.history_orders(
    symbol = "700.HK",
    status = [OrderStatus.Filled, OrderStatus.New],
    side = OrderSide.Buy,
    market = Market.HK,
    start_at = datetime(2022, 5, 9),
    end_at = datetime(2022, 5, 12),
)
print(resp)
```

## Response

### Response Headers

- Content-Type: application/json

### Response Example

```json
{
  "code": 0,
  "message": "success",
  "data": {
    "orders": [
      {
        "currency": "HKD",
        "executed_price": "0.000",
        "executed_quantity": "0",
        "expire_date": "",
        "last_done": "",
        "limit_offset": "",
        "msg": "",
        "order_id": "706388312699592704",
        "order_type": "ELO",
        "outside_rth": "UnknownOutsideRth",
        "price": "11.900",
        "quantity": "200",
        "side": "Buy",
        "status": "RejectedStatus",
        "stock_name": "Bank of East Asia Ltd/The",
        "submitted_at": "1651644897",
        "symbol": "23.HK",
        "tag": "Normal",
        "time_in_force": "Day",
        "trailing_amount": "",
        "trailing_percent": "",
        "trigger_at": "0",
        "trigger_price": "",
        "trigger_status": "NOT_USED",
        "updated_at": "1651644898",
        "remark": ""
      }
    ]
  }
}
```

### Response Status

| Status | Description | Schema |
|---|---|---|
| 200 | Get History Orders Success | [history_orders_rsp](#schemahistory_orders_rsp) |
| 400 | The query failed with an error in the request parameter. | None |

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

## Schemas

### history_orders_rsp

<a id="schemahistory_orders_rsp"></a>
<a id="schemahistory_orders_rsp"></a>

|Name|Type|Required|Description|
|---|---|---|---|
|has_more|boolean|true|has more orders record.<br/><br/>The maximum number of orders per query is 1000, if the number of results exceeds 1000, then has_more will be true|
|orders|object[]|false|Order Detail|
|∟ order_id|string|true|Order ID|
|∟ status|string|true|[Order Status](../trade-definition#orderstatus)|
|∟ stock_name|string|true|Stock Name|
|∟ quantity|string|true|Submitted Quantity|
|∟ executed_quantity|string|true|Executed Quantity.<br/><br/>when the order is not filled, value is 0|
|∟ price|string|true|Submitted Price.<br/><br/>when market condition order is not triggered, value is empty string|
|∟ executed_price|string|true|Executed Price.<br/><br/>when the order is not filled, value is 0|
|∟ submitted_at|string|true|Submitted Time|
|∟ side|string|true|Order Side<br/><br/> **Enum Value:**<br/> `Buy`<br/> `Sell`|
|∟ symbol|string|true|Stock symbol, use `ticker.region` format, example: `AAPL.US`|
|∟ order_type|string|true|[Order Type](../trade-definition#ordertype)|
|∟ last_done|string|true|Last done.<br/><br/>when the order is not filled, value is empty string|
|∟ trigger_price|string|true|`LIT` / `MIT` Order Trigger Price.<br/><br/>When the order is not `LIT` / `MIT` order, value is empty string|
|∟ msg|string|true|Rejected message or remark, default value is empty string.|
|∟ tag|string|true|Order tag<br/><br/> **Enum Value**<br/> `Normal` - Normal Order<br/> `GTC` - Long term Order<br/> `Grey` - Grey Order|
|∟ time_in_force|string|true|Time in force Type<br/><br/> **Enum Value:**<br/> `Day` - Day Order<br/> `GTC` - Good Til Canceled Order<br/> `GTD` - Good Til Date Order|
|∟ expire_date|string|true|Long term order expire date, format: `YYYY-MM-DD`, example: `2022-12-05`.<br/><br/>When not a long term order, default value is empty string|
|∟ updated_at|string|true|Last updated time, formatted as a timestamp (second)|
|∟ trigger_at|string|true|Conditional order trigger time. formatted as a timestamp (second)|
|∟ trailing_amount|string|true|`TSLPAMT` order trailing amount.<br/><br/>When the order is not `TSLPAMT` order, value is empty string|
|∟ trailing_percent|string|true|`TSLPPCT` order trailing percent.<br/><br/>When the order is not `TSLPPCT` order, value is empty string|
|∟ limit_offset|string|true|`TSLPPCT` order limit offset amount.<br/><br/>When the order is not `TSLPPCT` order, value is empty string|
|∟ trigger_status|string|true|Conditional Order Trigger Status<br/> When an order is not a conditional order or a conditional order is not triggered, the trigger status is NOT_USED<br/><br/> **Enum Value**<br/> `NOT_USED`<br/> `DEACTIVE`<br /> `ACTIVE`<br /> `RELEASED`|
|∟ currency|string|true|Currency|
|∟ outside_rth|string|true|Enable or disable outside regular trading hours<br/> Default is `UnknownOutsideRth` when the order is not a US stock<br/><br/> **Enum Value:**<br/> `RTH_ONLY` - Regular trading hour only<br/> `ANY_TIME` - Any time<br/> `OVERNIGHT` - Overnight"|
|∟ remark|string|true|Remark|

### Order Details

This API is used for order detail query


## SDK

| Language | Link |
|---|---|
| Python | [TradeContext.order_detail](https://longportapp.github.io/openapi-sdk/python/trade_context/#longport.openapi.TradeContext.order_detail) |
| JavaScript | [TradeContext.order_detail](https://longportapp.github.io/openapi-sdk/js/classes/trade.tradecontext.html#order_detail) |
| Rust | [TradeContext::order_detail](https://longportapp.github.io/openapi-sdk/rust/longport/trade/struct.TradeContext.html#method.order_detail) |
| Go | [TradeContext.Order_detail](https://pkg.go.dev/github.com/longportapp/openapi-go/trade#TradeContext.Order_detail) |
| Java | [TradeContext.getOrder_detail](https://longportapp.github.io/openapi-sdk/java/com/longport/trade/TradeContext.html#getOrder_detail) |

## 

## Request

<table className="http-basic">
<tbody>
<tr><td className="http-basic-key">HTTP Method</td><td>GET</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 for specifying order ID query, for example: `701276261045858304` |

### Request Example

```python
from longport.openapi import TradeContext, Config

config = Config.from_env()
ctx = TradeContext(config)

resp = ctx.order_detail(
    order_id = "701276261045858304",
)
print(resp)
```

## Response

### Response Headers

- Content-Type: application/json

### Response Example

```json
{
  "code": 0,
  "message": "success",
  "data": {
    "order_id": "828940451093708800",
    "status": "FilledStatus",
    "stock_name": "Apple",
    "quantity": "10",
    "executed_quantity": "10",
    "price": "200.000",
    "executed_price": "164.660",
    "submitted_at": "1680863604",
    "side": "Buy",
    "symbol": "AAPL.US",
    "order_type": "LO",
    "last_done": "164.660",
    "trigger_price": "0.0000",
    "msg": "",
    "tag": "Normal",
    "time_in_force": "Day",
    "expire_date": "2023-04-10",
    "updated_at": "1681113000",
    "trigger_at": "0",
    "trailing_amount": "",
    "trailing_percent": "",
    "limit_offset": "",
    "trigger_status": "NOT_USED",
    "outside_rth": "ANY_TIME",
    "currency": "USD",
    "remark": "1680863603.927165",
    "free_status": "None",
    "free_amount": "",
    "free_currency": "",
    "deductions_status": "NONE",
    "deductions_amount": "",
    "deductions_currency": "",
    "platform_deducted_status": "NONE",
    "platform_deducted_amount": "",
    "platform_deducted_currency": "",
    "history": [
      {
        "price": "164.6600",
        "quantity": "10",
        "status": "FilledStatus",
        "msg": "Execution of 10",
        "time": "1681113000"
      },
      {
        "price": "200.0000",
        "quantity": "10",
        "status": "NewStatus",
        "msg": "",
        "time": "1681113000"
      }
    ],
    "charge_detail": {
      "items": [
        {
          "code": "BROKER_FEES",
          "name": "Broker Fees",
          "fees": []
        },
        {
          "code": "THIRD_FEES",
          "name": "Third-party Fees",
          "fees": []
        }
      ],
      "total_amount": "0",
      "currency": "USD"
    }
  }
}
```

### Response Status

| Status | Description | Schema |
|---|---|---|
| 200 | Order detail query successful | [order_detail_rsp](#schemaorder_detail_rsp) |
| 400 | Query failed, request parameter error. | None |

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

## Schemas

### order_detail_rsp

<a id="schemaorder_detail_rsp"></a>
<a id="schemaorder_detail_rsp"></a>

Order Information

|Name|Type|Required|Description|
|---|---|---|---|
|order_id|string|true|Order ID|
|status|string|true|[Order Status](../trade-definition#orderstatus)|
|stock_name|string|true|Stock Name|
|quantity|string|true|Order Quantity|
|executed_quantity|string|true|Executed Quantity<br/><br/>When the order is not executed, it is 0|
|price|string|true|Order Price<br/><br/>When the market price conditional order is not triggered, it is an empty string|
|executed_price|string|true|Execution Price<br/><br/>When the order is not executed, it is 0|
|submitted_at|string|true|Submitted Time|
|side|string|true|Order Side<br/><br/> **Enum Value:**<br/> `Buy`<br/> `Sell`|
|symbol|string|true|Stock symbol, use `ticker.region` format, example: `AAPL.US`|
|order_type|string|true|[Order Type](../trade-definition#ordertype)|
|last_done|string|true|Last done.<br/><br/>when the order is not filled, value is empty string|
|trigger_price|string|true|`LIT` / `MIT` Order Trigger Price.<br/><br/>When the order is not `LIT` / `MIT` order, value is empty string|
|msg|string|true|Rejected message or remark, default value is empty string.|
|tag|string|true|Order tag<br/><br/> **Enum Value**<br/> `Normal` - Normal Order<br/> `GTC` - Long term Order<br/> `Grey` - Grey Order|
|time_in_force|string|true|Time in force Type<br/><br/> **Enum Value:**<br/> `Day` - Day Order<br/> `GTC` - Good Til Canceled Order<br/> `GTD` - Good Til Date Order|
|expire_date|string|true|Long term order expire date, format: `YYYY-MM-DD`, example: `2022-12-05`.<br/><br/> When not a long term order, default value is empty string|
|updated_at|string|true|Last updated time, formatted as a timestamp (second)|
|trigger_at|string|true|Conditional order trigger time. formatted as a timestamp (second)|
|trailing_amount|string|true|`TSLPAMT` order trailing amount.<br/><br/>When the order is not `TSLPAMT` order, value is empty string|
|trailing_percent|string|true|`TSLPPCT` order trailing percent.<br/><br/>When the order is not `TSLPPCT` order, value is empty string|
|limit_offset|string|true|`TSLPPCT` order limit offset amount.<br/><br/>When the order is not `TSLPPCT` order, value is empty string|
|trigger_status|string|true|Conditional Order Trigger Status<br/> When an order is not a conditional order or a conditional order is not triggered, the trigger status is NOT_USED<br/><br/> **Enum Value**<br/> `NOT_USED`<br/> `DEACTIVE`<br /> `ACTIVE`<br /> `RELEASED`|
|currency|string|true|Currency|
|outside_rth|string|true|Enable or disable outside regular trading hours<br/> Default is `UnknownOutsideRth` when the order is not a US stock<br/><br/> **Enum Value:**<br/> `RTH_ONLY` - Regular trading hour only<br/> `ANY_TIME` - Any time<br/> `OVERNIGHT` - Overnight"|
|remark|string|true|Remark|
|free_status|string|true|Commission-free Status, default value is None<br/><br/> **Enum Value:**<br/> `None` - None<br/> `Calculated` - Commission-free amount to be calculated<br/> `Pending` - Pending commission-free<br/> `Ready` - Commission-free applied|
|free_amount|string|true|Commission-free amount, default value is empty string.|
|free_currency|string|true|Commission-free currency, default value is empty string.|
|deductions_status|string|true|Deduction status/Cashback Status, default value is NONE<br/><br/> **Enum Value:**<br/> `NONE` - Pending Settlement <br/> `NO_DATA` - Settled with no data<br/> `PENDING` - Settled and pending distribution<br/> `DONE` - Settled and distributed|
|deductions_amount|string|true|Deduction amount, default value is empty string.|
|deductions_currency|string|true|Deduction currency, default value is empty string.|
|platform_deducted_status|string|true|Platform fee deduction status/Cashback Status, default value is NONE<br/><br/> **Enum Value:**<br/> `NONE` - Pending Settlement <br/> `NO_DATA` - Settled with no data<br/> `PENDING` - Settled and pending distribution<br/> `DONE` - Settled and distributed|
|platform_deducted_amount|string|true|Platform fee deduction amount, default value is empty string.|
|platform_deducted_currency|string|true|Platform fee deduction currency, default value is empty string.|
|history|object[]|true|Order history details|
|∟ price|string|true|Executed price for executed orders, submitted price for expired, canceled, rejected orders, etc.|
|∟ quantity|string|true|Executed quantity for executed orders, remaining quantity for expired, canceled, rejected orders, etc.|
|∟ status|string|true|Order status|
|∟ msg|string|true|Execution or error message|
|∟ time|string|true|Occurrence time|
|charge_detail|object|true|Order charges|
|∟ total_amount|string|true|Total charges amount|
|∟ currency|string|true|Settlement currency|
|∟ items|object[]|true|Order charge details|
|∟∟ code|string|true|Charge category code<br/><br/> **Enum Value:**<br/> `UNKNOWN`<br/> `BROKER_FEES`<br/> `THIRD_FEES`|
|∟∟ name|string|true|Charge category name|
|∟∟ fees|object[]|true|Charge details|
|∟∟∟ code|string|true|Charge code|
|∟∟∟ name|string|true|Charge name|
|∟∟∟ amount|string|true|Charge amount|
|∟∟∟ currency|string|true|Charge currency|

### Replace Order

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


## SDK

| Language | Link |
|---|---|
| Python | [TradeContext.replace_order](https://longportapp.github.io/openapi-sdk/python/trade_context/#longport.openapi.TradeContext.replace_order) |
| JavaScript | [TradeContext.replace_order](https://longportapp.github.io/openapi-sdk/js/classes/trade.tradecontext.html#replace_order) |
| Rust | [TradeContext::replace_order](https://longportapp.github.io/openapi-sdk/rust/longport/trade/struct.TradeContext.html#method.replace_order) |
| Go | [TradeContext.Replace_order](https://pkg.go.dev/github.com/longportapp/openapi-go/trade#TradeContext.Replace_order) |
| Java | [TradeContext.getReplace_order](https://longportapp.github.io/openapi-sdk/java/com/longport/trade/TradeContext.html#getReplace_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 |
| 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) |

### Request Example

```python
from decimal import Decimal
from longport.openapi import TradeContext, Config

config = Config.from_env()
ctx = TradeContext(config)

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

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

### Submit Order

This API is used for placing orders for Hong Kong and US stocks, warrants, and options.


## SDK

| Language | Link |
|---|---|
| Python | [TradeContext.submit_order](https://longportapp.github.io/openapi-sdk/python/trade_context/#longport.openapi.TradeContext.submit_order) |
| JavaScript | [TradeContext.submit_order](https://longportapp.github.io/openapi-sdk/js/classes/trade.tradecontext.html#submit_order) |
| Rust | [TradeContext::submit_order](https://longportapp.github.io/openapi-sdk/rust/longport/trade/struct.TradeContext.html#method.submit_order) |
| Go | [TradeContext.Submit_order](https://pkg.go.dev/github.com/longportapp/openapi-go/trade#TradeContext.Submit_order) |
| Java | [TradeContext.getSubmit_order](https://longportapp.github.io/openapi-sdk/java/com/longport/trade/TradeContext.html#getSubmit_order) |

## Request

<table className="http-basic">
<tbody>
<tr><td className="http-basic-key">HTTP Method</td><td>POST</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                                                                                                                                                                    |
|--------------------|--------|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| symbol             | string | YES      | Stock symbol, use `ticker.region` format, example: `AAPL.US`                                                                                                                   |
| order_type         | string | YES      | [Order Type](../trade-definition#ordertype)                                                                                                                                    |
| submitted_price    | string | NO       | Submitted price, example: `388.5`<br/><br/> `LO` / `ELO` / `ALO` / `ODD` / `LIT` Order Required                                                                                |
| submitted_quantity | string | YES      | Submitted quantity, example: `100`                                                                                                                                             |
| 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                                                                                                             |
| trailing_amount    | string | NO       | Trailing amount<br/><br/> `TSLPAMT` Order Required                                                                                                                             |
| trailing_percent   | string | NO       | Trailing percent<br/><br/> `TSLPPCT` Order Required                                                                                                                            |
| expire_date        | string | NO       | Long term order expire date, format `YYYY-MM-DD`, example: `2022-12-05`<br/><br/> Required when `time_in_force` is `GTD`                                                       |
| side               | string | YES      | Order Side<br/><br/> **Enum Value:**<br/> `Buy`<br/> `Sell`                                                                                                                    |
| outside_rth        | string | NO       | Enable or disable outside regular trading hours<br/><br/> **Enum Value:**<br/> `RTH_ONLY` - regular trading hour only<br/> `ANY_TIME` - any time<br/> `OVERNIGHT` - Overnight" |
| time_in_force      | string | YES      | Time in force Type<br/><br/> **Enum Value:**<br/> `Day` - Day Order<br/> `GTC` - Good Til Canceled Order<br/> `GTD` - Good Til Date Order                                      |
| remark             | string | NO       | remark (Maximum 64 characters)                                                                                                                                                 |

## Examples

For the sake of understanding, we will use Python as an example to demonstrate how to place orders for some scenarios.

### Open Position Buy

We expect to buy 100 shares of `700.HK` at a price of 380 HKD, and set it to be "order valid for the day".

```py
from decimal import Decimal
from longport.openapi import TradeContext, Config, OrderType, OrderSide, TimeInForceType

# Load configuration from environment variables
config = Config.from_env()

# Create a context for trade APIs
ctx = TradeContext(config)

resp = ctx.submit_order(
    "700.HK",
    OrderType.LO,
    OrderSide.Buy,
    Decimal(100),
    TimeInForceType.Day,
    submitted_price=Decimal(380),
    remark="Hello from Python SDK",
)
```

In this case:

- `OrderSide.Buy` - Is equivalent to "Buy" side of the order
- `OrderType.LO` - Is equivalent to "Limit Order", when it is a limit order, we need to pass the `submitted_price` parameter
- `TimeInForceType.Day` - Represents that the order is valid for the day

### Close Position Sell

We submit a market order to sell 100 shares of `700.HK`, and set it to be "order valid for the day".

```py
ctx.submit_order(
    "700.HK",
    OrderType.MO,
    OrderSide.Sell,
    Decimal(100),
    TimeInForceType.Day,
    remark="Hello from Python SDK",
)
```

- `OrderType.MO` - Represents a "Market Order"
- `OrderSide.Sell` - Represents "Sell" side of the order

### Stop Loss and Take Profit

> This corresponds to the "Buy if Touched" and "Sell if Touched" order types on our client's order placement interface.

Assuming we want to buy 100 shares of `700.HK` when the price reaches 380 HKD, and set it to be "Order valid before cancellation".

:::tip
**Order valid before cancellation** - This means that the order will remain valid until it is executed or cancelled.
:::

```py
ctx.submit_order(
    "NVDA.US",
    OrderType.LIT,
    OrderSide.Sell,
    Decimal(100),
    TimeInForceType.GoodTilCanceled,
    Decimal("999.00"),
    trigger_price=Decimal("1000.00"),
    remark="Hello from Python SDK",
)
```

- `OrderType.LIT` - Represents a "Limit If Touched"
- `TimeInForceType.GoodTilCanceled` - Represents that the order is valid before cancellation or until it is executed
- `trigger_price` - The parameter is used to set the trigger price. When the market price reaches the trigger price, the order will be submitted

### Trailing Stop Loss and Take Profit

> This corresponds to the "Trail to Buy" and "Trail to Sell" order types on our client's order placement interface.

Sometimes we need to set a trailing stop loss and take profit to protect our profits.

Assuming we hold 100 shares of `NVDA.US`, we submit a conditional order to monitor the market price changes of `NVDA.US`. When the market price falls back 0.5% from the highest point after the order is placed, we will reduce the price by 1.2 USD and place a limit order. The order is valid until June 30.

We can do like this:

```py
ctx.submit_order(
    "NVDA.US",
    OrderType.TSLPPCT,
    OrderSide.Sell,
    Decimal(100),
    TimeInForceType.GoodTilDate,
    expire_date=datetime.date(2024, 6, 30),
    trailing_percent=Decimal("0.5"),
    limit_offset=Decimal("1.2"),
    remark="Hello from Python SDK",
)
```

- `OrderType.TSLPPCT` - Represents a "Trailing Limit If Touched (Trailing Percent)", if you want to use "Trailing Amount", you can use `TSLPAMT`
- `TimeInForceType.GoodTilDate` - Represents that the order is valid until the specified date, when passing this parameter, we also need to pass the `expire_date` parameter
- `expire_date` - Is used to set the expiration date of the order
- `trailing_percent` - Used to set the tracking percentage, here `0.5` means 0.5%
- `limit_offset` - The parameter is used to set the specified spread, here `1.2` means 1.2 USD. If you do not need to specify the spread, you can pass `0` or not pass it.

When we subnmit such a conditional order, if the market price of `NVDA.US` falls back 0.5% from the highest point after the order is placed, for example, the highest point is `1,100 USD`, falling back 0.5% is `1,094.5 USD`, then our order will be placed a `LIMIT ORDER` at a price of `1,094.5 USD - 1.2 = 1,093.3 USD`.

### Get Today Deals



### Get Today Order

This API is used to get today order or get order by order id.


## SDK

| Language | Link |
|---|---|
| Python | [TradeContext.today_orders](https://longportapp.github.io/openapi-sdk/python/trade_context/#longport.openapi.TradeContext.today_orders) |
| JavaScript | [TradeContext.today_orders](https://longportapp.github.io/openapi-sdk/js/classes/trade.tradecontext.html#today_orders) |
| Rust | [TradeContext::today_orders](https://longportapp.github.io/openapi-sdk/rust/longport/trade/struct.TradeContext.html#method.today_orders) |
| Go | [TradeContext.Today_orders](https://pkg.go.dev/github.com/longportapp/openapi-go/trade#TradeContext.Today_orders) |
| Java | [TradeContext.getToday_orders](https://longportapp.github.io/openapi-sdk/java/com/longport/trade/TradeContext.html#getToday_orders) |

## 

## Request

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

### Parameters

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

| Name | Type | Required | Description |
|---|---|---|---|
| symbol | string | NO | Stock symbol, use `ticker.region` format, example: `AAPL.US` |
| status | string[] | NO | [Order status](../trade-definition#orderstatus)<br/><br/>example: `status=FilledStatus&status=NewStatus` |
| side | string | NO | Order side<br/><br/> **Enum Value:**<br/> `Buy`<br/> `Sell` |
| market | string | NO | Market<br/><br/> **Enum Value:**<br/> `US` - United States of America Market<br/> `HK` - Hong Kong Market |
| order_id | string | NO | Order ID, example: `701276261045858304` |

### Request Example

```python
from longport.openapi import TradeContext, Config, OrderStatus, OrderSide, Market

config = Config.from_env()
ctx = TradeContext(config)

resp = ctx.today_orders(
    symbol = "700.HK",
    status = [OrderStatus.Filled, OrderStatus.New],
    side = OrderSide.Buy,
    market = Market.HK,
)
print(resp)
```

## Response

### Response Headers

- Content-Type: application/json

### Response Example

```json
{
  "code": 0,
  "message": "success",
  "data": {
    "orders": [
      {
        "currency": "HKD",
        "executed_price": "0.000",
        "executed_quantity": "0",
        "expire_date": "",
        "last_done": "",
        "limit_offset": "",
        "msg": "",
        "order_id": "706388312699592704",
        "order_type": "ELO",
        "outside_rth": "UnknownOutsideRth",
        "price": "11.900",
        "quantity": "200",
        "side": "Buy",
        "status": "RejectedStatus",
        "stock_name": "Bank of East Asia Ltd/The",
        "submitted_at": "1651644897",
        "symbol": "23.HK",
        "tag": "Normal",
        "time_in_force": "Day",
        "trailing_amount": "",
        "trailing_percent": "",
        "trigger_at": "0",
        "trigger_price": "",
        "trigger_status": "NOT_USED",
        "updated_at": "1651644898",
        "remark": ""
      }
    ]
  }
}
```

### Response Status

| Status | Description | Schema |
|---|---|---|
| 200 | Get Today Orders Success | [today_orders_rsp](#schematoday_orders_rsp) |
| 400 | The query failed with an error in the request parameter. | None |

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

## Schemas

### today_orders_rsp

<a id="schematoday_orders_rsp"></a>
<a id="schematoday_orders_rsp"></a>

|Name|Type|Required|Description|
|---|---|---|---|
|orders|object[]|false|Order Detail|
|∟ order_id|string|true|Order ID|
|∟ status|string|true|[Order Status](../trade-definition#orderstatus)|
|∟ stock_name|string|true|Stock Name|
|∟ quantity|string|true|Submitted Quantity|
|∟ executed_quantity|string|true|Executed Quantity.<br/><br/>when the order is not filled, value is 0|
|∟ price|string|true|Submitted Price.<br/><br/>when market condition order is not triggered, value is empty string|
|∟ executed_price|string|true|Executed Price.<br/><br/>when the order is not filled, value is 0|
|∟ submitted_at|string|true|Submitted Time|
|∟ side|string|true|Order Side<br/><br/> **Enum Value:**<br/> `Buy`<br/> `Sell`|
|∟ symbol|string|true|Stock symbol, use `ticker.region` format, example: `AAPL.US`|
|∟ order_type|string|true|[Order Type](../trade-definition#ordertype)|
|∟ last_done|string|true|Last done.<br/><br/>when the order is not filled, value is empty string|
|∟ trigger_price|string|true|`LIT` / `MIT` Order Trigger Price.<br/><br/>When the order is not `LIT` / `MIT` order, value is empty string|
|∟ msg|string|true|Rejected message or remark, default value is empty string.|
|∟ tag|string|true|Order tag<br/><br/> **Enum Value**<br/> `Normal` - Normal Order<br/> `GTC` - Long term Order<br/> `Grey` - Grey Order|
|∟ time_in_force|string|true|Time in force Type<br/><br/> **Enum Value:**<br/> `Day` - Day Order<br/> `GTC` - Good Til Canceled Order<br/> `GTD` - Good Til Date Order|
|∟ expire_date|string|true|Long term order expire date, format: `YYYY-MM-DD`, example: `2022-12-05`.<br/><br/>When not a long term order, default value is empty string|
|∟ updated_at|string|true|Last updated time, formatted as a timestamp (second)|
|∟ trigger_at|string|true|Conditional order trigger time. formatted as a timestamp (second)|
|∟ trailing_amount|string|true|`TSLPAMT` order trailing amount.<br/><br/>When the order is not `TSLPAMT` order, value is empty string|
|∟ trailing_percent|string|true|`TSLPPCT` order trailing percent.<br/><br/>When the order is not `TSLPPCT` order, value is empty string|
|∟ limit_offset|string|true|`TSLPAMT` / `TSLPPCT` order limit offset amount.<br/><br/>When the order is not `TSLPAMT` / `TSLPPCT` order, value is empty string|
|∟ trigger_status|string|true|Conditional Order Trigger Status<br/> When an order is not a conditional order or a conditional order is not triggered, the trigger status is NOT_USED<br/><br/> **Enum Value**<br/> `NOT_USED`<br/> `DEACTIVE`<br /> `ACTIVE`<br /> `RELEASED`|
|∟ currency|string|true|Currency|
|∟ outside_rth|string|true|Enable or disable outside regular trading hours<br/> Default is `UnknownOutsideRth` when the order is not a US stock<br/><br/> **Enum Value:**<br/> `RTH_ONLY` - Regular trading hour only<br/> `ANY_TIME` - Any time<br/> `OVERNIGHT` - Overnight"|
|∟ remark|string|true|Remark|

### Withdraw Order

This API is used to withdraw an open order.


## SDK

| Language | Link |
|---|---|
| Python | [TradeContext.cancel_order](https://longportapp.github.io/openapi-sdk/python/trade_context/#longport.openapi.TradeContext.cancel_order) |
| JavaScript | [TradeContext.cancel_order](https://longportapp.github.io/openapi-sdk/js/classes/trade.tradecontext.html#cancel_order) |
| Rust | [TradeContext::cancel_order](https://longportapp.github.io/openapi-sdk/rust/longport/trade/struct.TradeContext.html#method.cancel_order) |
| Go | [TradeContext.Cancel_order](https://pkg.go.dev/github.com/longportapp/openapi-go/trade#TradeContext.Cancel_order) |
| Java | [TradeContext.getCancel_order](https://longportapp.github.io/openapi-sdk/java/com/longport/trade/TradeContext.html#getCancel_order) |

## 

## Request

<table className="http-basic">
<tbody>
<tr><td className="http-basic-key">HTTP Method</td><td>DELETE</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 |

### Request Example

```python
from longport.openapi import TradeContext, Config

config = Config.from_env()
ctx = TradeContext(config)

ctx.cancel_order("709043056541253632")
```

## 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 withdrawal was rejected with an incorrect request parameter. | None |

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